com.google.firebase.database.DatabaseException: Can't convert object of type java.util.ArrayList to type - flutter

public class MainActivity extends AppCompatActivity {
DatabaseReference myRef;
PlayersAdapter adapter;
RecyclerView recyclerView;
private static ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.tvplayers);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Loading");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(0);
// Read from the database
myRef = FirebaseDatabase.getInstance().getReference("player");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
// String value = dataSnapshot.getValue(String.class);
progressDialog.show();
ArrayList<PlayerModal> array= new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
// PlayerModal displayProducts = ds.getValue(PlayerModal.class);
PlayerModal value = dataSnapshot.getValue(PlayerModal.class);
array.add(value);
progressDialog.dismiss();
}
adapter= new PlayersAdapter(MainActivity.this,array);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
//
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
}

Related

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 .......................");
}
}

Interstitial ads for coco2d android game

I'm facing a lot of difficulties to show the Interstitial, it's my first time working with the Cocos2D game.
This is all main java code
public class FlyingPanda extends Activity implements AdListener {
/** Called when the activity is first created. */
public static CCGLSurfaceView mGLSurfaceView;
private boolean isCreated = false;
private static final String ADMOB_PUBLISH_ID = "xxxxxxxxxxxxxxxxxx";
#Override
public void onCreate(Bundle savedInstanceState) {
if( !isCreated ){
isCreated = true;
} else {
return;
}
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
RelativeLayout layout = new RelativeLayout(this);
layout.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
mGLSurfaceView = new CCGLSurfaceView(this);
// Create the adView
AdView adView = new AdView(this, AdSize.BANNER, ADMOB_PUBLISH_ID);
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
adView.setAdListener(this);
// Add the adView to it
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
adView.setLayoutParams(params);
layout.addView(mGLSurfaceView);
layout.addView(adView);
setContentView(layout);
Common.game_initialize();
getScaledCoordinate();
CCDirector.sharedDirector().attachInView(mGLSurfaceView);
// attach the OpenGL view to a window
Common.sound_engine = SoundEngine.sharedEngine();
loadSound();
What am I supposed to add here in admob setting? I'll define a variable named interstitial like the banner or what?
////////////////////////////////////////////////////////////////////////////////
// Admob Setting
////////////////////////////////////////////////////////////////////////////////
How can I Load interstitial in all this public classes?
#Override
public void onDismissScreen(Ad ad) {
// TODO Auto-generated method stub
}
#Override
public void onFailedToReceiveAd(Ad ad, ErrorCode errorCode) {
// TODO Auto-generated method stub
}
#Override
public void onLeaveApplication(Ad ad) {
// TODO Auto-generated method stub
}
#Override
public void onPresentScreen(Ad ad) {
// TODO Auto-generated method stub
}
#Override
public void onReceiveAd(Ad ad) {
MainActivity.java:
public class AppActivity extends Cocos2dxActivity {
private static final String ADMOB_INTERSTITIAL = "ca-app-pub-2575683230512628/5833084223";
private InterstitialAd admobInterstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_appActivity = this;
admobInterstitial = new InterstitialAd(this);
admobInterstitial.setAdUnitId(ADMOB_INTERSTITIAL);
admobInterstitial.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
admobInterstitial.loadAd(newAdRequest());
}
});
admobInterstitial.loadAd(newAdRequest());
}
public static void showInterstitial(final String adSdk){
Log.d("ADMOB INTERSTITIAL", "showInterstitial: " + adSdk);
_appActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if(adSdk.equalsIgnoreCase("admob")){
if(_appActivity.admobInterstitial != null){
if(_appActivity.admobInterstitial.isLoaded()){
_appActivity.admobInterstitial.show();
}
}
}
else if(adSdk.equalsIgnoreCase("chartboost")){
}
else if(adSdk.equalsIgnoreCase("revmob")){
}
else{
Log.w("INTERSTITIAL", "unknown ad to show: " + adSdk);
}
}
});
}
private AdRequest newAdRequest(){
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("YOUR_DEVICE_ID")
.build();
return adRequest;
}
}
c++ code (.c file):
const char* AppActivityClassName = "org/cocos2dx/cpp/AppActivity";
bool NativeHelper::instanceFlag = false;
NativeHelper* NativeHelper::instance = NULL;
NativeHelper* NativeHelper::getInstance(){
if(!instanceFlag){
instance = new NativeHelper();
instanceFlag = true;
}
return instance;
}
void NativeHelper::showInterstitial(string adSdk){
cocos2d::JniMethodInfo t;
if (cocos2d::JniHelper::getStaticMethodInfo(t, AppActivityClassName, "showInterstitial", "(Ljava/lang/String;)V")){
jstring stringArg = t.env->NewStringUTF(adSdk.c_str());
t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg);
t.env->DeleteLocalRef(t.classID);
t.env->DeleteLocalRef(stringArg);
}
}
c++ code (.h file):
class NativeHelper
{
public:
static void showInterstitial(string adSdk);
private:
static bool instanceFlag;
static NativeHelper* instance;
}
You can also use SDKBOX, but this is more flexible solution and you always have up-to-date sdk.

