I have this code:
Rechercher.java:
public void doOnResult(String json){
if ( json.equals("Aucune propostion pour le mois")||json.equals("Aucune propostion pour cette date")) {
Toast.makeText(Rechercher.this, "Aucune proposition actuellement.", Toast.LENGTH_LONG).show();
finish();
} else {
Intent iAfficher = new Intent(this, Afficher.class);
extras.putString("json", json);
extras.putInt("nbplaces", mCounter);
iAfficher.putExtras(extras);
this.startActivityForResult(iAfficher, 10);
}
}
Afficher.java:
Integer places = extras.getInt("nbplaces");
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.afficher);
ListView lvTrajets = (ListView)findViewById(R.id.lvTrajets);
Bundle bundle = getIntent().getExtras();
.......
proposition.put("Date",propId);
proposition.put("Trajet", propLieu+" de "+propVille+" --> "+propGare+" Places : "+places);
The places variable is always equal to 0.
I don't know why I can't get the right value.
You need to get the value from the Bundle in your Afficher.java file in your onCreate method as below:
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.afficher);
ListView lvTrajets = (ListView)findViewById(R.id.lvTrajets);
Bundle bundle = getIntent().getExtras();
Integer places = bundle.getInt("nbplaces"); //get value here
String jsonval=bundle.getString("json");
put the following line after the bundle declaration inside onCreate() method
Integer places = bundle.getInt("nbplaces");
and remove the following line
Integer places = extras.getInt("nbplaces");
try this please:
Integer places ;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.afficher);
Bundle bundle = getIntent().getExtras();
places = bundle.getInt("nbplaces")
...........
Move this Integer places = extras.getInt("nbplaces"); inside onCreate. Also initialization of extras.
public Intent getIntent ()
Added in API level 1
Return the intent that started this activity.
Instead of Integer places use int places. int is a primitive data type so use int instead of Integer for primitive data types.
int places;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.afficher);
Bundle extras = getIntent().getExtras();
places = extras.getInt("nbplaces");
You need to wait till the activity is created then use getIntent()
http://developer.android.com/reference/android/os/Bundle.html#getInt(java.lang.String)
public int getInt (String key)
Added in API level 1
Returns the value associated with the given key, or 0 if no mapping of the desired type exists for the given key.
Parameters
key a String
Returns
an int value
Related
Calling code (run in service):
Intent textIntent = new Intent(this, TextActivity.class);
textIntent.putExtra("text_seq", message.xfer.seq);
textIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(textIntent);
Called code (in TextActivity):
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
Log.d(TAG, "" + bundle.getInt("text_seq"))
...
In fact the whole bundle is lost - the code above throws an NPE when calling bundle.getInt().
I'm sure there's something obvious I have missed...
Bundle you are reading is NOT for that purpose. As per docs
void onCreate (Bundle savedInstanceState)
Bundle: If the activity is being re-initialized after previously being
shut down then this Bundle contains the data it most recently supplied
in onSaveInstanceState(Bundle). Note: Otherwise it is null.
If you need to get extras you need to call:
Bundle extras = getIntent().getExtra();
and then you can try to get your values:
int myVal = extras.getInt(key);
Alternatively you can try to use:
int myVal = getIntent().getIntExtra(key, defaultVal);
Have you tried using getIntent().getInt("text_seq") ?
get your bundle like this
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
Bundle intentBundle = getIntent().getExtra();
Log.d(TAG, "" + intentBundle.getExtra(“text_seq"))
}
The bundle you're using is the savedInstanceState you can read more about it here.
What you need to use is this:
Bundle intentBundle = getIntent().getExtra();
Since you added the bundle to Intent extras, so you need to get it from the getIntent().getExtra()
also you can get individual items like this :
getIntent().getIntExtra("text_seq", defaultValToReturn);
I am sending data from one activity to another through intent. I am sending two different strings but getting same value for both variable on next activity.
Here is my code :
public class Quizzes extends ActionBarActivity {
protected static final String QUIZ_TITLE = null;
protected static final String COURSE = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quizzes);
listView = (ListView) findViewById(R.id.listview);
String[] values = new String[] { "Quiz # 2" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
// ListView Item Click Listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
Intent intent = new Intent(getApplicationContext(), QuizDetail.class);
intent.putExtra(QUIZ_TITLE, item);
final String course = (String)textview.getText();
intent.putExtra(COURSE, course);
startActivity(intent);
}
});
}
}
If you see i am passing two string intent object :
1. QUIZ_TITLE
2. COURSE
When i debugged the application, I can see values like
1. QUIZ_TITLE = "Quiz # 1"
2. COURSE = "Intro to Computing"
All fine until here, but when i am retrieving these string on other activity, I am getting value "Intro to Computing" for both, here is code from that class.
public class QuizDetail extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_detail);
Intent intent = getIntent();
String quizTitle = intent.getStringExtra(Quizzes.QUIZ_TITLE);
TextView quizTitleTextView = (TextView) findViewById(R.id.quizTitle);
quizTitleTextView.setText(quizTitle+" : TESTING..");
String courseTitle = intent.getStringExtra(Quizzes.COURSE);
TextView courseTitleTextView = (TextView) findViewById(R.id.courseTitle);
courseTitleTextView.setText(courseTitle);
}
}
I am not sure why I am getting same value "Intro to computing" from Quizzes.QUIZ_TITLE and Quizzes.COURSE.
Any help would be highly appreciated.
Thanks..
Anjum
You are using bad the intent.putExtra(),
You need to put a key (you need to know) as first param, to get the object in the other activity like:
...
String item = ...;
intent.putExtra("COURSE", item);
...
And you get the extras with:
...
intent.getStringExtra("COURSE");
...
Edited !!!
There's a couple of things here that should be mentioned.
QUIZ_TITLE and COURSE are both null (I can't see where they're set)
When you add something to the Extras Bundle, you're placing values in to a dictionary. The key for this dictionary you're using, in this case, is null. This means the second time you're putting in to the dictionary, QUIZ_TITLE (null) is being replaced with the key COURSE (null).
If you change QUIZ_TITLE and COURSE to an actual String value, it should sort that problem.
The second thing to note, is that there's a difference between getExtraString and getExtras.getString. I have written about this here
Hope that helps.
Please try this
Intent intent = getIntent();
String quizTitle = intent.getExtras().getString(Quizzes.QUIZ_TITLE);
String courseTitle = iintent.getExtras().getString(Quizzes.COURSE);
Update:
Oh now i see it too:
protected static final String QUIZ_TITLE = null;
protected static final String COURSE = null;
is really fatal because using a null value for a key is not useful and even if it is possible you are setting your value for the key 'null' first and overwrite it then by setting the value for key 'null' again.
Change it to:
protected static final String QUIZ_TITLE = "extra_quiz_title"
protected static final String COURSE = "extra_course";
for example
In my android app, I store a value 1 in a bundle, and then start the activity, then I read the bundle value from the new activity, and its 0. I'm not sure what's going wrong...
content.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent myIntent = new Intent(context, ThreadScreen.class);
myIntent.putExtra("thread_id", Integer.toString(thread.getId(), 10));
context.startActivity(myIntent);
Transition.TransitionForward(context);
}
});
the myIntent mExtras = Bundle[{thread_id=1}].
This code, puts a value 1 with key thread_id. Then I start the activity, and then I read it here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thread_screen);
// activates the action bar
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
int thread_id = getIntent().getExtras().getInt("thread_id");
setUpScreen(thread_id);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
Here thread_id has a value of 0. Does anyone know what's wrong?
Thanks
You are writing a String key and reading an int. To write and read the same key, you need to use putExtra(String, int) and getInt.
getIntent().getExtras() will give you bundle
In your case you have put String type value in Intent Extra
So to get the value in ThreadClass Activity do below
int thread_id = Integer.parseInt(getIntent().getStringExtra("thread_id"));
Hope this helps
I have an class Voice, which extends Activity, and contains a counter. When the user answers correctly, the counter adds one via counter++;
public class Voice extends Activity implements OnClickListener{
ListView lv;
static final int check = 111;
int counter_score;
TextView txView;
MediaPlayer ourSong;
ImageView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.letter_a);
initialize();
}
private void initialize() {
lv = (ListView)findViewById(R.id.lvVoiceReturn);
Button b = (Button)findViewById(R.id.imageButtonSelector);
txView = (TextView)findViewById(R.id.counter);
b.setOnClickListener(this);
counter_score=0;
}
This score, is bundled and passed on to the next activity "What" within a string "your score is 1".
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == check && resultCode == RESULT_OK) {
ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
lv.setAdapter( new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
if(results.contains("hey") || results.contains("a") || results.contains("ay")) {
//toast referenced to xml the after 400ms
counter_score++;
txView.setText("Your Score is" + " " + counter_score);
AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
dialogBuilder.setTitle("AWSOME");
dialogBuilder.setMessage("¡Your current score is" + counter_score);
dialogBuilder.setIcon(R.drawable.ic_mark);
dialogBuilder.show();
ourSong = MediaPlayer.create(Voice.this, R.raw.rightsound2);
ourSong.start();
Thread timer = new Thread() {
public void run(){
try {
sleep(2500);
}catch (InterruptedException e){
e.printStackTrace();
} finally {
String score = txView.getText().toString();
Bundle keeper = new Bundle();
keeper.putString("key", score);
Intent putScore = new Intent(Voice.this, What.class);
putScore.putExtras(keeper);
startActivity(putScore);
}
}
};
timer.start();
}
}
The next Activity, What, gets this Bundle and displays it fine using setText(gotScore)
public class What extends Activity implements OnClickListener {
ListView lv;
static final int check = 111;
private int counter_score;
TextView txView;
MediaPlayer ourSong;
ImageView display;
String gotScore;
String classes[] = {"What", "Pagina", "What", "example3", "example4", "example5",
"example6"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.letter_b);
initialize();
Bundle gotKeeper = getIntent().getExtras();
gotScore = gotKeeper.getString("key");
txView.setText(gotScore);
}
private void initialize() {
// TODO Auto-generated method stub
lv = (ListView)findViewById(R.id.lvVoiceReturn);
Button b = (Button)findViewById(R.id.imageButtonSelector);
txView = (TextView)findViewById(R.id.counter);
b.setOnClickListener(this);
..this is when things go bad :(
On What I have another question tied to a counter as well. When the user answers correctly the counter adds one via counter++; and it does. However, it changes the txview string to "your score is 1". I can't get it to add 1 to the counter result passed from the previous activity within the string, so that the counter on What reads "your score is 2". This gets passes to the next activity in Bundle keeper, which holds the aggregate score.
I've read a few tutorials on passing an int verses a string, but some of the code they use like getInt is not recognized. I'm stumped.
What you're bundling and passing to the What activity is not the counter but the string "Your score is 1". If you want to increment that number in the next activity then you should be sending just the integer value and constructing whatever string you need there instead.
I ve read a few tuts on passing an int vs a string..but some of the code they use like getInt is not recognized..anywho Im stumped..
I'm not too sure I know what you mean by getInt() is not recognized. In any case, make things easier for yourself when passing counter from one activity to another. If it is an int and you plan on manipulating like an int in the receiving activity then add it to the bundle as an int. For example:
Bundle keeper = new Bundle();
keeper.putInt("key", counter_score);
And retrieve it from the bundle with:
Bundle gotKeeper = getIntent().getExtras();
int score = gotKeeper.getInt("key");
What if you make a "global" class to be shared across the different activities, and use it to keep the variables used "in sync"?
For example - Globals.java:
public class Globals {
public int counter_score;
}
And then reference that variable using Globals.counter_score
You can of course also use that shared class for other variables and functions as well - for example common operations.
Update
As the commenters pointed out, this method isn't particularily good - I forgot that the code is simply referenced, and doesn't "live" on its own to keep information for the other activities (thanks for correcting me on that one, I'm still learning...)
Something that COULD work better, though, is to pass the current state of the counter_score variable in the intent when you launch your second activity - for example:
IntentToLaunchTheOtherActivity( counter_score );
And then maybe pass the variable back to the previous activity if it's changed afterwards...
I got it work. Essentially I needed to what what TJ Third suggested converting keeper.putString("key", counter_score); to keeper.putInt("key", counter_score);, I also needed to convert the bundle being received to an int within the "What" activity. Within "What" activity I renamed int counter_score; and int gotKeeper;(this was String gotKeeper) then instead of calling counter_score =0; now that the bundle passed is an int,I called counter_score = gotKeeper; under initialize(); so the counter score equals the result generated from the previous activity "Voice".
Now when the user answers correctly, counter++; adds one to the existing counter_score and bundles it and send it to the next activity, and rinse a repeat.
static final int check = 111;
int counter_score;
TextView txView;
MediaPlayer ourSong;
ImageView display;
int gotKeeper;
String classes[] = {"What", "Pagina", "What", "example3", "example4", "example5",
"example6"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.letter_b);
initialize();
Bundle gotKeeper = getIntent().getExtras();
gotKeeper = gotScore.getInt("key");
counter_score = gotKeeper;
Again thnx to everyone for your suggestions and insight.Huge help to a newbie.
I want to show the value inserted by user in first window to the next window.
I am accepting the User weight & height in first window and I want to show it on the second screen as Your weight & Height.
I search a lot and even tried a code but in emulator m getting forcefully closed error.
First Activity :
public class BMI_Main extends Activity
{
EditText BMI_weight;
public String weight;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.bmi_main);
Button submit =(Button)findViewById(R.id.BMI_submit);
BMI_weight = (EditText)findViewById(R.id.BMI_EdTx_kg);
submit.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
weight = BMI_weight.getText().toString();
// create a bundle
Bundle bundle = new Bundle();
// add data to bundle
bundle.putString("wt", weight);
// add bundle to the intent
Intent intent = new Intent(v.getContext(), BMI_Result.class);
intent.putExtras(bundle);
startActivityForResult(intent, 0);
}
}
);
Second Activity :
public class BMI_Result extends Activity
{
TextView Weight = (TextView)findViewById(R.id.BMI_TxtVw_wt);
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.bmi_result);
//get the bundle
Bundle bundle = getIntent().getExtras();
// extract the data
String weight = bundle.getString("wt");
Weight.setText(weight);
}
So please help me for it..
As far as I can see you have the following member definition in BMI_Result:
TextView Weight = (TextView)findViewById(R.id.BMI_TxtVw_wt);
But you can only call findViewById after the class was initialized, since it is a member function of the View class, so change this line to:
TextView Weight;
And add this line to the onCreate method right after setContentView(...):
Weight = (TextView)findViewById(R.id.BMI_TxtVw_wt);
Edit: It said "...right after super.onCreate(...)", now it's correct ;)
You should override onCreate()
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
And the token at the end of onCreate is wrong.
You should use the Context.startActivity(Intent intent) method in your first window/Activity.
Store your data which you want to pass to the second window/Activity in the Intent object, like:
Intent intent = new Intent();
intent.putExtra("weight", weight);
intent.putExtra("height", height);
this.startActivity(intent);
And retrieve them in the second screen/Activity in the onCreate method, like:
Intent intent = getIntent(); // This is the intent you previously created.
int weight = intent.getExtra("weight");
int height = intent.getExtra("height");