Interstitial ads for coco2d android game - eclipse

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.

Related

Passing ExoPlayer instance from activity to binded service?

I'm trying to make a Video Player using ExoPlayer that can also work in the background and you can control it through the notification. I already created the ExoPlayer and the ForeGround Service for the notification and i binded them. At the moment it works as intended, the only problem is that i don't want the activity player to stop working when i close the notification. This happens because at the moment i'm creating the ExoPlayer instance in the service and then i pass the instance to the Activity, so when i close the notification the instance gets lost. Is there a way to initialize the player instance in the Activity and then pass that instance to the service so i can still control the video from the notification without risking to lose the instance once the notification is closed?
I'm pretty new to android and this is the first time that i'm binding a service to an activity so i don't really know how to do it. I tried searching on Google but that didn't help either.
This is the Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playerView=findViewById(R.id.player_view);
intent=new Intent(this,AudioPlayerService.class);
//here i will add the url that needs to be loaded
//but at the moment this is just a draft
Util.startForegroundService(this,intent);
playerView.setUseController(true);
//playerView.showController();
playerView.setControllerAutoShow(true);
playerView.setControllerHideOnTouch(true);
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
AudioPlayerService.LocalBinder binder = (AudioPlayerService.LocalBinder) iBinder;
mService = binder.getService();
mBound = true;
initializePlayer();
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBound = false;
}
};
#Override
public void onStart() {
super.onStart();
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
initializePlayer();
}
#Override
protected void onStop() {
unbindService(mConnection);
mBound = false;
super.onStop();
}
private void releasePlayer() {
if (player != null) {
player.release();
player = null;
}
}
private void initializePlayer() {
if (mBound) {
SimpleExoPlayer player = mService.getplayerInstance();
playerView.setPlayer(player);
}
}
}
This is the Service
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public SimpleExoPlayer getplayerInstance() {
if (player == null) {
startPlayer();
}
return player;
}
public class LocalBinder extends Binder {
public AudioPlayerService getService() {
return AudioPlayerService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
final Context context=this;
}
private void startPlayer() {
final Context context = this;
player = ExoPlayerFactory.newSimpleInstance(context, new DefaultTrackSelector());
ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory(new DefaultHttpDataSourceFactory("NotificationSync", 10000, 10000, true))
.createMediaSource(Uri.parse("https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"));
player.prepare(mediaSource);
player.setPlayWhenReady(true);
playerNotificationManager = PlayerNotificationManager.createWithNotificationChannel(context, "1",
R.string.app_name,
2,
new PlayerNotificationManager.MediaDescriptionAdapter() {
#Override
public String getCurrentContentTitle(Player player) {
return "title";
}
#Nullable
#Override
public PendingIntent createCurrentContentIntent(Player player) {
Intent intent = new Intent(context, MainActivity.class);
return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
#Nullable
#Override
public String getCurrentContentText(Player player) {
return "text";
}
#Nullable
#Override
public Bitmap getCurrentLargeIcon(Player player, PlayerNotificationManager.BitmapCallback callback) {
return null;
}
}, new PlayerNotificationManager.NotificationListener() {
#Override
public void onNotificationCancelled(int notificationId, boolean dismissedByUser) {
stopSelf();
}
#Override
public void onNotificationPosted(int notificationId, Notification notification, boolean ongoing) {
mNotification = notification;
mNotificationId = notificationId;
if (ongoing) {
startForeground(notificationId, notification);
}
}
}
);
playerNotificationManager.setPlayer(player);
playerNotificationManager.setUseStopAction(true);
}
#Override
public void onDestroy() {
releasePlayer();
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (player == null) {
//here i will get all the data from the intent that came from the
//activity (title,text,url...)
startPlayer();
}
return START_STICKY;
}
private void releasePlayer() {
if (player != null) {
player.release();
player = null;
}
}
}
In the end all i want to achieve is a video player that you start in the activity and also works/can be controlled through a notification without interruption when i go from activity->background and background->activity. If there are other ways to achieve this i'm open to try.

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

Deezer android sdk UI freeze during login

I implemented the Deeezer android SDK in my application and I got a user who can't log into its Deezer account on its Motorola Razr I. The login UI freezes on this page and the application restarts. He doesn't encounter the issue on its other devices.
The SDK version I use is 0.9.3
Here is a screenshot of the page where the application freezes.
What kind of information would help identify the issue?
Edit
Here is the source code :
public class LoginActivity extends Activity
{
protected static final String[] PERMISSIONS = new String[] {"basic_access", "manage_library", "delete_library", "listening_history", "manage_community"};
// DeezerConnect object
private DeezerConnect m_deezerConnect;
// Handle connection callbacks.
private DialogHandler m_dialogHandler = new DialogHandler();
// if the authentication failed, retry once
private boolean m_firstTry = true;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
m_deezerConnect = new DeezerConnectImpl(getString(R.string.deezer_app_id));
SessionStore sessionStore = new SessionStore();
AlertDialog.Builder deezerAuthDialog = new AlertDialog.Builder(this);
deezerAuthDialog.setTitle(R.string.deezer_authentication);
deezerAuthDialog.setMessage(R.string.enter_deezer_credentials);
deezerAuthDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
connectToDeezer(m_dialogHandler);
}
});
deezerAuthDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
finish();
}
});
deezerAuthDialog.setOnCancelListener(new DialogInterface.OnCancelListener()
{
#Override
public void onCancel(DialogInterface dialog)
{
finish();
}
});
deezerAuthDialog.show();
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onDestroy()
{
super.onDestroy();
}
/**
* Connects to Deezer web services using an injectable DialogListener listener.
* #param listener event listener that will be notified of the connection progress.
*/
private void connectToDeezer(final DialogListener listener)
{
m_deezerConnect.authorize(this, PERMISSIONS, listener);
}
/** Handle DeezerConnect callbacks. */
private class DialogHandler implements DialogListener
{
#Override
public void onComplete(final Bundle values)
{
SessionStore sessionStore = new SessionStore();
sessionStore.save(m_deezerConnect, LoginActivity.this);
LoginActivity.this.finish();
}
#Override
public void onDeezerError(final DeezerError deezerError)
{
Log.e(DeemoteGlobals.TAG, "DialogError error during login" , deezerError );
LoginActivity.this.finish();
}
#Override
public void onError(final DialogError dialogError)
{
// the api returns an error while the authentication succeed, so we force a retry once
int errorCode = dialogError.getErrorCode();
if (errorCode == -10 && m_firstTry)
{
m_firstTry = false;
connectToDeezer(m_dialogHandler);
return;
}
Log.e(DeemoteGlobals.TAG, "DialogError error during login", dialogError);
}
LoginActivity.this.finish();
}
#Override
public void onCancel()
{
LoginActivity.this.finish();
}
#Override
public void onOAuthException(OAuthException oAuthException)
{
LoginActivity.this.finish();
}
}
}

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