0

I'm developing an app with the following scenario:

Activity A -> Activity B -> Activity C -> Activity A

I pass my values between each Activity through the Intents, and it works, but when I come back to Activity A, it seems all values are cleaned.

Code from Activity C :

Intent client = new Intent(getApplicationContext(), ActivityA.class);
            client.putExtra("TOKEN_VALUE", TOKEN_VALUE);
            client.putExtra("PARAMS", params); // Hashmap with {"id":"value"}
            client.putExtra("PICLIST", picArray);
            client.putExtra("TESTLIST", testArray);
            client.putExtra("TESTDATA", myData);
            client.putExtra("TESTTEMP", myTemp);
            client.putExtra("COMPTEUR", compteur);
            client.putExtra("LAUNCH",first_launch);
            client.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(client);

When I try to get these values, they're all null.

EDIT:

Here is the code for onCreate() and onNewIntent():

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    // init the gps to get a location
    locationListener = new MyLocationListener();
    locationMangaer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);


    // Checking if Wifi is enabled
    final WifiManager wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    if (isSharingWiFi(wifi)) {
        new AlertDialog.Builder(this)
                .setCancelable(false)
                .setMessage("L' application requiert une connexion à Internet")
                .setPositiveButton("Accéder aux paramètres wifi ", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                    }

                })
                .setNegativeButton("Accéder aux paramètres du réseau mobile", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS));
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show().getWindow().setLayout(1000, 600);
    }

    mId = (EditText) findViewById(R.id.exam_valve);
    mName = (EditText) findViewById(R.id.exam_op);
    b1 = (Button) findViewById(R.id.take_picture);
    b2 = (Button) findViewById(R.id.add_exam_button);
    b3 = (Button) findViewById(R.id.addTest_button);
    b1.setOnClickListener(clickListenerBoutons);

    // Init and fill the two spinners
    condition_status = (Spinner) findViewById(R.id.spinner_valve_condition);
    reason_status = (Spinner) findViewById(R.id.spinner_exam_reason);

    ArrayAdapter<String> valve_condition_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item) {

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return super.getView(position, convertView, parent);
        }
    };

    valve_condition_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    valve_condition_adapter.add(getResources().getString(R.string.ok));
    conditionArray[0] = "ok";
    valve_condition_adapter.add(getResources().getString(R.string.rusty));
    conditionArray[1] = "rusty";
    valve_condition_adapter.add(getResources().getString(R.string.damaged));
    conditionArray[2] = "damaged";
    valve_condition_adapter.add(getResources().getString(R.string.broken));
    conditionArray[3] = "broken";
    condition_status.setAdapter(valve_condition_adapter);


    ArrayAdapter<String> exam_reason_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item) {

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return super.getView(position, convertView, parent);
        }
    };

    exam_reason_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    exam_reason_adapter.add(getResources().getString(R.string.programmed));
    reasonArray[0] = "programmed";
    exam_reason_adapter.add(getResources().getString(R.string.valve_installation));
    reasonArray[1] = "valve-installation";
    exam_reason_adapter.add(getResources().getString(R.string.improvised));
    reasonArray[2] = "improvised";
    reason_status.setAdapter(exam_reason_adapter);


    condition_status.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            condition = conditionArray[position];
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    reason_status.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            reason = reasonArray[position];
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    // Init the request queue
    mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    mRequestQueue.start();

    // Creating the Token to connect to the REST server


    final String myUrl = MY_SERVER_ADDRESS;
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, myUrl, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jsonObject) {
            exponent = jsonObject.optString("publicExponent");
            modulus = jsonObject.optString("publicModulus");
            ex = new BigInteger(exponent);
            mo = new BigInteger(modulus);
            Log.i("TEST REST ", ex.toString());
            Log.i("TEST REST ", mo.toString());
            try {
                key = RSACrypt.encrypt("temporary password", mo, ex);
                Log.i("TOKEN GENERATION", "La clé est : " + key);
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("password", key);
                String body = new JSONObject(params).toString().replace("\\", "");
                Log.i("JSON OBJECT", body);
                JsonRequest tokenRequest = new JsonStringRequest(Request.Method.POST, myUrl, body, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        TOKEN_VALUE = jsonObject.optString("token");
                        Log.i("TOKEN GENERATION", "Le token est : " + TOKEN_VALUE);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        String message = new String(volleyError.networkResponse.data);
                        Log.i("REQUETE 2", "Erreur" + volleyError.getMessage() + message);
                    }
                });
                mRequestQueue.add(tokenRequest);
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("ERROR TOKEN GENERATION", e.getMessage());
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            TOKEN_VALUE = "HOSTUNREACHABLE";
            Log.i("REQUETE 1", "Erreur" + volleyError.getMessage());
        }
    });
    mRequestQueue.add(request);

    // Sending the request with all parameters
    b2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Getting the current date
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
            String date = df.format(Calendar.getInstance().getTime());
            lon = locationMangaer.getLastKnownLocation(LOCATION_SERVICE).getLongitude();
            lat = locationMangaer.getLastKnownLocation(LOCATION_SERVICE).getLatitude();
            // Filling params
            params.put(REASON, reason);
            params.put(ID_VALVE, mId.getText().toString());
            params.put(OPERATOR, mName.getText().toString());
            params.put(DATE, date + "T00:00:00");
            params.put(CONDITION, condition);
            params.put(LONGITUDE, Double.toString(lon));
            params.put(LATITUDE, Double.toString(lat));

            for (int k = 0; k < pictureNameArray.length; k++) {
                Bitmap bm = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/MyApp/MyImages/" + pictureNameArray[k] + ".jpg");
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
                byte[] b = baos.toByteArray();
                String encodedImage = Base64.encodeToString(b, Base64.NO_WRAP);
                Log.i("PICTURE data", encodedImage);
                HashMap<String, String> currentPic = new HashMap<String, String>();
                currentPic.put(DATA, encodedImage);
                currentPic.put(FILENAME, pictureNameArray[k]);
                currentPic.put(MEDIATYPE, "image/jpg");
                PicList.put(new JSONObject(currentPic));
            }


            AlertDialog.Builder alert = new AlertDialog.Builder(HomeActivity.this);
            final EditText edittext = new EditText(getApplicationContext());
            alert.setMessage("Veuillez saisir un commentaire sur l'examen");
            alert.setTitle("Commentaire");
            alert.setView(edittext);
            alert.setPositiveButton("Continuer", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    String myComment = edittext.getText().toString();
                    params.put(COMMENT, myComment);

                    if (TOKEN_VALUE == "HOSTUNREACHABLE") {
                        // Save on SQL Lite + alert
                    } else {
                        Intent intent = new Intent(HomeActivity.this, SendMyRequestService.class);
                        intent.putExtra("PARAMS", params);
                        intent.putExtra("PICLIST", pictureNameArray);
                        intent.putExtra("TESTLIST", TestList.toString());
                        startActivity(intent);
                    }
                }
            });

            alert.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    params.clear();
                }
            });

            alert.show();


        }
    });

    b3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            params.put(REASON, reason);
            params.put(ID_VALVE, mId.getText().toString());
            params.put(OPERATOR, mName.getText().toString());
            params.put(CONDITION, condition);

            Intent intent = new Intent(HomeActivity.this, ListDeviceActivity.class);
            intent.putExtra("COMPTEUR", pictureNumber);
            intent.putExtra("TOKEN_VALUE", TOKEN_VALUE);
            intent.putExtra("PARAMS", params);
            intent.putExtra("PICLIST", pictureNameArray);
            intent.putExtra("TESTLIST", TestList.toString());
            startActivity(intent);
        }
    });


