Why does setText in the TextField doesn't work? - gwt

Why does this method doesn't save the new selected categories. is there something wrong with my codes?
catCon = new TextField();
rowEditing.addEditor(catConfig, catCon);
this is the code for setting the catCon:
TextButton save = new TextButton("Save");
save.addSelectHandler(new SelectEvent.SelectHandler() {
#Override
public void onSelect(SelectEvent event) {
selectedItems = new LinkedList<Short>();
for (int i = 0; i < toCat.size(); i++) {
selectedItems.add(toCat.get(i).getIDCategory());
}
Collections.sort(selectedItems);
newSelectedItems = selectedItems.toString().replace(",", "-").replace("[", "").replace("]", "").replace(" ", "");
msg = new MessageBox("SELECTED ITEMSSSSSSSSS: " + selectedItems.size() + " " + newSelectedItems);;
msg.show();
catCon.setText(newSelectedItems);
hide();
}
});
and this is where the saving of the commited changes:
rowEditing.getSaveButton().addSelectHandler(new SelectEvent.SelectHandler() {
#Override
public void onSelect(SelectEvent event) {
store.commitChanges();
service.saveUserRights(store.get(index), new AsyncCallback<Boolean>() {
#Override
public void onFailure(Throwable caught) {
msg = new MessageBox("Error", caught.getMessage());
msg.show();
}
#Override
public void onSuccess(Boolean result) {
if (result) {
msg = new MessageBox("Information", "Changes saved.");
msg.show();
service.getURListGrid(new AsyncCallback<List<UserRights>>() {
#Override
public void onFailure(Throwable caught) {
MessageBox msg = new MessageBox("Error", caught.getMessage());
msg.show();
}
#Override
public void onSuccess(List<UserRights> result) {
store = new ListStore<UserRights>(properties.idRight());
store.addAll(result);
grid.reconfigure(store, cm);
}
});
} else {
msg = new MessageBox("Error", "Failed to save changes.");
msg.show();
}
}
});
}
});
When I am going to set the catCon there will no be changes of the data but when I manually type the categories there will be a change. Can somebody help me?

In order for me to save the current categories is to get the index of the store and set the category to the newSelectedItem
store.get(index).setCategories(newSelectedItems);
I hope this will help to the people who has the same problem as mine.

Related

RXJava Observable emit items when subscribe with Observer as anonymous type ONLY

When I create a new Observer as anonymous type It works Fine:
Observable<List<Post>> postsListObservable = mApplicationAPI.getPosts();
postsListObservable.
subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread()).subscribe( new Observer<List<Post>>() {
#Override
public void onSubscribe(Disposable d) {
Log.i("ZOKa", "onSubscribe: ");
}
#Override
public void onNext(List<Post> posts) {
Log.i("ZOKa", "onNext: " + posts.size());
}
#Override
public void onError(Throwable e) {
Log.i("ZOKa", "onError: " + e.getMessage());
}
#Override
public void onComplete() {
Log.i("ZOKa", "onComplete: ");
}
});
When I create the Observer as a Dynamic Type it doesn't emit data
Observable<List<Post>> postsListObservable = mApplicationAPI.getPosts();
postsListObservable.
subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread());
Observer<List<Post>> observer = new Observer<List<Post>>() {
#Override
public void onSubscribe(Disposable d) {
Log.i("ZOKa", "onSubscribe: ");
}
#Override
public void onNext(List<Post> posts) {
Log.i("ZOKa", "onNext: " + posts.size());
}
#Override
public void onError(Throwable e) {
Log.i("ZOKa", "onError: " + e.getMessage());
}
#Override
public void onComplete() {
Log.i("ZOKa", "onComplete: ");
}
};
postsListObservable.subscribe(observer);
Logcat for the first code snippet:
com.tripleService.basesetupfordi/I/ZOKa: onSubscribe:
com.tripleService.basesetupfordi/I/ZOKa: onNext: 100:
com.tripleService.basesetupfordi/I/ZOKa: onComplete:
Logcat for the second one:
com.tripleService.basesetupfordi/I/ZOKa: onError: null
So, What is the diff in between?
That's because Operators return new observables, but they don't modify the observable that they were called on. subscribeOn and observeOn in the second example has no impact on the postsListObservable and the observer.
Following should work:
Observable<List<Post>> postsListObservable = mApplicationAPI.getPosts();
Observable<List<Post>> postsListObservable2 = postsListObservable.
subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread());
Observer<List<Post>> observer = new Observer<List<Post>>() {
...
};
postsListObservable2.subscribe(observer);
or
Observable<List<Post>> postsListObservable = mApplicationAPI.getPosts();
Observer<List<Post>> observer = new Observer<List<Post>>() {
...
};
postsListObservable.
subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread()).subscribe(observer);