Get value from Android listview and put it in extra

In my code below I created a method which is: I would like to put a variable in putExtra that I can get it in the new activity. The problem is in the new activity gave me the first value(numtelephone) from first element in my list. I know that because of getItem(0), but how can I get the value( numtelephone ) for every element from the list?
public class ListClient extends Activity {
String myJSON,test;
TextView numt;
private static final String TAG_RESULTS="result";
private static final String TAG_NOMCLIENT = "nomclient";
private static String TAG_NUMTELEPHONE ="numtelephone";
private static final String TAG_DEPART ="depart";
private static final String TAG_DESTINATION ="destination";
private static final String TAG_NBRPERSONNE ="nbrpersonne";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_client);
list = (ListView) findViewById(R.id.list);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
protected void showList(){
//json parsing etc...
ListAdapter adapter = new SimpleAdapter(
ListClient.this, personList, R.layout.list_item,
new String[]{TAG_NOMCLIENT,TAG_NUMTELEPHONE,TAG_DEPART,TAG_DEPART,TAG_NBRPERSONNE},
new int[]{R.id.name, R.id.numt, R.id.depart, R.id.destination, R.id.nbrpersonne}
);
list.setAdapter(adapter);
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// json dowload from web, not needed in this question
return "";
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
public void GoUpdate(View v ) {
Intent in = new Intent(getBaseContext(), Update.class);
in.putExtra("NUMTELEPHONE",((HashMap<String, String>)list.getAdapter().getItem(0)).get("numtelephone"));
}
startActivity(in);
}
}
There is simple and only one solution. Delete your xml android:click property of list and add this list#setOnItemClickListener in your onCreate:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_client);
list = (ListView) findViewById(R.id.list);
personList = new ArrayList<HashMap<String,String>>();
getData();
//this thing has been added
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(id!=-1){
Intent in = new Intent(getBaseContext(), Update.class);
in.putExtra("NUMTELEPHONE", ((HashMap<String, String>) list.getAdapter().getItem((int)id)).get("numtelephone")); //TAG_NUMTELEPHONE
startActivity(in);
}
}
});
}
To move it from onCreate do:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_client);
list = (ListView) findViewById(R.id.list);
personList = new ArrayList<HashMap<String, String>>();
getData();
list.setOnItemClickListener(new OnMyListItemClickListener());
}
Context context = this;
private class OnMyListItemClickListener implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(id!=-1){
Intent in = new Intent(context, Update.class);
in.putExtra("NUMTELEPHONE", ((HashMap<String, String>) list.getAdapter().getItem((int) id)).get("numtelephone")); //TAG_NUMTELEPHONE
startActivity(in);
}
}
}
Lesson learned - dont create sucha buttons - they are not aware in which item they are, so you cant extract the id - instead just use something like AlertDialog
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(id!=-1){
AlertDialog.Builder al = new AlertDialog.Builder(context);
al.setMessage("Are you sure you want to do it?");
al.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent in = new Intent(context, Update.class);
in.putExtra("NUMTELEPHONE", ((HashMap<String, String>) list.getAdapter().getItem((int) id)).get(TAG_NUMTELEPHONE));
startActivity(in);
}
});
al.setNegativeButton(android.R.string.no, null);
al.show();
}
}

promixitylistner working even after unregistring it

