简体   繁体   中英

android: onSaveInstanceState ()

I try to pass a string from one activity to another activity. This is the coding in Activity A :

@Override
    public void onSaveInstanceState(Bundle savedInstanceState) {

      savedInstanceState.putString("UserName", UserName);
      Log.i(Tag, "UserName1: "+ UserName);
      super.onSaveInstanceState(savedInstanceState);
    }

In Activity B I use this code to get the string:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_item);
        setUpViews();


        if (savedInstanceState != null){
            UserName = savedInstanceState.getString("UserName");            
          }
        Log.i(Tag, "UserName2: "+ UserName);    
    }

But the logcat shown the first log "UserName1" when I clikc the open to Activity B , and show the second log "UserName2" as "null".

May I know what wrong with my code?

What I want to do is Activity A pass the String in Activity B when I click the "button" and intent to Activity B. So I can get the String value in Activity B.

Any Idea? Cause I getting error when using intent.putStringExtra() and getintent.getStringExtra(), so I change to use onSaveInstanceState (), but still having problem.

EDIT: This is my original code, I can get the String in Activity B , but unexpected I can't save my data in Sqlite. If remove the putString Extra then everything go smoothly.

@Override
    public boolean onOptionsItemSelected(MenuItem item) {       
        Intent addItem = new Intent(ItemActivity.this, AddEditItem.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        addItem.putStringExtra("UserName", UserName);
        Log.e(Tag, "UseName: "+ UserName);
        startActivity(addItem);     
        return super.onOptionsItemSelected(item);

    }

Code in Activity B:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_item);
        setUpViews();


        UserName = (String) getIntent().getStringExtra("UserName"); 
        Log.e(Tag, "UserName3: "+ UserName);
    }

Full code for Activity B:

public class AddEditItem extends Activity implements OnItemSelectedListener {

    private static final String Tag = null;
    private EditText inputItemName;
    private EditText inputItemCondition;
    private EditText inputEmail;
    private Button btnGal, btnConfirm;
    private Bitmap bmp;
    private ImageView ivGalImg; 
    private Spinner spinner;
    String[] category =  {"Books", "Clothes & Shoes", "Computer", "Electronics", "Entertainment", "Food & Drinks", 
            "Furnitures", "Mobile Phone", "Other", "UKM"};
    String selection;
    String filePath, itemName, itemCondition;   
    String UserName, user;
    private int id;
    private byte[] blob=null;
    byte[] byteImage2 = null;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_item);
        setUpViews();


        if (savedInstanceState != null){
            UserName = savedInstanceState.getString("UserName");            
          }
        Log.e(Tag, "UserName2: "+ UserName);

        //UserName = (String) getIntent().getStringExtra("UserName");   
        //Log.e(Tag, "UserName3: "+ UserName);
    }


    private void setUpViews() {

        inputItemName = (EditText)findViewById(R.id.etItemName);
        inputItemCondition = (EditText)findViewById(R.id.etItemCondition);
        inputEmail = (EditText)findViewById(R.id.etEmail);
        ivGalImg = (ImageView) findViewById(R.id.ivImage);      

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(AddEditItem.this, android.R.layout.simple_spinner_dropdown_item, category);

        spinner = (Spinner)findViewById(R.id.spnCategory);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);

        Bundle extras = getIntent().getExtras();

        if (extras != null) {
            id=extras.getInt("id");
            user=extras.getString("user");
            inputItemName.setText(extras.getString("name"));
            inputItemCondition.setText(extras.getString("condition"));          
            inputEmail.setText(extras.getString("email"));  
            selection = extras.getString("category");

            byteImage2 = extras.getByteArray("blob");

            if (byteImage2 != null) {
                if (byteImage2.length > 3) {
                    ivGalImg.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2,0,byteImage2.length));
                }
            }

        }


        btnGal = (Button) findViewById(R.id.bGallary);
        btnGal.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(intent, 0);
            }
        });

        btnConfirm = (Button) findViewById(R.id.bConfirm);
        btnConfirm.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (inputItemName.getText().length() != 0 && inputItemCondition.getText().length() != 0
                        && inputEmail.getText().length() != 0) {
                    AsyncTask<Object, Object, Object> saveItemTask = new AsyncTask<Object, Object, Object>() {
                        @Override
                        protected Object doInBackground(Object... params) {
                            saveItem();
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Object result) {
                            Toast.makeText(getApplicationContext(),
                                    "Item saved", Toast.LENGTH_LONG)
                                    .show();
                            finish();

                        }
                    };

                    saveItemTask.execute((Object[]) null);
                    Toast.makeText(getApplicationContext(),
                            "Item saved reconfirm", Toast.LENGTH_LONG)
                            .show();
                } else {
                    AlertDialog.Builder alert = new AlertDialog.Builder(
                            AddEditItem.this);
                    alert.setTitle("Error In Save Item");
                    alert.setMessage("You need to fill in all the item details");
                    alert.setPositiveButton("OK", null);
                    alert.show();
                }
            }
        });
    }

    private void saveItem() {

        if(bmp!=null){
            ByteArrayOutputStream outStr = new ByteArrayOutputStream();
            bmp.compress(CompressFormat.JPEG, 100, outStr);
            blob = outStr.toByteArray();
        }

        else{blob=byteImage2;}

        ItemSQLiteConnector sqlCon = new ItemSQLiteConnector(this);

        if (getIntent().getExtras() == null) {
            sqlCon.insertItem(UserName, inputItemName.getText().toString(), 
                    inputItemCondition.getText().toString(),        
                    inputEmail.getText().toString(), 
                    selection, blob);
        }

        else {
            sqlCon.updateItem(id, UserName, inputItemName.getText().toString(), 
                    inputItemCondition.getText().toString(),    
                    inputEmail.getText().toString(),
                    selection, blob);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,Intent resultdata) {
        super.onActivityResult(requestCode, resultCode, resultdata);
        switch (requestCode) {
        case 0:
            if (resultCode == RESULT_OK) {
                Uri selectedImage = resultdata.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filePath = cursor.getString(columnIndex);

                cursor.close();
                // Convert file path into bitmap image using below line.
                bmp = BitmapFactory.decodeFile(filePath);
                ivGalImg.setImageBitmap(bmp);
            }

        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, 
            int pos, long id) {
        // TODO Auto-generated method stub
        TextView tv = (TextView)view;
        selection = tv.getText().toString(); 

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

}

May I know what wrong with my code?

onSaveInstanceState() has nothing to do with passing data between activities. Instead, you need to put your string in an extra on the Intent used with startActivity() .

Cause I getting error when using intent.putExtra() and getintent.getExtra()

Since that is the correct approach (albeit using getStringExtra() ), please go back to it and fix whatever error you are encountering.

onSaveInstanceState is not used in that purpose, its used to save your activity state on for example orientation change, or when you leave an activity and get back to it. What you need is to use intents.

Other than starting activity, intents can also carry some information throughout app, like this: This would be activity 1:

Intent = new Intent (getApplicationContext(), Activity2.class);
intent.putExtra("UserName", UserName);
startActivity(intent);

and to recover it in second activity use:

String username = getIntent().getExtras().getString("UserName");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM