0

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

    }

}
user2301281
  • 757
  • 2
  • 12
  • 27

2 Answers2

0

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • sorry, edited my question. There have no error when I using getStringExtra(). The log message shown I had successively pass the string value. But don't why it can't shown the expected result for other part. (I want save the String in sqlite but it fail to save have no error, no reason. I even use the toast massage the check d progress, the toast massage can show but don't know why it can't save in sqlite, but when I remove the "putStringExtra" then everything go smoothly.>.<) That is the reason I try use another method to get the String. – user2301281 Jun 03 '13 at 14:14
0

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");
Marko Niciforovic
  • 3,561
  • 2
  • 21
  • 28
  • Yes. I try this method before, just getting unexpected result (as I explain in comment below.) So may I know is it another method than that? I had ask in this post. http://stackoverflow.com/questions/16892411/android-send-get-string-besides-by-using-extra-method – user2301281 Jun 03 '13 at 14:17
  • you can use shared preferences but this is very basic thing and not many things can go wrong to get unexpected result. Check if you didnt mix up keys somewhere or show us code so we can help you better – Marko Niciforovic Jun 03 '13 at 14:23
  • also there is no need to use putStringExtra or getStringExtra, only putExtra and getString is enough – Marko Niciforovic Jun 03 '13 at 14:24
  • I edited my question, what code else I need to shown? How to use shared preferences? – user2301281 Jun 03 '13 at 14:24
  • for shared preferences check my answer here http://stackoverflow.com/questions/15428606/save-editbox-values-in-the-custom-listview/15428662#15428662 but that is not their purpose, this is intent purpose, just try with my code above I'm sure it will work. – Marko Niciforovic Jun 03 '13 at 14:26
  • where should I put shared preferences method? under onCreate(Bundle)? – user2301281 Jun 03 '13 at 14:32
  • wherever you want to use them if onCreate then onCreate, they are global you can use then anywhere but again, that is not their purpose I suggest you to go and fix intent problem. Its what they are made to do just try putExtra and getString and doublecheck your keys cuz they are case sensitive – Marko Niciforovic Jun 03 '13 at 14:34
  • Noted. Actually I can get the String value I pass in Activity B (Check by using log, and my project shown no error.). just it affected my other result. Thanks. – user2301281 Jun 03 '13 at 14:36
  • no problem, if you found me any help vote so this question doesnt show up as unanswered or deleted for same reason :) – Marko Niciforovic Jun 03 '13 at 14:37
  • I just try this shared preferences method, finally it's work. Thanks again. =D – user2301281 Jun 03 '13 at 14:52