I am devolping an application which turns the screen off and on based proximity sensor. The code i wrote sucessful turns the screen off and on.
This is the acivity from which the proximity sensors are registed and unregistered
MainActivity.java
public class MainActivity extends Activity {
public String TAG = "MainActivity";
BackgroundService mService;
boolean mBound = false;
boolean firstTime = true;
Intent BackgroundIntent ;
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
Log.w(TAG, "Service Disconeted");
mBound = false;
mService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
LocalBinder binder = (LocalBinder)service;
mService = binder.getService();
mBound=true;
if(firstTime){
MainActivity.this.onStart();
}
firstTime = false;
Log.w(TAG, "Service Connectedd");
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.w(TAG, "onCreate()");
setContentView(R.layout.activity_main);
Button buttonStart = (Button)findViewById(R.id.button1);
Button buttonStop = (Button)findViewById(R.id.button2);
buttonStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mService.enableSensor();
Log.w(TAG, "ButtonStart Clicked");
}
});
buttonStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mBound){
mService.disableSensor();
}
Log.w(TAG, "ButtonSTOP Clicked");
}
});
startService(new Intent(this,BackgroundService.class));
}
#Override
public void onStart(){
super.onStart();
Log.w(TAG, "onStart Method");
Intent intent = new Intent(getApplicationContext(),BackgroundService.class);
getApplicationContext().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop(){
super.onStop();
if(mBound){
getApplicationContext().unbindService(mConnection);
Log.w(TAG, "Unbinding the service");
}
Log.w(TAG, "onStop Method");
}
}
This is the service which has a SensorEventListner which which listens to the changes in the proximity sensor
BackgroundService.java
public class BackgroundService extends Service{
public String TAG = "BackgroundService";
private final IBinder mBinder = new LocalBinder();
private SensorManager mSensorManager ;
private Sensor mProximitySensor ;
private SensorEventListener mSenosorEventListener;
private PowerManager.WakeLock proximityWakeLock;
public float maxSensorValue;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.e(TAG, "Binding with backgroundService");
return mBinder;
}
public class LocalBinder extends Binder{
BackgroundService getService(){
return BackgroundService.this;
}
}
#Override
public void onCreate(){
Log.w(TAG, "BackgroundService Created");
proximityWakeLock = ((PowerManager)getSystemService("power")).newWakeLock(32, "");
proximityWakeLock.setReferenceCounted(false);
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
maxSensorValue = mProximitySensor.getMaximumRange();
mSenosorEventListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if(event.sensor.getType() == Sensor.TYPE_PROXIMITY ){
if(event.values[0] == maxSensorValue)
{
Log.w(TAG, "Object moved ****AWAY*****");
screanTurnOn();
}
else{
Log.w(TAG, "Object moved ****NEAR******");
screanTurnOFF();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Sensor Accuracy Changed", Toast.LENGTH_SHORT).show();
}
};
}
#Override
public void onDestroy(){
mSensorManager.unregisterListener(mSenosorEventListener);
Log.w(TAG, "BackgroundService is Destroyed");
super.onDestroy();
}
public void screanTurnOFF(){
if(proximityWakeLock.isHeld()){
this.proximityWakeLock.release();
Log.e(TAG,"WakeLock is released");
}
}
public void screanTurnOn(){
if(!proximityWakeLock.isHeld())
proximityWakeLock.acquire();
while(proximityWakeLock.isHeld()){
Log.e(TAG, "WakeLock is acurqerd");
return;
}
}
public void enableSensor(){
if(mProximitySensor == null){
Log.w(TAG, "No Proximity detector found");
}else{
mSensorManager.registerListener(mSenosorEventListener, mProximitySensor,SensorManager.SENSOR_DELAY_NORMAL);
Log.w(TAG, "Proximity detector Enabled : "+ mProximitySensor.getName());
}
}
public void disableSensor(){
mSensorManager.unregisterListener(mSenosorEventListener,mProximitySensor);
Log.w(TAG, "Proximity Detector Disabled : " + EnableProximitySensor);
}
}
I have two buttons, one that registers the SensorEventListner to the sensor manager, and one to unregister it. The first button works perfectly. When i click on the second button, the ProximityEventListen remain unregistered.The sensoEventLister still works but the app will not show any Log messages from the BackGroundService.
If i comment out the screenTurnON() and screenTurnOFF() functions, the code works perfectly.
Please Help me out

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