Refresh ListView when Device receives GCM IntentService Message - service

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

Related

Android Webview signout issue

In my webview app when I run the app for the first time and log out from a user session, close the app and then when I open the app again instead of asking user credentials I find myself already logged in. I tried clearing cookies but then it always require sign in on every restart. I only want it to ask for sign in when the user logs out from the app.
Please Help!!
Here is a snippet of the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = (FrameLayout) findViewById(R.id.framelayout);
bar = (ProgressBar) findViewById(R.id.progressBar2);
bar.setMax(100);
webview = (WebView) findViewById(R.id.mywebview);
webview.clearCache(true);
webview.clearHistory();
WebSettings mWebSettings = webview.getSettings();
mWebSettings.setSaveFormData(false);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
LoadWeb();
}
});
LoadWeb();
}
public void LoadWeb(){
webview = (WebView) findViewById(R.id.mywebview);
webview.setWebViewClient(new HelpClient());
webview.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress) {
frameLayout.setVisibility(View.VISIBLE);
bar.setProgress(newProgress);
setTitle("Loading....");
if (newProgress == 100){
frameLayout.setVisibility(View.GONE);
setTitle(view.getTitle());
}
super.onProgressChanged(view, newProgress);
}
});
webview.getSettings().setJavaScriptEnabled(true);
webview.setVerticalScrollBarEnabled(false);
webview.loadUrl(WebAddress);
webview.loadUrl("javascript:window.location.reload(true)");
swipe.setRefreshing(false);
bar.setProgress(0);
}
private class HelpClient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
frameLayout.setVisibility(view.VISIBLE);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
swipe.setRefreshing(false);
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
try {
webview.stopLoading();
} catch (Exception e) {
}
if (webview.canGoBack()) {
webview.goBack();
}
webview.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your internet connection and try again.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
super.onReceivedError(view, request, error);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK){
if (webview.canGoBack()){
webview.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Run below code before loadUrl()
WebStorage webStorage = WebStorage.getInstance();
webStorage.deleteAllData();
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
I test it using Gmail account
CookieSynManager is now deprecated. This works for me :
WebStorage.getInstance().deleteAllData()
CookieManager.getInstance().removeAllCookies(null)

Background service is not working in some devices like vivo , mi etc.. after app is clear from recent app

i am use the below code to send the location to the server but it is not working in some devices after app is clear from recent app. so what is best alternate way to start service when app is closed.
public class GpsService extends Service implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
private LocationCallback mLocationCallback;
SharePref sharePref;
#Override
public void onCreate() {
super.onCreate();
Log.e("sevice start", ">>>>>>>>>>>>>>>>>>>>>>>>>......");
sharePref = new SharePref(GpsService.this);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_logo)
.setContentTitle("My Awesome App")
.setContentText("Doing some work...")
.setContentIntent(pendingIntent).build();
startForeground(1337, notification);
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
// Update UI with location data
// ...
Toast.makeText(getBaseContext(), locationResult.toString(), Toast.LENGTH_LONG).show();
}
}
;
};
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("sevice start", "mGoogleApiClient >>>>>>>>>>>>>>>>>>>>>>>>>......");
mGoogleApiClient.connect();
return START_REDELIVER_INTENT;
}
#Override
public void onDestroy() {
mGoogleApiClient.disconnect();
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
//Check Google play is available or not
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
//Save your location
Log.e("GpsService Location lat", "Is change " + location.getLatitude());
Log.e("Gps Location long", "Is change " + location.getLongitude());
Log.e("GpsService userid", "Enter" + sharePref.getUserId());
Toast.makeText(GpsService.this, location.toString(), Toast.LENGTH_LONG).show();
sharePref.SetLat(String.valueOf(location.getLatitude()));
sharePref.SetLong(String.valueOf(location.getLongitude()));
String lati = String.valueOf(location.getLatitude());
String longi = String.valueOf(location.getLongitude());
HashMap<String, String> param = new HashMap<>();
param.put(PARAM_USER_ID, sharePref.getUserId());
param.put(PARAM_SESSION_ID, sharePref.getSessionId());
param.put(PARAM_LAT, lati);
param.put(PARAM_LONG, longi);
param.put(PARAM_PLATFORM, PLATFORM);
BikerService.addLatLong(GpsService.this, param, new APIService.Success<JSONObject>() {
#Override
public void onSuccess(JSONObject response) {
Log.e("Location Response-->", "" + response.toString());
BikerParser.AddLatLongResponse AddLatLongResponse = BikerParser.AddLatLongResponse.addLatLongResponse(response);
if (AddLatLongResponse.getStatusCode() == API_STATUS_FOUR_ZERO_ONE) {
stopService(new Intent(GpsService.this, GpsService.class));
}
}
});
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Log.e("sevice start", "startLocationUpdates >>>>>>>>>>>>>>>>>>>>>>>>>......");
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
}

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

setOnItemClickListener in customized listview

