in signin the method gettext must be called from ui thread error - gettext

I'm trying to create a login for an application. However I have a problem.
This is my code:
in this code there is an error in the getText() in the android studio
actually m creating a login page with the help of the JSONParsing of web API, the login detail sync from the web api
public class Register extends Activity implements OnClickListener{
EditText user, pass, email, mobile;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//si lo trabajan de manera local en xxx.xxx.x.x va su ip local
// private static final String REGISTER_URL = "http://xxx.xxx.x.x:1234/cas/register.php";
//testing on Emulator:
private static final String REGISTER_URL = "http://abc.demo.xxxxxxxxx.xxx/xxx";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
email = (EditText)findViewById(R.id.Email);
mobile = (EditText)findViewById(R.id.etmobile);
mRegister = (Button)findViewById(R.id.register);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Creating User...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
String mobile = mobile.getText().toString();
String email = email.getText().toString();
try {
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("mobile", mobile));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
REGISTER_URL, "POST", params);
// full json response
Log.d("Registering attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Registering Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}

You will have to pass EditText values as args in the Async task.
String[] params = {user.getText().toString(),
pass.getText().toString(),
mobile.getText().toString(),
email.getText().toString()};
new CreateUser().execute(params);
You can play with the UI elements only in classes that run in UI thread. Activity or fragments etc.

Related

Android ListView does not update dynamic location data

I have researched this topic thoroughly and found similar questions on StackOverflow but not specific enough for my question. I am trying to update my ListView with a SimpleCursorAdapter. I have a button, "Get Network Location" that when I press it, it dynamically populates my ListView with new location data (id, lat, lon, acc, time) every time the location changes inside method "onLocationChanged". This is done through adding the new location data to the database and setting the cursor to the adapter.
So it works fine until the "Back" button is pressed or the phone changes orientation. In onResume, the listview becomes empty, so I had to open the database again and set the cursor to the adapter and the adapter to listview again. This populates the listview with complete data from database at the time that "onResume" is called.
However, when a new location data gets added in "onLocationChanged", the new data doesn't populate the listview, until "onResume" gets called again. adapter.notifyDataSetChanged is called both in "onResume" an "onLocation" changed but to no avail. My guess is the listview has changed to a different one after "onCreate" is called but I don't know how to resolve that.
Please anyone with knowledge on this issue let me know what is wrong with my code.
Here's my code:
public class MainActivity extends Activity {
LocationManager locMan;
String provider;
Boolean netWork_enabled = false;
private static long MINTIME;
private static float MINDIS;
Cursor cursor;
NetworkScanDB GeoLocInfoDb;
String row;
double lat;
double lon;
double accur;
double time;
EditText etMinTime;
EditText etMinDis;
ListView lv;
SimpleCursorAdapter sd;
String[] columns;
int[] to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize lv
lv = (ListView) findViewById(R.id.listView1);
// getting min time and distance from edit text
etMinTime = (EditText) findViewById(R.id.et_minTime);
etMinDis = (EditText) findViewById(R.id.et_minDis);
// initiating location
locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locMan.NETWORK_PROVIDER;
try {
netWork_enabled = locMan.isProviderEnabled(provider);
} catch (Exception ex) {
}
columns = new String[] { NetworkScanDB.Key_RowID,
NetworkScanDB.Key_Lat, NetworkScanDB.Key_Lon,
NetworkScanDB.Key_Accur, NetworkScanDB.Key_Time };
to = new int[] { R.id.t0, R.id.t1, R.id.t2, R.id.t3, R.id.t4 };
sd = new SimpleCursorAdapter(MainActivity.this, R.layout.nsrow, cursor,
columns, to, 0); // had to change to api 11., 0=no query
}
LocationListener locationListenerNetwork = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
try {
GeoLocInfoDb = new NetworkScanDB(MainActivity.this);
GeoLocInfoDb.open();
// insert row into DB
GeoLocInfoDb.insertGeoLocInfo(location.getLatitude(),
location.getLongitude(), location.getAccuracy(),
location.getTime());
cursor = GeoLocInfoDb.getGeoLocInfoCursor();
sd = new SimpleCursorAdapter(MainActivity.this, R.layout.nsrow,
cursor, columns, to, 0); // had to change to api 11.,
// 0=no query
Toast.makeText(getApplicationContext(),
"added new location onLocationChanged",
Toast.LENGTH_LONG).show();
// lv = (ListView) findViewById(R.id.listView1);
sd.notifyDataSetChanged();
lv.setAdapter(sd);
GeoLocInfoDb.close();
} catch (Exception e) {
Log.w("nwscan", e.toString());
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
public void getNetworkLocation(View v) {
MINTIME = Long.parseLong(etMinTime.getText().toString());
MINDIS = Float.parseFloat(etMinDis.getText().toString());
if (netWork_enabled) {
locMan.requestLocationUpdates(provider, MINTIME, MINDIS,
locationListenerNetwork);
} else {
Toast.makeText(getApplicationContext(), "network not enable",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(getApplicationContext(), "onResume ", Toast.LENGTH_LONG)
.show();
GeoLocInfoDb = new NetworkScanDB(MainActivity.this);
GeoLocInfoDb.open();
cursor = GeoLocInfoDb.getGeoLocInfoCursor();
sd = new SimpleCursorAdapter(MainActivity.this, R.layout.nsrow, cursor,
columns, to, 0); // had to change to api 11., 0=no query
sd.notifyDataSetChanged();
lv.setAdapter(sd);
}
...
}

Issue with UploadServlet in GWT Project - empty MultiPart

I'm developing a web-app using GWT, and I need to upload a file to the server.
I've written this servlet (which I found here on stackoverflow)
public class ImageUploadService extends HttpServlet {
private static final int MAX_FILE_SIZE = 1 * 1024 * 1024;
#Override
protected void doPost(final HttpServletRequest request,
final HttpServletResponse response) {
wlog("INFO: LA SERVLET é PARTITA");
boolean isMultipart = /* ServletFileUpload.isMultipartContent(request); */true;
if (isMultipart) {
wlog("INFO: IL CONTENUTO é MULTIPART");
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
try {
List<FileItem> items = upload.parseRequest(request);
wlog("INFO: LISTA PARTI " + Arrays.toString(items.toArray()));
Iterator<FileItem> iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/fileuploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
item.write(uploadedFile);
wlog("INFO: SALVATO FILE SU DISCO");
}
}
wlog("FINE SERVLET");
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void wlog(String s) {
System.out.println("UPLOAD SERVLET " + s);
}
}
This servlet is correctly invoked, and the method doPost executes when I perform form.submit() on the client, but the problem is, upload.parseRequest always returns an empty list.
As I seached here on SO the solution, I found that the main cause for this behaviour is that the request has already been parsed before, but, as you can see from the code I posted, I never parse the request before .parseRequest().
I'm really getting mad tryng to understand where the problem stands, as all the solutions suggested so far haven't worked.
Thanks to everyone who will help spot the error..
(If it helps, I may post the client-side code, although I don't think that the issue lies there)
EDIT: inserted client code
private void inserisciSegnalazioneOK() {
final PopupPanel inserisciSegnalazionePopup = new PopupPanel();
VerticalPanel inseriscisegnalazioneholder = new VerticalPanel();
final FormPanel textform = new FormPanel();
final FormPanel uploadform = new FormPanel();
Button inseriscisegnalazionebtn = new Button("INSERISCI SEGNALAZIONE");
VerticalPanel textholder = new VerticalPanel();
VerticalPanel uploadholder = new VerticalPanel();
final Segnalazione segnalazione = new Segnalazione();
final ListBox lbcat = new ListBox();
for (String s : listaCategorie)
lbcat.addItem(s);
final TextBox descrizione = new TextBox();
final GoogleSuggestBox gsb = new GoogleSuggestBox();
final FileUpload fu = new FileUpload();
textholder.add(new Label("scegli la categoria della segnalazione"));
textholder.add(lbcat);
textholder.add(new Label("inserisci una descrizione testuale"));
textholder.add(descrizione);
textholder.add(new Label("inserisci l'indirizzo della segnalazione"));
textholder.add(gsb);
uploadholder.add(new Label(
"se puoi, allega una foto della segnalazione"));
uploadholder.add(fu);
textform.add(textholder);
uploadform.add(uploadholder);
inseriscisegnalazioneholder.add(textform);
inseriscisegnalazioneholder.add(uploadform);
inseriscisegnalazioneholder.add(inseriscisegnalazionebtn);
inserisciSegnalazionePopup.setWidget(inseriscisegnalazioneholder);
inseriscisegnalazionebtn.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
// TODO Auto-generated method stub
segnalazione.setCategoria(lbcat.getItemText(lbcat
.getSelectedIndex()));
segnalazione.setDescrizione(descrizione.getText());
segnalazione.setIndirizzo(gsb.getText());
segnalazione.setUtente(username);
log("INFO: upload del file " + fu.getFilename());
textform.submit();
uploadform.submit();
}
});
uploadform.setAction(GWT.getModuleBaseURL() + "imageUpload");
uploadform.setEncoding(FormPanel.ENCODING_MULTIPART);
uploadform.setMethod(FormPanel.METHOD_POST);
uploadform.addSubmitHandler(new FormPanel.SubmitHandler() {
#Override
public void onSubmit(SubmitEvent event) {
// TODO Auto-generated method stub
if (fu.getFilename().length() == 0) {
Window.alert("Non hai eseguito l'upload di nessuna immagine");
event.cancel();
}
}
});
textform.addSubmitHandler(new FormPanel.SubmitHandler() {
#Override
public void onSubmit(SubmitEvent event) {
// TODO Auto-generated method stub
dataLayerService.inserisciSegnalazione(segnalazione,
new AsyncCallback<Boolean>() {
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated
// method stub
caught.printStackTrace();
}
#Override
public void onSuccess(Boolean result) {
// TODO Auto-generated
// method stub
if (result) {
Window.alert("Inserimento avvenuto con successo");
inserisciSegnalazionePopup.hide();
gc.getLatLng(segnalazione.getIndirizzo(),
new LatLngCallback() {
#Override
public void onFailure() {
// TODO
// Auto-generated
// method
// stub
}
#Override
public void onSuccess(
LatLng point) {
// TODO
// Auto-generated
// method
// stub
Marker m = new Marker(point);
map.addOverlay(m);
listaMarker.add(m);
}
});
} else
Window.alert("L'inserimento ha avuto esito negativo");
}
});
}
});
inserisciSegnalazionePopup.setAutoHideEnabled(true);
inserisciSegnalazionePopup.setGlassEnabled(true);
inserisciSegnalazionePopup.center();
}
You have to set a name to your FileUpload if you want the field to be sent out to the server.
BTW, why are you using a FormPanel for your "data" form? Why aren't you simply calling the RPC from the submit button's click? or alternatively, why aren't you putting everything in the same uploadForm and processing it all at once (data and uploaded file) on the server in your upload servlet?

Facebook onComplete callback not being triggered in Fragment

I am making a request to the Facebook API using the Facebook SDK. I am trying to retrieve a graph user however it doesnt matter what I do. The callback is not being triggered.
How do I trigger the OnActivityResult of the fragment?
public class SampleFragment
extends Fragment
{
FacebookUtils instance;
private TextView labelText;
private ProfilePictureView prof;
private Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View contentView = inflater.inflate(R.layout.fragment_sample, container, false);
labelText = ((TextView) contentView.findViewById(R.id.label_text));
prof = (ProfilePictureView)contentView.findViewById(R.id.selection_profile_pic);
button= ((Button) contentView.findViewById(R.id.button));
Bundle bundle = getArguments();
String label = bundle.getString("label");
labelText.setText(label);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// If the session is open, make an API call to get user data
// and define a new callback to handle the response
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
Toast.makeText(getActivity(),user.getFirstName(),Toast.LENGTH_LONG).show();
if (session == Session.getActiveSession()) {
if (user != null) {
prof.setProfileId(user.getId());
AppMsg.makeText(getActivity(),user.getFirstName(),AppMsg.STYLE_CONFIRM).show();
//user id
//profileName = user.getName();//user's profile name
//userNameView.setText(user.getName());
}
}
}
});
Request.executeBatchAsync(request);
}
}
});
return contentView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
}

