getIntent().getStringExtra("name") returns null - java

I'm currently making a "Battleships" game for my school project.
first off, i put Strings named "hostState" and "key" in the intent extra and start the activity:
public void startGame(String key){
i = new Intent(OnlineGame.this, Start.class);
i.putExtra("key", key);
i.putExtra("hostState", hostState);
startActivity(i);
}
when i try to retrieve the string, it returns null. this is how I attempted to retrieve the strings:
key = getIntent().getStringExtra("key");
isHost = getIntent().getStringExtra("hostState");
when I ran the code in debug mode, it showed me that the intent (i) did in fact contain the extras that i put in it, but for some reason it doesn't remember those when I attempt to get them through getIntent().getStringExtra();
i have checked that all of the names aligned, capital letters, etc. and that I was using the right format for sending and receiving the extra (I made a demo app to test the result and it came out perfectly as expected).

Try this,
key = getIntent().getExtras().getString("key");
isHost = getIntent().getExtras().getString("hostState");
or if its not working update putextra (Manual Typecast)
public void startGame(String key){
i = new Intent(OnlineGame.this, Start.class);
i.putExtra("key", ""+key);
i.putExtra("hostState", ""+hostState);
startActivity(i);
}

call method like this startGame("ABC", "XYZ");
public void startGame(String key,String hostState){
i = new Intent(OnlineGame.this, Start.class);
i.putExtra("key", key);
i.putExtra("hostState", hostState);
startActivity(i);
}

Related

Sending a MultiMap type datastructure through an intent in android studio

I had to create a "multimap" type data structure for my android app that looks like this
HashMap<Integer, String []> sampleStorage = new HashMap<Integer, String []>
I am trying to pass it through several activities but it fails to pass to the first activity. I know this because the data is available in the activity that it is created but not available in the activity I pass the intent to.
I am using this code to add it to the intent and send it
Intent intent = new Intent(this, MyActivity.class);
Bundle args = new Bundle();
args.putSerializable("sampleStorage", (Serializable)sampleStorage);
intent.putExtra("BUNDLE", args);
And this is the code I am using to retrieve it
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
sampleStorage = (HashMap<Integer, String []>) args.getSerializable("sampleStorage");
The error that gets thrown when I try to access it in the second activity is a NullPointerError so it seems like it doesn't even make it to the second activity. Any help will be greatly appreciated, thank you in advance.
So after a few days of scouring my code I found out that there was a secondary declaration of sampleStorage that was overwriting my initial hash map. Sorry that I originally didn't provide enough of my code for someone to properly answer the question in the first place.

nullpointerexception when use getIntent().getExtras().getString

I want to pass a value in a activity to another activity and use this code
Intent i = new Intent(MainActivity.this,ListActivity.class);
i.putExtra("position","ایران");
startActivity(i);
and in other activity for return variable use this code
value = getIntent().getExtras().getString("position");
Now when I run the program it gives this error:
java.lang.nullpointerexception
Please help me.
This is the right way to retrieve string extra:
value = getIntent().getStringExtra("position");
Explanation
Why getExtras() does not work:
getExtras() returns a bundle which was previously put inside intent using putExtras(bundle).
so, the code would look like:
// Put position inside intent using extras:
Intent intent = new Intent();
Bundle extras = new Bundle();
extras.putString("position",position);
intent.putExtras(extras);
// Retrieve position:
getIntent().getExtras().getString("position");
But that's a lot more code, storing extra inside the intent directly is much more cleaner way

putExtra when sending variables across activities in Android allows the variable to be set to null

To send a variable from a Fragment to an Activity, I have used putExtra and extras.getString. However, I discovered I am getting a NullPointerException when using Log.e to check the value due to variable in which I am passing becoming =null. This happens after I have started the activity.
So how do i prevent this from occurring. Thus keeping the value of the variable.
Code for Fragment:
Integer IDPasser;
Intent intent = new Intent(getActivity(), ArticleViewer.class);
IDPasser = (Integer) data.ArticleID.toArray()[position];
intent.putExtra("ArticleID",IDPasser);
Log.e("Passer", IDPasser.toString()); //Shows that value is not = null.
startActivity(intent);
Code for Activity:
Bundle extras = getIntent().getExtras();
if (extras != null) {
Integer IDPasser = extras.getInt("ArticleID");
Log.e("TESTER", IDPasser.toString()); //NullPointerException due to IDPasser becoming = null.
}
The Fragment code is fine. In the Activity:
int idPasser = getIntent().getIntExtra("ArticleID", 0);
The second parameter in getIntExtra() is the default value to return if an int extra that corresponds to the key "ArticleID" is not found.
I would recommend making IDPasser an int not an Integer to avoid any confusion about whether the extra data is being passed as on Object or an int. I think you might be having a problem where you are inserting the value technically as putExtra(... Serializable) and expecting to get it out with extras.getInt(...)
int IDPasser;
Intent intent = new Intent(getActivity(), ArticleViewer.class);
IDPasser = data.ArticleID.toArray()[position];
intent.putExtra("ArticleID", IDPasser);
Log.e("Passer", String.valueOf(IDPasser)); //Shows that value is not = null.
startActivity(intent);
Then:
Bundle extras = getIntent().getExtras();
if (extras != null) {
int IDPasser = extras.getInt("ArticleID");
Log.e("TESTER", String.valueOf(IDPasser)); //NullPointerException due to IDPasser becoming = null.
}