@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    String TOKEN_VALUE = intent.getStringExtra("TOKEN_VALUE");
    String params = intent.getStringExtra("params");
    String test_data = intent.getStringExtra("TESTDATA");
    String test_temp = intent.getStringExtra("TESTTEMP");
    String testArray = intent.getStringExtra("TESTLIST");

    try {
        JSONObject parameters = new JSONObject(params);
        Log.i("Id valve récuperé", parameters.optString("ID_VALVE"));
        Log.i("Raison récuperée", parameters.optString("REASON"));
        Log.i("Nom opérateur récuperé", parameters.optString("OPERATOR"));
        Log.i("Condition récuperée", parameters.optString("CONDITION"));
        if (parameters.optString("ID_VALVE") != null)
            mId.setText(parameters.optString("ID_VALVE"));
        if (parameters.optString("REASON") != null) {
            int i = this.getResources().getIdentifier(parameters.optString("REASON"), "string", this.getPackageName());
            reason_status.setSelection(i);
        }
        if (parameters.optString("OPERATOR") != null)
            mName.setText(parameters.optString("OPERATOR"));
        if (parameters.optString("CONDITION") != null) {
            int j = this.getResources().getIdentifier(parameters.optString("CONDITION"), "string", this.getPackageName());
            condition_status.setSelection(j);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (intent.getStringArrayExtra("PICLIST") != null) {
        pictureNameArray = intent.getStringArrayExtra("PICLIST");
    }
    HashMap<String, String> currentTest = new HashMap<String, String>();
    if (testArray != null) {
        try {
            TestList = new JSONArray(testArray);
            currentTest.put(TDATA, test_data);
            currentTest.put(TEMP, test_temp);
            TestList.put(new JSONObject(currentTest));
            } catch (JSONException e) {
            e.printStackTrace();
        }
    } else {
        currentTest.put(TDATA, test_data);
        currentTest.put(TEMP, test_temp);
        TestList.put(new JSONObject(currentTest));

    }
}
Yash Sampat
  • 30,051
  • 12
  • 94
  • 120
Ideor
  • 5
  • 5
  • Use `startActivityForResult()`. Also read life cycle of `Activity`'s. – Piyush Jun 08 '15 at 11:22
  • I already use startActivityForResult to take photos with the camera (picArray is the array of pictures' name). – Ideor Jun 08 '15 at 11:40

3 Answers3

0

Remove:

client.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

Use in ActivityA:

   @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
       if (resultCode == Activity.RESULT_OK && data != null) {
     //do some action
    }

 }
Piyush
  • 18,895
  • 5
  • 32
  • 63
Suman Dey
  • 66
  • 1
  • 10
0

When you use FLAG_ACTIVITY_SINGLE_TOP, you can retrieve the Intent in the onNewIntent() method, not in onCreate().

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    String TOKEN_VALUE = intent.getStringExtra("TOKEN_VALUE");
    String params = intent.getStringExtra("params");
    // and so on ....
}

