How do I initialise a variable in this case? - java

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;

Related

Why does getAppWidgetInfo return null sometimes? How to avoid this?

I have 2 types of the widgets in the app and single ConfigActivity for setting both of the widgets. To update widgets for the first time after configuration and for the reconfigurations later I have to press START button in the fragment of ConfigActivity. Before sending intent to update widget I define the type of the widget, using getAppWidgetInfo (code is below).
Sometimes getAppWidgetInfo.provider returns null.
// Button Start (Start Widget)
buttonStart.setOnClickListener {
val appWidgetManager = AppWidgetManager.getInstance(context)
// We have a single ConfigActivity for all the types of the widgets,
// thus we have to differ widget types.
// Get string with short name of widget provider (looks like ".WidgetTodayProvider"),
// using getAppWidgetInfo.provider.shortClassName.
// Delete dot from the string, using substring(1).
val widgetProviderShortName =
appWidgetManager.getAppWidgetInfo((activity as ConfigActivity).appWidgetId)
.provider.shortClassName
.substring(1)
// Update appwidget from ConfigActivity
when (widgetProviderShortName) {
"WidgetTodayProvider" ->
intent = Intent(
ACTION_UPDATE_AFTER_SETTING_TODAY, null, context,
WidgetTodayProvider::class.java
)
"WidgetPeriodProvider" ->
intent = Intent(
ACTION_UPDATE_AFTER_SETTING_PERIOD, null, context,
WidgetPeriodProvider::class.java
)
}
intent.putExtra(
AppWidgetManager.EXTRA_APPWIDGET_ID,
(activity as ConfigActivity).appWidgetId
)
activity?.sendBroadcast(intent)
activity?.setResult(RESULT_OK, (activity as ConfigActivity).resultValue)
activity?.finish()
}
Description of the error: Attempt to read from field 'android.content.ComponentName android.appwidget.AppWidgetProviderInfo.provider' on a null object reference
The documentation of getAppWidgetInfo says:
If the appWidgetId has not been bound to a provider yet, or you don't have access to that appWidgetId, null is returned.
But this doesn't explain how, why and under what conditions it's possible, when appWidgetId is not bound to provider.
Why in the most cases everything is ok, but only sometimes getAppWidgetInfo returns null? How to control this and avoid this problem?
Could somebody explain me, please?

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

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);
}

Why to check all conditions before proceeding?

Hi I am a beginner to programming. I am trying to learn Android development from udacity.
Cursor cur = someFunction();
if(cur != null){
Intent intent = new Intent(getActivity(), two.class);
intent.setData(cur.getLong(2));
startActivity(intent)
}
Now in two class.
Intent intent = getActivity.getIntent();
if(intent != null){
mString = intent.getDataString();
}
if(null != mString){
mTextView.setText(mString);
}
I was just wondering why do we require so many ifs in this code. The if in first piece of code is fine.
When the second activity was called from first activity. Why do we need to check if the intent is null? Since it is the only entry point to the second activity.
And why do we again need to check if the string is null before assigning it to Text View?
Just because you see it in some code, that doesn't mean it's required.
The check for null on the first condition isn't necessary. The code here looks like it's being very paranoid that getIntent() might return null.
In the second condition, there is nothing that's telling the compiler that there is a guarantee that the return string will definitely not be null. In fact, the documentation states that it may return null, so it's safe to always check. You can put a null string into a TextView, but that isn't necessarily what's desired. It's hard to tell without context.
Because if you don't check if something is null and try to invoke a method on it, it will cause a NullPointerException. That's why only after you've confirmed that the Intent is not null, you can call the method
intent.getDataString();

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.
}

Categories

Resources