Getting a value from a class extending activity in a plugin

When jumping from Activity to activity via Cordova, plugin, i want to be able to put additional information into a bundle and pass it along with the intent. I seem to have issues getting the current activity and then getting a value via
public int getCounter(){return counter;}
I have a Activity Definition which, onCreate will set counter to a value from the passed in bundle.
I have a Cordova plugin then which i am working with, which will carry out the intent to next activity.
Echo Class is a mediary which will jump between acticities based on html clicks.
//In the Class: public class Echo extends CordovaPlugin
private void launchSecondActivity(String data, CallbackContext cc){
Bundle b = new Bundle();
int tmp = ((SecondaryActivity)cordova.getActivity()).getCounter();
tmp++;
b.putInt("id", tmp);
Intent i = new Intent(cordova.getActivity().getApplicationContext(), SecondaryActivity.class);
i.putExtras(b);
cordova.getActivity().startActivity(i);
cc.success();
}
It seems that it causes a seg fault of sorts, when i am trying to assign counter to tmp, in the line:
int tmp = ((SecondaryActivity)cordova.getActivity()).getCounter();
Is there something i am doing wrong? I am trying to get the currently active activity, and then call a public function in that activity.
End Goal: I am trying to take an int, and keep passing it into intents, incremented. So that way, it will know how deep into the activity chain it is. I am working on nested state saving and curious as to the depth i am at, at any given time. The tmp being passed into the activity will be incremented each time, so it will maintain a depth.
Instead of creating a class with get counter, storing the int in the Bundle and passing it to the next activity would be far easier.
Example:
//send item to plugin.
int item = 0; // or whatever it is
Bundle b = new Bundle();
b.put("ident", item);
Intent i = new Intent();
i.putExtras();
//...
And then on the next activity.
public void onCreate(Bundle savedInstanceState)
{
int item = getIntent().getExtras().getInt("ident");
}
Then you can do with it what you will. The answer overall while the previous activity as the old number. What does that mean? It means that you can increment and do whatever you want with it when passing it to the next activity. It is copied, so you can incrememnet and store it recursively. Allowing you to even say something like:
if (item ==0){/*set new source for Activity*/}
else if(item == 1){/*set source 2*/}
//etc.

How do I initialise a variable in this case?

I'm starting an intent where the activity started depends on whether a device is a group owner or just a joined peer. At the moment, instructIntent is not initialised. Am I supposed to make it null as Eclipse suggests? Or is there some more professional, Java code style way of handling this?
Intent instructIntent;
if (info.groupFormed && info.isGroupOwner) {
Log.d(WiFiDirectActivity.TAG, "DeviceDetailFragment_onCreateView: btn_ready pressed on host");
instructIntent = new Intent(getActivity(), LeaderActivity.class);
} else if (info.groupFormed) {
Log.d(WiFiDirectActivity.TAG, "DeviceDetailFragment_onCreateView: btn_ready pressed on client");
instructIntent = new Intent(getActivity(), MusicianActivity.class);
}
instructIntent.putExtra(Intent.EXTRA_TEXT, "Play");
instructIntent.putExtra(MusicService.EXTRAS_GROUP_OWNER_ADDRESS, info.groupOwnerAddress.getHostAddress());
instructIntent.putExtra(MusicService.EXTRAS_GROUP_OWNER_PORT, 8080);
startActivity(instructIntent);
Making it null won't help. The real problem is if info.groupFormed is false, you won't have a valid value in instructIntent. But even if you initialize it to null, it still won't be valid. That means it will throw an exception when you call putExtra in it. A better way is to do:
if(info.groupFormed){
if(info.isGroupOwner){
instructIntent = new Intent(getActivity(), LeaderActivity.class);
}
else{
instructIntent = new Intent(getActivity(), MusicianActivity.class);
}
//all of your putExtra and startIntent calls here
}
Notice that all branches that go to the put and start calls on the intent will create a new intent. This way you won't have a null or unitnitialized variable trying to call a member function.
Any variable declared in java should be given value before using it. In the code given above there is possibility that we will not assign any value to the instructIntent variable if both both if and else if condition is not satisfied.
So you have to initialize instructIntent to null as follows.
Intent instructIntent = null;

Categories

Resources