How to reopen/prevent closing of ControlsFX LoginDialog on failed login?

In my application, the first I do is request the user to login using the controlsFX LoginDialog. If the login is successful, I display the application, however if it fails the login window will close.
I would rather the login window stay open to allow the user to attempt to login again.
public void start(Stage stage) throws Exception {
LoginDialog ld = new LoginDialog(new Pair<String, String>("", ""), new Callback<Pair<String,String>, Void>() {
#Override
public Void call(Pair<String, String> info) {
boolean success = login(info.getKey(), info.getValue());
if(success){
openDriverWindow(stage);
}else {
//Display error message
}
return null;
}
});
ld.show();
}
If the login is unsuccessful, the dialog closes - which requires the user to reopen the application.
You can use Dialog from JDK8u40 which will be released at march 2015 or use dialogs from ConrolsFX (openjfx-dialogs-1.0.2). There is a code to implement Dialog which will not be closed until authentication is not passed.
// Create the custom dialog.
Dialog<Pair<String, String>> dialog = new Dialog<>();
dialog.setTitle("Login Dialog");
dialog.setHeaderText("Look, a Custom Login Dialog");
dialog.setGraphic(new ImageView(this.getClass().getResource("login.png").toString()));
// Set the button types.
ButtonType loginButtonType = new ButtonType("Login", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL);
// Create the username and password labels and fields.
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 150, 10, 10));
TextField username = new TextField();
username.setPromptText("Username");
PasswordField password = new PasswordField();
password.setPromptText("Password");
grid.add(new Label("Username:"), 0, 0);
grid.add(username, 1, 0);
grid.add(new Label("Password:"), 0, 1);
grid.add(password, 1, 1);
// Enable/Disable login button depending on whether a username was entered.
Button loginButton = (Button)dialog.getDialogPane().lookupButton(loginButtonType);
loginButton.setDisable(true);
**// Prevent closing dialog if not authenticated**
loginButton.addEventFilter(ActionEvent.ACTION, (event) -> {
if (!authenticated()) {
event.consume();
}
});
// Do some validation (using the Java 8 lambda syntax).
username.textProperty().addListener((observable, oldValue, newValue) -> {
loginButton.setDisable(newValue.trim().isEmpty());
});
dialog.getDialogPane().setContent(grid);
// Request focus on the username field by default.
Platform.runLater(() -> username.requestFocus());
// Convert the result to a username-password-pair when the login button is clicked.
dialog.setResultConverter(dialogButton -> {
if (dialogButton == loginButtonType) {
return new Pair<>(username.getText(), password.getText());
}
return null;
});
Optional<Pair<String, String>> result = dialog.showAndWait();
result.ifPresent(usernamePassword -> {
System.out.println("Username=" + usernamePassword.getKey() + ", Password=" + usernamePassword.getValue());
});
this example was given from this article where you can find many useful examples
Try this:
public class Main extends Application{
private boolean login(String key, String value){
Pair loginData = new Pair<String, String>("test", "test");
if (loginData.getKey().equals(key) && loginData.getValue().equals(value)) {
return true;
}
else {
//Вывести Alert.
Platform.runLater(new Runnable() {
#Override
public void run() {
try {
Alert alert = new Alert(Alert.AlertType.ERROR, "Вы ввели неправильное имя или пароль");
alert.setTitle("Error");
alert.showAndWait();
} catch (Exception e) {
e.printStackTrace();
}
}
});
return false;
}
}
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Terminal Kuban-electro");
getLogin(primaryStage);
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent t) {
System.exit(0);
}
});
}
private void getLogin(Stage primaryStage){
LoginDialog ld = new LoginDialog(new Pair<String, String>("", ""), new Callback<Pair<String, String>, Void>() {
#Override
public Void call(Pair<String, String> info) {
boolean success = login(info.getKey(), info.getValue());
if (success) {
Scene scene = null;
try {
scene = new Scene(FXMLLoader.load(getClass().getClassLoader().getResource("fxml/main.fxml")));
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
}
} else {
getLogin(primaryStage);
}
return null;
}
});
ld.setHeaderText("Введите имя пользователя и пароль");
ld.setTitle("Авторизация");
ld.show();
}
public static void main(String[] args) throws MalformedURLException {
//Инициализация формы в потоке
Thread myThready = new Thread(() -> {
launch(args);
});
myThready.start();
}
}

DoubleClick on a row in JfaceTable to get the details of object on that row

