2

I want to save the details of activities of user even if he closed the app by pressing back button or changed the orientation.I used shared prefences but i don't know how it works.i saw in different programmings using sharepreferences to save data.But i can't do it.Is there any changes i have to do. Here is my code:

package tmt.niranjan.travellingtrack;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.ActivityRecognitionClient;

public class MainActivity extends Activity implements GooglePlayServicesClient.ConnectionCallbacks,GooglePlayServicesClient.OnConnectionFailedListener {

private ActivityRecognitionClient arclient;
private PendingIntent pIntent;
private BroadcastReceiver receiver;
private TextView tvActivity;
public static final String SHARED_PREFERENCES =
        "tmt.niranjan.travellingtrack.SHARED_PREFERENCES";
 public static final String KEY_LOG_FILE_NUMBER =
            "tmt.niranjan.travellingtrack.KEY_LOG_FILE_NUMBER";
  public static final String KEY_LOG_FILE_NAME =
            "tmt.niranjan.travellingtrack.KEY_LOG_FILE_NAME";
  public static final String KEY_LOG_FILE_NAME1 =
            "tmt.niranjan.travellingtrack.KEY_LOG_FILE_NAME";
  public static final String KEY_PREVIOUS_ACTIVITY_TYPE =
            "tmt.niranjan.travellingtrack.KEY_PREVIOUS_ACTIVITY_TYPE";
private SharedPreferences mpref;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tvActivity = (TextView) findViewById(R.id.Actrec);
    mpref = getApplicationContext().getSharedPreferences(
            SHARED_PREFERENCES, Context.MODE_PRIVATE);

    int resp =GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if(resp == ConnectionResult.SUCCESS){
        arclient = new ActivityRecognitionClient(this, this, this);
        arclient.connect();


    }
    else{
        Toast.makeText(this, "Please install Google Play Service.", Toast.LENGTH_SHORT).show();
    }

    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Editor editor = mpref.edit();
            String v =  "Type:"+intent.getExtras().getInt("Type")+" "+"Activity :" + intent.getStringExtra("Activity") + " " + "Confidence : " + intent.getExtras().getInt("Confidence") + "\n";
            editor.putInt(KEY_PREVIOUS_ACTIVITY_TYPE,intent.getExtras().getInt("Type"));
            editor.putString(KEY_LOG_FILE_NAME, "Activity");
            editor.putInt(KEY_LOG_FILE_NUMBER, intent.getExtras().getInt("Confidence"));
            editor.putString(KEY_LOG_FILE_NAME1,v);



            tvActivity.setText(v);

            editor.commit();
        }
      };

     IntentFilter filter = new IntentFilter();
     filter.addAction("tmt.niranjan.myactivityrecognition.ACTIVITY_RECOGNITION_DATA");
     registerReceiver(receiver, filter);

}


@Override
protected void onDestroy() {
    super.onDestroy();
    if(arclient!=null){
        arclient.removeActivityUpdates(pIntent);
        arclient.disconnect();
    }
    Toast.makeText(this, "ondestroycalled", Toast.LENGTH_SHORT).show();
    unregisterReceiver(receiver);
}

@Override
public void onConnectionFailed(ConnectionResult arg0) {
    Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();
}
@Override
public void onConnected(Bundle arg0) {
    Intent intent = new Intent(this, ActivityRecognitionService.class);
    pIntent = PendingIntent.getService(this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
    arclient.requestActivityUpdates(1000, pIntent);   
}
@Override
public void onDisconnected() {
}

}

Niranjan
  • 1,879
  • 2
  • 22
  • 28
  • `But i can't do it` - ????? `onDestroy()` is a bad choice. `onPause()` or `onStop()` are probably better. – Simon Jul 24 '14 at 12:11
  • It's really not clear what you are asking. The way you get these values back out of SharedPreferences is by calling `mPrefs.getInt(NAME, DEFAULT_VALUE)` and changing it for ints, booleans, Strings, etc. I don't see anywhere that you are trying to get these values back. – anthonycr Jul 24 '14 at 12:50
  • Here i am trying to access values by tvActivity.setText(v).I am saving String v value in sharedpreferences. i am expecting to get the previous and present values of v. is it wrong? – Niranjan Jul 24 '14 at 13:08

1 Answers1

0

You are missing editor.apply(); before editor.commit();

Give it a go and see if it works

Here is code that I use and works fine, so if it is not editor.apply then it would suggest that nothing is being set from your intents.getextra, have you debugged to see if these contain a value?

SharedPreferences.Editor editor = prefs.edit();
            editor.putString("key_pref_branch_code", mainObject.getString("Code"));
            editor.putString("key_pref_branch_id", mainObject.getString("ID"));
            editor.putString("key_pref_branch_name", mainObject.getString("Name"));
            editor.putString("key_pref_json_url", "http://xxxxx:8080/storehandler.ashx");
            editor.apply();
            editor.commit();
dave
  • 1,410
  • 1
  • 16
  • 42
  • I added editor.apply() but it is not working. plz go through the code suggest me if there i did any mistakes – Niranjan Jul 24 '14 at 12:36
  • 1
    editor.apply() and editor.commit() are basically synonymous (http://stackoverflow.com/questions/5960678/whats-the-difference-between-commit-and-apply-in-shared-preference), this is not the answer. – anthonycr Jul 24 '14 at 12:37
  • Then please give me the right answer @A.C.R.Development – Niranjan Jul 24 '14 at 12:42
  • @Niranjan, just demanding answers is not the way you do things on here! What else have you tried? For instance what is the value of intent.getExtras().getInt("Confidence")); when debugging? – dave Jul 24 '14 at 12:44
  • ya i have created another class called ActivityRecognitionService.java i am accessing the confidence,type,Activity values.Here confidence is nothing but the probability of the activity because the google services may not give 100% gaurantee of activity of user it will give probabilities of deferent activities and we can acces most probable activity....If you want i will post the another class also – Niranjan Jul 24 '14 at 13:03