0

我正在开发一个具有以下场景的应用程序:

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

我通过 s 在每个值之间传递我的值ActivityIntent它可以工作,但是当我回到ActivityA 时,似乎所有值都被清除了。

来自ActivityC 的代码:

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

当我尝试获取这些值时,它们都是null.

编辑:

这是和的onCreate()代码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));

    }
}
4

3 回答 3

0

消除:

client.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

用于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
    }

 }
于 2015-06-08T11:28:48.370 回答
0

使用时FLAG_ACTIVITY_SINGLE_TOP,可以IntentonNewIntent()方法中检索,而不是在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 ....
}

对于 singleTop 活动,该onNewIntent()方法充当执行的入口点,而不是onCreate(). 因为Activity已经存在某处,onCreate()所以不被调用。

此外,startActivityForResult()在这种情况下使用其他一些帖子建议是错误的。回调onActivityResult()将在 C 中,而不是在 A 中。

于 2015-06-08T11:30:06.643 回答
0

在活动 C 中用这个替换你的代码:

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

在活动 A 中,只需通过以下方式获取值:

Intent intent= getIntent();
String value1 = intent.getStringExtra("TOKEN_VALUE");
String value2 = intent.getStringExtra("params");
于 2015-06-08T11:32:06.673 回答