Two exact same startactivity() in a switch, only one works - java

I'm new at coding.
So I have a switch where the app can choose the next actvity using the string nextActivityExtra. The intent.putExtra are necessary for the other activities and no activity have problem recieving them. So basically the code works, but only on the first case. When the app comes back at this "switch activity", it should get to the second case, and here it cannot load MainActivity (it loads a black screen and suddenly goes back to the "switch activity").
If I switch ExplicaioActivity for MainActivity or for any other activty it will work fine unless it's in the second case. I really cannot grasp what's happening here, I also tried the same code with If's with similar results.
public class EntreActivities extends AppCompatActivity {
ImageView iconView;
int count;
String levelExtra;
Intent intent;
String nextActivityExtra;
String rutaLevelNumber;
boolean isTaskCompleted;
Class myClass;
public void Rotate(View view) {
RotateAnimation rotateAnimation = new RotateAnimation(0, 30,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 1f);
rotateAnimation.setDuration(3000);
rotateAnimation.setRepeatMode(Animation.REVERSE);
rotateAnimation.setRepeatCount(Animation.INFINITE);
rotateAnimation.setFillAfter(true);
rotateAnimation.setStartOffset(1000);
iconView.setAnimation(rotateAnimation);
}
public void startAct() {
if (getIntent().getBooleanExtra("inTraining", false)) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
Toast.makeText(this, "TTTTtrain", Toast.LENGTH_SHORT).show();
} else {
switch (nextActivityExtra) {
case "ExplicaioActivity":
myClass = ExplicaioActivity.class;
Toast.makeText(EntreActivities.this, "here", Toast.LENGTH_SHORT).show();
intent = new Intent(getApplicationContext(), ExplicaioActivity.class);
intent.putExtra("Level", rutaLevelNumber);
intent.putExtra("inTraining", false);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
break;
case "MainActivity":
myClass = MainActivity.class;
Toast.makeText(EntreActivities.this, "here", Toast.LENGTH_SHORT).show();
intent.putExtra("Level", rutaLevelNumber);
intent.putExtra("inTraining", false);
intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
break;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entre_activities);
iconView = findViewById(R.id.iconView);
iconView.setRotation(-15);
Intent intent = getIntent();
levelExtra = intent.getStringExtra("Level");
nextActivityExtra = intent.getStringExtra("NextActivity");
rutaLevelNumber = intent.getStringExtra("Level");
Rotate(iconView);
startAct();
}
}
This is the error log that I could take from AS:
2019-01-12 01:08:12.383 4282-4282/com.example.root.exercicis E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.root.exercicis, PID: 4282
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.root.exercicis/com.example.root.exercicis.EntreActivities}: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
at com.example.root.exercicis.EntreActivities.startAct(EntreActivities.java:53)
at com.example.root.exercicis.EntreActivities.onCreate(EntreActivities.java:100)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 

you are trying to put extra before initialising the Intent inside MainActivity case.
Initialize Intent before putting extra like following
intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("Level", rutaLevelNumber);
intent.putExtra("inTraining", false);

The reason for this is because you're creating a new Intent that doesn't have the String extra "NextActivity".
Let me walk you through what's happening:
Activity is started and onCreate() is run.
Intent intent = getIntent() is run and intent now contains all data from the Intent that was sent to this Activity.
nextActivityExtra = intent.getStringExtra("NextActivity") is run and now, nextActivityExtra is now stored with either "ExplicaioActivity" or "MainActivity".
startAct() is run.
Switch statement is run properly because nextActivityExtra has the proper value. Let's pretend it's ExplicaioActivity.
intent = new Intent(getApplicationContext(), ExplicaioActivity.class);is run, and it creates a NEW intent.
You use intent.putExtra("Level") and intent.putExtra("inTraining"), but forget to put `intent.putExtra("NextActivity");
New Activity is started and onCreate() is run.
Intent intent = getIntent() is run and intent now contains all data from the Intent that was sent to this Activity. But keep in mind that this Intent from the previous Activity is missing the Extra "NextActivity"
nextActivityExtra = intent.getStringExtra("NextActivity") is run, but since there's no extra for this, so null is stored in this variable instead.
Switch case happens, but Switch does not support null so the black screen is actually a crash for the Activity.
So to fix this, you simply have to add intent.putExtra("NextActivity", NEW_VALUE); inside case "ExplicaioActivity" with NEW_VALUE being the new value you want to add as the extra value. `
However, for case "MainActivity", besides doing what I said before, you also need to rearrange a line of code.
Switch this:
intent.putExtra("Level", rutaLevelNumber);
intent.putExtra("inTraining", false);
intent = new Intent(getApplicationContext(), MainActivity.class);
to this:
intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("Level", rutaLevelNumber);
intent.putExtra("inTraining", false);

