Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an int value from one activity to other

Tags:

android

can anyone help what is the problem in my code

Activiy 1:

int view=1;
TabFunctionality.setFirstTabFunctionality(TabFunctionality.FIRST_TAB, 1);
Intent intent = new Intent(AdultTeeth.this, MainScreen.class);
Bundle b = new Bundle();
b.putInt("TEXT", view);                 
intent.putExtras(b);    
startActivityForResult(intent, TEETH_VIEW);
finish();

Activity 2:

Bundle b = this.getIntent().getExtras(); int view=b.getInt("TEXT");
like image 851
user828948 Avatar asked Oct 01 '11 09:10

user828948


3 Answers

You can directly use putExtra also.

Activity 1

Intent intent = new Intent(AdultTeeth.this, MainScreen.class);
intent.putExtra("int_value", int_variable);
startActivity(intent);

Activity 2

Intent intent = getIntent();
int temp = intent.getIntExtra("int_value", 0); // here 0 is the default value
like image 174
Lalit Poptani Avatar answered Oct 22 '22 15:10

Lalit Poptani


Passactivity:

 Intent i = new Intent(view.getContext(), Passactivity.class);        
 i.putExtra("font",selected_font);
 startActivity(i);

Receving activity

private int my_size;

 Intent i = getIntent();
     my_size = i.getIntExtra("size",20); // 20  for default value.
like image 33
RajaReddy PolamReddy Avatar answered Oct 22 '22 15:10

RajaReddy PolamReddy


The answers given are here aren't wrong but they are incomplete in my opinion. The best way to do this with validations is to make sure that the extra is taken from the previous Activity as well as the savedInstanceState which is the Bundle data received while starting the Activity and can be passed back to onCreate if the activity needs to be recreated (e.g., orientation change) so that you don't lose this prior information. If no data was supplied, savedInstanceState is null.

Sending data -

Intent intent = new Intent(context, MyActivity.class);
intent.putExtra("name", "Daenerys Targaryen");
intent.putExtra("number", "69");
startActivity(intent);

Receiving data -

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.myactivity);

    int no;
    String na;

    if(savedInstanceState == null){
        Bundle extras = getIntent().getExtras();

        if(extras != null){
            no = Integer.parseInt(extras.getString("number"));
            na = extras.getString("name");
        }

    }else{
        no = (int) savedInstanceState.getSerializable("number");
        na = (String) savedInstanceState.getSerializable("name");
    }

    // Other code
}
like image 30
SanVed Avatar answered Oct 22 '22 16:10

SanVed