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

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();
}
}

Related

Why does setText in the TextField doesn't work?

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.

Progress Dialog on Rajawali Vuforia example

It is possible to show progress dialog when loading the .obj model. I tried to call the ProgressDialog in RajawaliVuforiaExampleRenderer.java but it said "Can't create handler inside thread that has not called Looper.prepare()"
I have pasted part of the code here:
protected void initScene() {
mLight = new DirectionalLight(.1f, 0, -1.0f);
mLight.setColor(1.0f, 0, 0);
mLight.setPower(1);
getCurrentScene().addLight(mLight);
LoaderOBJ objParser = new LoaderOBJ(mContext.getResources(),
mTextureManager, R.raw.wall_obj);
try {
// Load model
objParser.parse();
wall = objParser.getParsedObject();
addChild(wall);
} catch (Exception e) {
e.printStackTrace();
}
}
EDITED:
I have read the comment from Abhishek Agarwal and updated the code for Renderer part, now i having problem on calling the ProgressDialog when loading the model, here is my code for the UI thread.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setScreenOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// receive file path
String filePath = this.getIntent().getStringExtra("FullFilePath");
Log.i(filePath, "FullFilePath:" + filePath);
waitDialog = ProgressDialog.show(this, "", "Loading", true);
waitDialog.show();
new ModelLoader().execute();
}
#Override
protected void setupTracker() {
int result = initTracker(TRACKER_TYPE_MARKER);
if (result == 1) {
result = initTracker(TRACKER_TYPE_IMAGE);
if (result == 1) {
super.setupTracker();
} else {RajLog.e("Couldn't initialize image tracker.");
}
} else {
RajLog.e("Couldn't initialize marker tracker.");
}}
protected void initApplicationAR() {
super.initApplicationAR();
createImageMarker("marker.xml");
}
protected void initRajawali() {
super.initRajawali();
mRenderer = new ModelRenderer(this);
mRenderer.setSurfaceView(mSurfaceView);
super.setRenderer(mRenderer);
mUILayout = this;
mUILayout.setContentView(mLayout, new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
private class ModelLoader extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
startVuforia();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
waitDialog.dismiss();
}
}
Progress Dialog can be shown on the UIThread. So show progress dialog on the main thread not under GLThread
You can use Handler to be on threadUI :
`private Handler mHandler = new Handler();
...
mHandler.post(new Runnable() {
#Override
public void run() {
view_progressBar.setProgress(val);
}
});`

I am working with facebook game request

