简体   繁体   English

android:onSaveInstanceState()

[英]android: onSaveInstanceState ()

I try to pass a string from one activity to another activity. 我尝试将字符串从一个活动传递到另一个活动。 This is the coding in Activity A : 这是活动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: 活动B中,我使用以下代码获取字符串:

@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". 但是,当我单击“ 活动B ”的打开按钮时,logcat显示了第一个日志“ UserName1”,而将第二个日志“ UserName2”显示为“ 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. 我想做的是,当我单击“按钮”并打算向活动B传递时,活动A在活动B中传递字符串。因此,我可以在活动B中获得字符串值。

Any Idea? 任何想法? Cause I getting error when using intent.putStringExtra() and getintent.getStringExtra(), so I change to use onSaveInstanceState (), but still having problem. 原因我在使用intent.putStringExtra()和getintent.getStringExtra()时遇到错误,所以我更改为使用onSaveInstanceState(),但仍然有问题。

EDIT: This is my original code, I can get the String in Activity B , but unexpected I can't save my data in Sqlite. 编辑:这是我的原始代码,我可以在Activity B中获取String,但出乎意料的是我无法在Sqlite中保存数据。 If remove the putString Extra then everything go smoothly. 如果删除putString Extra,那么一切都会顺利进行。

@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: 活动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: 活动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. onSaveInstanceState()与活动之间传递数据无关。 Instead, you need to put your string in an extra on the Intent used with startActivity() . 相反,您需要将字符串放在与startActivity()一起使用的Intent

Cause I getting error when using intent.putExtra() and getintent.getExtra() 原因在使用intent.putExtra()和getintent.getExtra()时出现错误

Since that is the correct approach (albeit using getStringExtra() ), please go back to it and fix whatever error you are encountering. 由于这是正确的方法(尽管使用getStringExtra() ),所以请返回至该方法并修复遇到的任何错误。

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. onSaveInstanceState并非用于此目的,它用于保存您的活动状态(例如方向更改),或者当您离开活动并返回活动时。 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: 除了开始活动,意图还可以在整个应用程序中携带一些信息,例如:这是活动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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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