In eclipse e4.
On double clicking on a row in jface table I want to see the data on that row as a dialog.
Existing Code
orgTable.addDoubleClickListener(new IDoubleClickListener() {
#Override
public void doubleClick(DoubleClickEvent event) {
System.out.println("Double CLikc works");
}
});
OrgTable.addDoubleClickListener(new IDoubleClickListener() {
#Override
public void doubleClick(DoubleClickEvent event) {
System.out.println("Double CLikc works");
IStructuredSelection sel = (IStructuredSelection) event.getSelection();
OrgDetails org = (OrgDetails) sel.getFirstElement();
if(org != null){
System.out.println("Double-click on : "+ org.getOrgName()+ " " + org.getTin());
}
System.out.println(orgTable.getElementAt());
}
});

My custome list view not update with new data

Hello I created a custom list view and for update used notifyDataSetChanged() method but my list not updated. please help me.
this is my source code
public class fourthPage extends ListActivity {
ListingFeedParser ls;
List<Listings> data;
EditText SearchText;
Button Search;
private LayoutInflater mInflater;
private ProgressDialog progDialog;
private int pageCount = 0;
String URL;
ListViewListingsAdapter adapter;
Message msg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bundle b = getIntent().getExtras();
URL = b.getString("URL");
Log.i("Ran->URL", "->" + URL);
MYCITY_STATIC_DATA.fourthPage_main_URL = URL;
final ListingFeedParser lf = new ListingFeedParser(URL);
Search = (Button) findViewById(R.id.searchButton);
SearchText = (EditText) findViewById(R.id.search);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(SearchText.getWindowToken(), 0);
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
try {
progDialog = ProgressDialog.show(this, "",
"Loading please wait....", true);
progDialog.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
try {
data = lf.parse();
} catch (Exception e) {
e.printStackTrace();
}
msg = new Message();
msg.what = 1;
fourthPage.this._handle.sendMessage(msg);
}
}).start();
Search.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SearchText = (EditText) findViewById(R.id.search);
if (SearchText.getText().toString().equals(""))
return;
CurrentLocationTimer myLocation = new CurrentLocationTimer();
LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(final Location location) {
Toast.makeText(
getApplicationContext(),
location.getLatitude() + " "
+ location.getLongitude(),
Toast.LENGTH_LONG).show();
String URL = "http://75.125.237.76/phone_feed_2_point_0_test.php?"
+ "lat="
+ location.getLatitude()
+ "&lng="
+ location.getLongitude()
+ "&page=0&search="
+ SearchText.getText().toString();
Log.e("fourthPage.java Search URL :->", "" + URL);
Bundle b = new Bundle();
b.putString("URL", URL);
Intent it = new Intent(getApplicationContext(),
fourthPage.class);
it.putExtras(b);
startActivity(it);
}
};
myLocation.getLocation(getApplicationContext(),
locationResult);
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"No data available for this request", Toast.LENGTH_LONG)
.show();
}
}
private Handler _handle = new Handler() {
#Override
public void handleMessage(Message msg) {
progDialog.dismiss();
if (msg.what == 1) {
if (data.size() == 0 || data == null) {
Toast.makeText(getApplicationContext(),
"No data available for this request",
Toast.LENGTH_LONG).show();
}
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
adapter = new ListViewListingsAdapter(getApplicationContext(),
R.layout.list1, R.id.title, data, mInflater);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
adapter.notifyDataSetChanged();
} else {
Toast.makeText(getApplicationContext(),
"Error in retrieving the method", Toast.LENGTH_SHORT)
.show();
}
}
};
public void onListItemClick(ListView parent, View v, int position, long id) {
// remember i m going from bookmark list
MYCITY_STATIC_DATA.come_from_bookmark = false;
Log.i("4thPage.java - MYCITY_STATIC_DATA.come_from_bookmark",
"set false - > check" + MYCITY_STATIC_DATA.come_from_bookmark);
Listings sc = (Listings) this.getListAdapter().getItem(position);
if (sc.getName().equalsIgnoreCase("SEE MORE...")) {
pageCount = pageCount + 1;
final ListingFeedParser lf = new ListingFeedParser((URL.substring(
0, URL.length() - 1)) + pageCount);
try {
progDialog = ProgressDialog.show(this, "",
"Loading please wait....", true);
progDialog.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
data.remove(data.size() - 1);
data.addAll(lf.parse());
Message msg = new Message();
msg.what = 1;
fourthPage.this._handle.sendMessage(msg);
}
}).start();
} catch (Exception e) {
pageCount = pageCount - 1;
// TODO: handle exception
Toast newToast = Toast.makeText(this, "Error in getting Data",
Toast.LENGTH_SHORT);
}
} else {
Bundle b = new Bundle();
b.putParcelable("listing", sc);
Intent it = new Intent(getApplicationContext(),
FifthPageTabbed.class);
it.putExtras(b);
startActivity(it);
}
}
#Override
public void onBackPressed() {
setResult(0);
finish();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.e("RESUME:-)", "4th Page onResume");
try {
//adapter.notifyDataSetChanged();
//setListAdapter(adapter);
//getListView().setTextFilterEnabled(true);
} catch (Exception e) {
Log.e("EXCEPTION in 4th page",
"in onResume msg:->" + e.getMessage());
}
}
}
Do not re-create the object of ArrayList or Array you are passing to adapter, just modify same ArrayList or Array again. and also when array or arrylist size not changed after you modify adapter then in that case notifydatasetchange will not work.
In shot it is work only when array or arraylist size increases or decreases.
What version of Android are you targeting? The latest version seems to have revised how notifyDataSetChanged() works. If you target sdk 11 it might work?
Also, there seems to be a different (and very thorough answer) to this question in another post:
notifyDataSetChanged example