I finished working with sending the request with android reading https://developers.facebook.com/docs/howtos/androidsdk/3.0/send-requests/
but i'm having a problem with handling requests.
https://developers.facebook.com/docs/howtos/androidsdk/3.0/app-link-requests/
I think I did what it told me to do, but I can't get the uri and the requestid
they are all null.
I thing the problem is that when I receive a request I can't click the accept button.
It says that the playstore can't find the app. So the request doesn't disappear.
How can I solve the problem?
public class MainActivity extends Activity {
private static final List<String> PERMISSIONS = Arrays
.asList("read_requests");
private Bundle SIS;
private Session.StatusCallback logincallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
// TODO Auto-generated method stub
if (session.isOpened()) {
updateview();
getp();
loginlogoutbutton.setText("Login");
onSessionStateChange(session, state, exception);
} else {
}
}
};
public void updateview() {
Session session = Session.getActiveSession();
if (session.isOpened()) {
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
tt.setText(user.getId());
}
}
});
} else
{
tt.setText("Login");
}
}
private Button loginlogoutbutton;
private Button sendrequestbutton;
private Button testbtn;
private TextView tt;
private String app_id = "APP ID";
private String requestId;
public void getp() {
Session session = Session.getActiveSession();
if (session == null || !session.isOpened()) {
return;
}
List<String> permissions = session.getPermissions();
if (!permissions.containsAll(PERMISSIONS)) {
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSIONS)
.setCallback(new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
// TODO Auto-generated method stub
}
}));
} else {
}
}
#Override
public void onResume() {
super.onResume();
checkforrequest();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SIS = savedInstanceState;
tt = (TextView) findViewById(R.id.tex);
loginlogoutbutton = (Button) findViewById(R.id.loginlogoutbtn);
loginlogoutbutton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
onClickLoginLogout();
}
});
sendrequestbutton = (Button) findViewById(R.id.sendrequest);
sendrequestbutton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
sendRequestDialog();
}
});
testbtn = (Button) findViewById(R.id.button1);
testbtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
checkforrequest();
}
});
ConfirmLogin(app_id);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
}
public boolean ConfirmLogin(String iappid) {
app_id = iappid;
Session session = Session.getActiveSession();
boolean dd = true;
if (session == null) {
if (SIS != null) {
session = Session.restoreSession(this, null,
new Session.StatusCallback() {
#Override
public void call(Session session,
SessionState state, Exception exception) {
// TODO Auto-generated method stub
}
}, SIS);
}
if (session == null) {
session = new Session.Builder(this).setApplicationId(app_id)
.build();
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this)
.setCallback(logincallback));
dd = true;
} else {
dd = false;
}
}
return dd;
}
public void onClickLoginLogout() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this)
.setCallback(logincallback));
} else if (session.isClosed()) {
session = new Session.Builder(this).setApplicationId(app_id)
.build();
Session.setActiveSession(session);
session.openForRead(new Session.OpenRequest(this)
.setCallback(logincallback));
} else {
session.closeAndClearTokenInformation();
loginlogoutbutton.setText("Login");
}
}
private void sendRequestDialog() {
Bundle params = new Bundle();
params.putString("message",
"Learn how to make your Android apps social");
params.putString("data", "{\"badge_of_awesomeness\":\"1\","
+ "\"social_karma\":\"5\"}");
WebDialog requestsDialog = (new WebDialog.RequestsDialogBuilder(this,
Session.getActiveSession(), params)).setOnCompleteListener(
new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error != null) {
if (error instanceof FacebookOperationCanceledException) {
} else {
}
} else {
final String requestId = values
.getString("request");
if (requestId != null) {
maketoast(requestId);
} else {
}
}
}
}).build();
requestsDialog.show();
}
public void checkforrequest() {
maketoast("0");
Uri intentUri = this.getIntent().getData();
if (intentUri != null) {
String requestIdParam = intentUri.getQueryParameter("request_ids");
maketoast("1 : " +requestIdParam);
if (requestIdParam != null) {
String array[] = requestIdParam.split(",");
requestId = array[0];
}
}
else
{
maketoast("uri = null");
}
}
public void maketoast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
private void getRequestData(final String inRequestId) {
// Create a new request for an HTTP GET with the
// request ID as the Graph path.
maketoast("2");
Request request = new Request(Session.getActiveSession(), inRequestId,
null, HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
// Process the returned response
GraphObject graphObject = response.getGraphObject();
FacebookRequestError error = response.getError();
// Default message
String message = "Incoming request";
if (graphObject != null) {
// Check if there is extra data
if (graphObject.getProperty("data") != null) {
try {
// Get the data, parse info to get the
// key/value info
JSONObject dataObject = new JSONObject(
(String) graphObject
.getProperty("data"));
// Get the value for the key -
// badge_of_awesomeness
String badge = dataObject
.getString("badge_of_awesomeness");
// Get the value for the key - social_karma
String karma = dataObject
.getString("social_karma");
// Get the sender's name
JSONObject fromObject = (JSONObject) graphObject
.getProperty("from");
String sender = fromObject
.getString("name");
String title = sender + " sent you a gift";
// Create the text for the alert based on
// the sender
// and the data
message = title + "\n\n" + "Badge: "
+ badge + " Karma: " + karma;
} catch (JSONException e) {
message = "Error getting request info";
}
} else if (error != null) {
message = "Error getting request info";
}
}
maketoast(message);
}
});
// Execute the request asynchronously.
Request.executeBatchAsync(request);
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
// Check if the user is authenticated and
// an incoming notification needs handling
if (state.isOpened() && requestId != null) {
maketoast("3");
getRequestData(requestId);
requestId = null;
} else if (requestId == null) {
maketoast("4");
}
if (state.isOpened()) {
} else if (state.isClosed()) {
}
}
}
this is the code.

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();
}