android:onSaveInstanceState()

时间:2013-06-03 14:03:20

标签: android android-intent bundle

我尝试将字符串从一个活动传递到另一个活动。 这是活动A

中的编码
@Override
    public void onSaveInstanceState(Bundle savedInstanceState) {

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

活动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);    
    }

但当我将活动B 打开时,logcat显示第一个日志“UserName1”, 并将第二个日志“UserName2”显示为“null”。

我可能知道我的代码有什么问题吗?

我想要做的是当我点击“按钮”并意图活动B时,活动A传递活动B中的字符串。所以我可以在活动B中获得字符串值。

任何想法?因为我在使用intent.putStringExtra()和getintent.getStringExtra()时遇到错误,所以我改为使用onSaveInstanceState(),但仍然有问题。

修改 这是我的原始代码,我可以在活动B 中获取字符串,但意外的是我无法在Sqlite中保存我的数据。如果删除了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);

    }

活动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);
    }

活动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

    }

}

2 个答案:

答案 0 :(得分:0)

  

我可能知道我的代码有什么问题吗?

onSaveInstanceState()与在活动之间传递数据无关。相反,您需要在与Intent一起使用的startActivity()上添加额外的字符串。

  

因为我在使用intent.putExtra()和getintent.getExtra()时遇到错误

由于这是正确的方法(虽然使用getStringExtra()),请回到它并修正您遇到的任何错误。

答案 1 :(得分:0)

onSaveInstanceState不用于此目的,它用于保存您的活动状态,例如方向更改,或者当您离开活动并返回它时。 你需要的是使用意图。

除了启动活动之外,意图还可以在整个应用程序中携带一些信息,如下所示: 这将是活动1:

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

并在第二次活动中恢复它:

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