Related

how to open fragment from another activity android

i am trying to use startactivityfromfragment()
i didnt find sumthing usefull for me to be a good example
until now i was able to move data(string of web url) from fragment to fragment
now its a diffrent story.. i think i need to use startactivityfromfragment()..
but dont know how
Bundle bundle = new Bundle();
bundle.putString("WEB","someweb.com");
MultiFragment multiFragment = new MultiFragment();
multiFragment.setArguments(bundle);
Intent intent1 = new Intent(getBaseContext(), MultiFragment.class);
startActivityFromFragment(MainActivity.class,intent1,"WEB");
Try this:
Put this code in current fragment, from where you want to open an activity.
Intent i=new Intent(getActivity(),Multifragment.class);
i.putExtra("key","value");
getActivity().startActivity(i);
In the next activity which contains fragment, put these:
String value=getIntent().getStringExtra("key");
Bundle bundle=new Bundle();
bundle.putString("key",value);
YourFragmentClass ob=new YourFragmentClass();
ob.setArguments(bundle);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.your_container_layout,ob).addToBackStack(null).commit();
Then, In YouFragmentClass:
Bundle=getArguments();
if(bundle!=null}
String value=bundle.getString("key");
Use your Activity name as second parameter in which the your MultiFragment exist
Intent i = new Intent(MainActivity.this, ActivityName.class);
putExtras(bundle);
startActivity(i);
finish();
Method 1
For sending data from activity to another activity's fragment call a normal intent with bundle value, In another activity check on getIntent() and call a method from that fragment
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("web_url", "url");
startActivity(intent);
and call from another activity
String webUrl = getIntent().getStringExtra("web_url");
Fragment newFragment = getSupportFragmentManager().findFragmentById(R.id.frame_tab);
newFragment.openWeb(webUrl);
Method 2
In second activity make a static variable and save the data from getIntent() and in fragment use that variable.
Mehtod 3
interface FragmentListner{
void openFragment(String url);
}
Activity A :
FragmentListner frag = new FragmentListner();
frag.openFragment("Url");
Activity B:
class B implements FragmentListner{
void openFragment(String url){
//Open Fragment here
}
I think:
In an activity that doesn't contain fragment:
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("something", "yep");
startActivity(intent);
And, in the next activity which contains fragment:
Intent intent = getIntent();
String op = intent.getStringExtra("something");
if (op != null){
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment,
new YourFragment()).addToBackStack(null).commit();
}

NullPointerException while dealing with creating an intent in MainActivity [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I've been looking into this for a few days and can't seem to find a thread specific to my problem. My app crashes every time I try to add a string to my bundle.
I'm getting the error at extras.putString(EXTRA_MESSAGE, message);
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ArrayList<String> priceGroupSpinnerItems;
public static final String EXTRA_MESSAGE = "lss.mywebsiteoffline.MESSAGE";
public String message = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spnPriceGroup = (Spinner) findViewById(R.id.price_group_spinner);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.list_price_group, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnPriceGroup.setAdapter(adapter);
message = spnPriceGroup.getSelectedItem().toString();
}
/** Called when the user taps the Go button */
public void sendMessage(View view) {
Intent mIntent;
mIntent = new Intent(this, nextActivity.class);
Bundle extras = mIntent.getExtras();
extras.putString(EXTRA_MESSAGE, message);
mIntent.putExtras(extras);
startActivity(mIntent);
}
}
Logcat
E/AndroidRuntime: FATAL EXCEPTION: main
Process: lss.mybbofflinever3, PID: 8181
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5702)
at android.widget.TextView.performClick(TextView.java:10896)
at android.view.View$PerformClick.run(View.java:22546)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5702) 
at android.widget.TextView.performClick(TextView.java:10896) 
at android.view.View$PerformClick.run(View.java:22546) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7224) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Bundle.putString(java.lang.String, java.lang.String)' on a null object reference
at lss.mywebsiteoffline.MainActivity.sendMessage(MainActivity.java:59)
I have tried examples to use just intent, or bundle, and adding strings directly to putString. I might be missing something blatantly obvious. Not sure what I might be looking for after adding strings directly to the putString method and getting the same error.
By default an Intent does not have extras and getExtras() returns null. If you want to set extras, you need to create the extras bundle yourself. Replace
Bundle extras = mIntent.getExtras();
with
Bundle extras = new Bundle();
Or just call one of the putExtra() overloads on the Intent - it will also init the extras bundle in case it's not there already.
Try this:
Intent mIntent = new Intent(this, nextActivity.class);
mIntent.putExtra(EXTRA_MESSAGE, message);
startActivity(mIntent);