For singleTop Activities, the onNewIntent() method acts as an entry point which is executed instead of onCreate(). Because the Activity already exists somewhere, onCreate() is not called.

Also, using startActivityForResult() in this situation as some of the other posts have suggested is wrong. The callback to onActivityResult() will be in C, not in A.

Yash Sampat
  • 30,051
  • 12
  • 94
  • 120
  • This supports loop ? Because my app needs to get the scenario many times. – Ideor Jun 08 '15 at 11:46
  • On Activity A i have 3 buttons (one is photo with the onActivityResult , one starts ActivityB , and the last send jsonrequest) , I need to copy the code from onCreate in onNewIntent ? – Ideor Jun 08 '15 at 12:04
  • no. only the code for getting the data from the `Intent` when you go from C to A. – Yash Sampat Jun 08 '15 at 12:13
  • Ok , but I use the data to setSelection of 2 spinners, and setText in 2 EditText. How can I do it ? – Ideor Jun 08 '15 at 12:20
  • It doesn't work for me , when I come back in Activity A , it executes the code of onCreate . – Ideor Jun 08 '15 at 13:15
  • Yes, `onCreate()` will always execute. Please post the code of `onCreate()` and `onNewIntent()` .... :) – Yash Sampat Jun 08 '15 at 13:28
  • Done (: I need more explaination . – Ideor Jun 08 '15 at 13:33
  • I've just found my problem , I just declare my spinner for all the class (not only for onCreate). Thanks a lot for your solution – Ideor Jun 08 '15 at 14:15
0

Replace your code with this in Activity C:

Intent i = new Intent(ActivityC.this, ActivityA.class);
i.putExtra("TOKEN_VALUE", TOKEN_VALUE);
i.putExtra("PARAMS", params);
startActivity(i);

And in Activity A, simply get the values by:

Intent intent= getIntent();
String value1 = intent.getStringExtra("TOKEN_VALUE");
String value2 = intent.getStringExtra("params");
Yohan Blake
  • 1,298
  • 4
  • 21
  • 43