Sharing Data with the Class that does not extends Activity

I have made a TCP client for android using socket. However, the program that I have does not allow me to dynamically input the server address. Also i cannot use intent to transfer String from MainActivity because my TcpClient.java does not extends to Activity. What logic shall I implement so that I can dynamically set server address and connect to any server I wish..
MainActivity.java
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Intent i = new Intent(this, Preferences.class);
startActivityForResult(i, RESULT_SETTINGS);
break;
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SETTINGS:
saveData();
break;
}
}
public class connectTask extends AsyncTask<String,String,TcpClient> {
#Override
protected TcpClient doInBackground(String... message) {
//we create a TCPClient object and
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
mTcpClient.run(serverip, serverport);
return null;
}
}
//call it at Activity startup onStart() for example
public void loadData(){
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences;
mySharedPreferences = getSharedPreferences(MYPREFS, mode);
serverip = mySharedPreferences.getString("IP", serverip);
serverport = mySharedPreferences.getInt("Port", serverport);
}
// Call it whenever you modify the values
public void saveData()
{
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences;
mySharedPreferences = getSharedPreferences(MYPREFS, mode);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("IP", serverip);
editor.putInt("Port", serverport);
editor.commit();
Toast.makeText(getBaseContext(),
"Server Settings Saved" + serverip + serverport ,
Toast.LENGTH_LONG).show();
}
}
This is not saving the data. Its showing null0 on the Toast.Also these are the variables declared for the above code
public static final String MYPREFS = "192.168.1.3";
public String serverip;
public int serverport;
Preferences.java
package com.example.homauto;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Preferences extends PreferenceActivity{
#SuppressWarnings("deprecation")
#Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
I am a newbie to programming..
Here is the website from where i took the references..Android TCP Connection tutorial
Ok, there are a couple of thing you can do in order to pass the IP and Port to the TCPClient class. For me the easiest one is to declare the run method as follows:
public void run(String srvIP, int srvPort)
{
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(srvIP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, srvPort);
You must call it like this:
mTcpClient.run("ServerIP", ServerPort);
like this: mTcpClient.run("192.168.1.25", 4444);
Other possibility is to change the create method and put those parameters there,
// You have to remove the final in these variables
public static String SERVERIP = "192.168.0.102"; //your computer IP address
public static int SERVERPORT = 4444;
public TCPClient(String srvIP, int srvPort, OnMessageReceived listener) {
SERVERIP=srvIP;
SERVERPORT=srvPort;
mMessageListener = listener;
}
and you instantiate the class like this:
mTcpClient = new TcpClient(ServerIP, ServerPort, new TcpClient.OnMessageReceived()
Now, in your application (main activity) you need to put a dialog or another activity in order to ask the user for the IP and port to connect to before you launch the TCPClient class, in your case the AsyncTask.
I'd put an action bar menu and when clicked show a dialog to ask for those values.
Also, you may save the values so that you have them for future use (in MainActivity):
// call it at Activity startup onStart() for example
public void loadData()
{
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences;
mySharedPreferences = getSharedPreferences(Typedefs.saveConfigsFileName, mode);
serverIP = mySharedPreferences.getString("IP", serverIP);
serverPort = mySharedPreferences.getInt("Port", serverPort);
}
// Call it whenever you modify the values
public void saveData()
{
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences;
mySharedPreferences = getSharedPreferences(Typedefs.saveConfigsFileName, mode);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("IP", serverIP);
editor.putInt("Port", serverPort);
editor.commit();
}

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