app crash with android.content.Context.getPackageName()' on a null object reference

i need help.
I'm in the finish phase of development of my android application and now after a few month of develop the app magically crash with this error :
java.lang.String android.content.Context.getPackageName()' on a null object reference
I don't know what is the problem but i will post the code that cause the crash :
public static void start(Context context) {
context.startActivity(new Intent(context, ConversationsActivity.class));
}
called with this piece of code (inside a fragment):
ConversationsActivity.start(getActivity());
The last change that i've make was to add Fabric.io ( in particular Branch ) and from the history in the last commit on git i don't show nothing that can produce this error
EDIT :
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4900)
at com.exampleapp.views.messages.ConversationsActivity.start(ConversationsActivity.java:31)
at com.exampleapp.views.menu.MenuFragment.onMenuMessagesClicked(MenuFragment.java:116)
at com.exampleapp.views.menu.MenuFragment_ViewBinding$5.doClick(MenuFragment_ViewBinding.java:82)
at butterknife.internal.DebouncingOnClickListener.onClick(DebouncingOnClickListener.java:22)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Or you could do this:
public static void start(Activity activity) {
activity.startActivity(new Intent(activity, ConversationsActivity.class));
}
You should use getActivity() to launch an Activity from Fragment.
From a Fragment: Context is parent activity (getActivity()).
Intent intent = new Intent(getActivity(), ConversationsActivity.class);
startActivity(intent);
From an Activity: Context is current activity (this).
Intent intent = new Intent(this, ConversationsActivity.class);
startActivity(intent);
Your problem is that you are using the intent wrong. Replace your start() code with this:
public static void start() {
Intent i = new Intent(getApplicationContext(), ConversationsActivity.class);
startActivity(i);
}
Then instead of using ConversationsActivity.start(getActivity()); to call it, just use start(); when you want to call the method.
Hope this helps!

What is the difference between getIntent() and new Intent() in Android?

I do like this
first way
Intent intent = new Intent();
intent.putExtra("isLoggedIn",true);
setResult(RESULT_OK,intent);
second way
Intent intent = getIntent();
intent.putExtra("isLoggedIn",true);
setResult(RESULT_OK,intent);
Both can give the same result.I want to know the actual difference between this two
In the context of an Activity, getIntent() will return the Intent that was originally sent to the Activity. The example you gave may work the same, but you should really avoid using getIntent() if you are passing the Intent to another Activity or sending it back as a result.
For example:
If I start an activity with:
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("key", "test");
startActivity(intent);
Then in my MainActivity class:
Intent intent = getIntent();
String value = intent.getString("key"); // value will = "test".
So now consider if you have SecondActivity and I am starting it from MainActivity using getInent();
Intent intent = getIntent();
intent.setClassName("com.example.pkg", "com.example.pkg.SecondActivity"");
intent.setComponent(new ComponentName("com.example.pkg", "com.example.pkg.SecondActivity"));
intent.putExtra("isLoggedIn",true);
startActivity(intent);
Then in my SecondActivity I can access key and isLoggedIn both.
Intent intent = getIntent();
String value = intent.getString("key"); // value will = "test".
boolean testIsLoggedIn = intent.getBooleanExtra("isLoggedIn",true);
So, generally it is not good practice to use the getIntent to start further activities.

pass Intent to function throws NullPointerException

In an Android I would like to pass an Intent Object to a function, but consistently get a NullPointerException.
I could not find any source citing that this is not possible.
basically I have this:
public Intent intent;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intent = getIntent();
int check = elsewhere.chk_intent(intent); //<=THROWS ERROR
}
chk_intent() performs some functions on data transmitted with the intent, especieally if some extra fields are present.
I tried to move getIntent() into this function, but this is not allowed.
Any help would be much appreciated
Is this activity called by another activity? The intent will not be null only if previous activity supplies an intent to the current activity:
// previous activity
Intent intent = new Intent(FirstActivity.class, SecondActivity.class);
int value = 10;
intent.putIntExtra("key", value);
startActivity(intent);
// use this if want to return data
//startActivityForResult(intent);
If this activity is the starting (main) activity or it is not called by any previous activity, then getIntent() is null, you need to initialize your own new Intent object.
// current activity in onCreate() method
if(getIntent() == null) {
Intent intent = new Intent();
int check = elsewhere.chk_intent(intent);
}

Categories