Refresh ListView when Device receives GCM IntentService Message

My app is able to receive messages from GCM and saves the messages to the SQLlite database on the phone. The messages are viewable in a activity that has a listview.
In the code below, the onPause() function refreshes the listView. This is not a good implementation because it only works if the activity is not displayed at the time of the update. If the activity is displayed at the time of an update, the list is static and does not update.
Questions:
How to I update the listview when the activity is being displayed? Or is there a way to use a background service to update the adapter, so that whenever the activity is displayed, it always shows the newest data.
is this kind of functionality currently not possible with android and I'll need to implement something else like 'pull-to-refresh'?
refreshing listview in OnResume() crashes the application, and shows a null pointer exception.
Activity:
public class NotesView extends Activity implements OnItemClickListener {
ListView listView;
NoteAdapter objAdapter;
NotificationsDatabase db = new NotificationsDatabase(this);
List<Notes> listAlerts;
String note;
String time;
TextView noteView;
TextView timeView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
new MyTask().execute();
}
// My AsyncTask start...
class MyTask extends AsyncTask<Void, Void, List<Notes>> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NotesView.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
if (isCancelled()) {
this.cancel(true);
}
}
#Override
protected List<Notes> doInBackground(Void... params) {
db.open();
listAlerts = db.getData();
if (isCancelled()) {
this.cancel(true);
}
return null;
}
protected void onPostExecute(List<Notes> alerts) {
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
db.close();
setAdapterToListview();
}
}// end myTask
public void setAdapterToListview() {
objAdapter = new NoteAdapter(NotesView.this, R.layout.row_notes, listAlerts);
objAdapter.sortByNoteDesc();
objAdapter.notifyDataSetChanged();
listView.setAdapter(objAdapter);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
Intent intent = new Intent(
NotesView.this.getApplicationContext(),
TabBarExample.class);
intent.putExtra("goToTab", "Alerts");
startActivity(intent);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void onItemClick(AdapterView<?> parent, View viewDel, int position,
long id) {
for (int i = 0; i < 1; i++) {
Notes item = listAlerts.get(position);
int ids = item.getId();
note = item.getNote();
time = item.getTimeStamp();
}
System.out.println(note + " " + time);
//
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setAdapter(null);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
new MyTask().execute();
}
#Override
protected void onDestroy() {
}
}
Code snippets From GCMIntentService
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
//String message = getString(R.string.gcm_message);
System.out.println("onMessage: ");
Bundle extras = intent.getExtras();
String message = extras.getString("message");
String event_id_from_server = extras.getString("server_id");
// displayMessage(context, message);
generateNotification(context, message);
saveMsg(message);
System.out.println("server id is " + event_id_from_server);
if (event_id_from_server != null) {
updateLocalDatabase(event_id_from_server);
}
}
public void saveMsg(String msg) {
boolean worked = true;
try {
NotificationsDatabase entry = new NotificationsDatabase(GCMIntentService.this);
entry.open();
java.util.Date date = new java.util.Date();
Timestamp x = new Timestamp(date.getTime());
String timeStamp = x.toLocaleString();
entry.createEntry(msg, timeStamp);
entry.close();
//update adapter service
} catch (Exception e) {
worked = false;
String error = e.toString();
System.out.println(error);
} finally {
if (worked) {
}
}
}
I cleaned up your code a little bit. Basically all the view assignments should be done once in onCreate, while the loading of the data should be done in onResume(). See if this helps:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setAdapter(null);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
}
#Override
protected void onResume() {
super.onResume();
new MyTask().execute();
}
#Override
protected void onPause() {
super.onPause();
}