Here is the activity ShowData.java where i am setting up customized listview.. Now i need to click view on that listview and need to display another activity but throws force close.. It throws error on listview.setAdapter(adapter);
public class ShowData extends Activity
{
ListView listview;
Intent intent;
ArrayList<BeanClass> datalist;
CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
listview = (ListView) findViewById(R.id.listView1);
Intent intent = getIntent();
datalist = (ArrayList<BeanClass>) intent.getSerializableExtra("list");
Log.i("Size of ArrayList", "is " +datalist.size());
adapter = new CustomAdapter(ShowData.this, R.layout.customrow , datalist);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
{
Intent i = new Intent(ShowData.this,DetailActivity.class);
i.putExtra("datalist", datalist);
i.putExtra("position", arg2);
startActivity(i);
}
}
}
Here is the CustomAdapter.java
public class CustomAdapter extends ArrayAdapter<BeanClass>
{
Context context;
int layoutResourceId;
BeanClass bc;
ArrayList<BeanClass> vbc;
public CustomAdapter(Context context, int layoutResourceId, ArrayList<BeanClass> vbc)
{
super(context, layoutResourceId, vbc);
this.context=context;
this.layoutResourceId=layoutResourceId;
this.vbc=vbc;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
StringReaderHolder holder;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent,false);
holder= new StringReaderHolder();
holder.mytext1 = (TextView) row.findViewById(R.id.textView1);
holder.mytext2 = (TextView) row.findViewById(R.id.textView2);
holder.mytext3 = (TextView) row.findViewById(R.id.textView3);
row.setTag(holder);
}
else
{
holder = (StringReaderHolder) row.getTag();
}
BeanClass bsObject = vbc.get(position);
holder.mytext1.setText(bsObject.name);
holder.mytext2.setText(bsObject.address);
holder.mytext3.setText(bsObject.phone);
return row;
}
static class StringReaderHolder
{
TextView mytext1,mytext2,mytext3;
}
}
How should i use setOnItemClickListener...??? Thanks...
In Your getView Method try:
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(context,DetailActivity.class);
i.putExtra("datalist", vbc);
i.putExtra("position", position);
startActivity(i);
}
});

What's the problems when I use ".getText().toString();"

#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText nameText = (EditText) findViewById(R.id.editText1);
name = nameText.getText().toString();
nameText.setText("");
EditText numberText = (EditText) findViewById(R.id.editText2);
number = numberText.getText().toString();
numberText.setText("");
person = new Person(name, number);
order.add(person);
PersonAdapter pa = new PersonAdapter(con, R.layout.row, order);
setListAdapter(pa);
}
});
}
#Override
protected void onListItemClick(ListView l, View v, final int position, long id) {
// TODO Auto-generated method stub
final int index = position;
AlertDialog.Builder aDialog = new AlertDialog.Builder(this);
aDialog.setTitle("What do you want??");
aDialog.setPositiveButton("Delete",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
order.remove(index);
PersonAdapter pa = new PersonAdapter(con, R.layout.row,
order);
setListAdapter(pa);
}
});
aDialog.setNeutralButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) con.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog, (ViewGroup)findViewById(R.id.root_layout));
builder = new AlertDialog.Builder(con);
builder.setView(layout);
builder.setTitle("Fill EditText");
builder.setIcon(R.drawable.icon);
editNum = (EditText)findViewById(R.id.editNum);
editName = (EditText)findViewById(R.id.editName);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
name = editName.getText().toString();
number = editNum.getText().toString();
order.set(position, new Person(name,number));
PersonAdapter pa = new PersonAdapter(con, R.layout.row, order);
setListAdapter(pa);
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alertDialog = builder.create();
alertDialog.show();
}
});
aDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
AlertDialog ad = aDialog.create();
ad.show();
}
public PersonAdapter(Context context, int textViewResourceId,
ArrayList<Person> items) {
super(context, textViewResourceId, items);
this.items = items;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
}
Person p = items.get(position);
if (p != null) {
TextView tt = (TextView) v.findViewById(R.id.android_toptext);
TextView bt = (TextView) v.findViewById(R.id.android_bottomtext);
if (tt != null) {
tt.setText(p.getName());
}
if (bt != null) {
bt.setText("TEL : " + p.getNumber());
}
}
return v;
}
private String name;
private String number;
public Person(String name, String number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
}
I am practicing Widget(exactly I am making custom dialog) and Listener In android . But I stop now because ".getText().toString();" makes error ... I can't understand.. T^T Please Help me... why it makes error?? I think It doesn't have problem
You should declare your EditText globally
EditText editName;
EditText editNum;
#Override
public void onCreate(Bundle savedInstanceState) {
...
}
.....
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) con.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog, (ViewGroup)findViewById(R.id.root_layout));
builder = new AlertDialog.Builder(con);
builder.setView(layout);
builder.setTitle("Fill EditText modificated");
builder.setIcon(R.drawable.icon);
editName = (EditText)findViewById(R.id.editName);
editNum = (EditText)findViewById(R.id.editNum);