0

我尝试将字符串从一个活动传递到另一个活动。这是活动 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);    
    }

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

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

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

任何想法?因为在使用intent.putStringExtra() 和getintent.getStringExtra() 时出错,所以我改用onSaveInstanceState(),但还是有问题。

编辑:这是我的原始代码,我可以在Activity 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

    }

}
4

2 回答 2

0

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

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

因为使用 intent.putExtra() 和 getintent.getExtra() 时出现错误

由于这是正确的方法(尽管使用getStringExtra()),请返回并修复您遇到的任何错误。

于 2013-06-03T14:05:58.153 回答
0

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

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

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

并在第二个活动中恢复它使用:

String username = getIntent().getExtras().getString("UserName");
于 2013-06-03T14:10:11.813 回答