Here is the code
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(this.redirectUrl+"?username="+getValue(loginString)+"&password="+getValue(pwdString)));
startActivity(browserIntent);
I have this error :
10-17 15:30:35.288 5467-5467/com.example.android.navigationdrawerexample W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40cd7930)
10-17 15:30:35.298 5467-5467/com.example.android.navigationdrawerexample E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Fragment PlanetFragment{41b91f78} not attached to Activity
at this line :
startActivity(browserIntent);
This and this DOESN'T work for me.
What i can do ?
Why don't you just call getActivity() from Fragment and then call startActivity() like getActivity().startActivity(intent);
From the exception, it looks like you're calling this method on a Fragment that is not (yet?) attached to an Activity. From the source of the Fragment class:
public void startActivity(Intent intent, Bundle options) {
if (mActivity == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
...
To fix this, just change the place where this method is called, i.e. after onAttach() and before onDetach().
Related
In my project I have two activities: MainActivity.class and SecondActivity.class.
To switch from the MainActivity to the SecondActivity I use the following code:
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
MainActivity.this.startActivity(intent);
And it works.
I use the same code to switch from the SecondActivity to the MainActivity but the app crashes:
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
SecondActivity.this.startActivity(intent);
If I try to open the MainActivity from the MainActivity itself it crushes too, but this doesn't happen if I try to open the SecondActivity from the SecondActivity.
Any idea?
Here my stack trace:
2021-09-29 17:25:56.843 25827-25827/st.com.st25androiddemoapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: st.com.st25androiddemoapp, PID: 25827
java.lang.RuntimeException: Unable to resume activity {st.com.st25androiddemoapp/st.com.st25androiddemoapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4270)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4302)
at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2044)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at st.com.st25androiddemoapp.MainActivity.onResume(MainActivity.java:279)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1454)
at android.app.Activity.performResume(Activity.java:8050)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4260)
Thank You
If what you want is to return to MainActivity then in SecondActivity you should simply do:
finish()
This will destroy the activity and return to the previous one.
When you start MainActivity using startActivity(intent), Intent.getAction() method will return null. This method is called in MainActivity#onResume.
To prevent your app from crashing, you need to make sure that action is not null before calling any methods (equals() in your case.)
I found the source code. Just and action != null && here
if (action != null && (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED) ||
action.equals(NfcAdapter.ACTION_TECH_DISCOVERED) ||
action.equals(NfcAdapter.ACTION_TAG_DISCOVERED))) {
// If the resume was triggered by an NFC event, it will contain an EXTRA_TAG providing
// the handle of the NFC Tag
Tag androidTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (androidTag != null) {
// This action will be done in an Asynchronous task.
// onTagDiscoveryCompleted() of current activity will be called when the discovery is completed.
new TagDiscovery(this).execute(androidTag);
}
}
don't forget to add brackets ()
It will fix the NPE, but I'm not sure if this is the best solution. I don't know what you are trying to achieve.
upd
If you want to navigate back to main activity by closing Second activity, which was opened on top of MainActivity, then just use finish() method
have you tried replace getapplicationcontext() with this ?
Intent intent = new Intent(SecondActivity.this,MainActivity.class);
startActivity(intent);
I have Fragment A and Fragment B, on fragment A i have an input searchbox and when I open the fragment it shows the softkeyboard which is intended. When switching fragments sometimes a NullPointerException occurs. I cannot reproduce the error but the log file says that the error occurs on the onResume() function. Below is the code i used on my onResume(), what can be the reason i get java.lang.NullPointerException?
#Override
public void onResume() {
super.onResume();
getActivity().setTitle(R.string.app_name);
if (getActivity().getWindow().getCurrentFocus() == searchbox) {
searchbox.postDelayed(new Runnable() {
#Override
public void run() {
InputMethodManager imm = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(searchbox, InputMethodManager.SHOW_IMPLICIT);
}
}
}, 300);
}
}
Edit:
Here is logcat:
java.lang.NullPointerException:
at com.myapp.fragments.MyMain$7.run (MyMain.java:258)
at android.os.Handler.handleCallback (Handler.java:815)
at android.os.Handler.dispatchMessage (Handler.java:104)
at android.os.Looper.loop (Looper.java:207)
at android.app.ActivityThread.main (ActivityThread.java:5811)
at java.lang.reflect.Method.invoke (Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:907)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:768)
Inside the run method you have:
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
getActivity() may be null if the fragment is not attached to the Activity after 300 milliseconds.
Null pointer exception means you are trying to work with a variable that has not been initialized yet. So in your onResume method, check all the variables. Make sure they survive the activity distruction. Because many variables don't resume in the onResume.
You will need to figure out which variable is giving null pointer exception and then initialize that variable in the onResume method.
You can use try catch method on each code line in your onResume method to fugure out which of the codeline is giving error. in catch method you can print out the error to console as follows
try{
//1st code line
}catch{ System.out.println("1st line gives the error")
}
Yes I agreewith magnetar. That should solve your issue.
try{
//code line 1
}catch(Exception e){
Log.i(TAG, "method: "+e.getMessage());
}
try this on each line
Another way you can go about it is by debugging your project and adding breakpoints in onResume method. That could be more helpful.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
My problem is that one specific activity in my app can't be launched for some reason, and it throws:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
All other launching code that looks like this work fine, the problem is ONLY when I'm launching Player1. The class surely exists, and I can't understand what is the problem.
I'm launching an activity called Player1 from an activity called ChooseLevel. When some button is pressed, the call is:
Intent intent = new Intent(ChooseLevel.this, Player1.class);
Bundle b = new Bundle();
b.putInt("game_level", 1);
intent.putExtras(b);
startActivity(intent);
finish();
The logs show that the error is in: Player1.onCreate(Player1.java:50)
The code in line Player1:50 is:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player1);
changeIndex = 0;
cards = new ArrayList<Card>(8);
score = (TextView) findViewById(R.id.score_text);
message = (TextView) findViewById(R.id.msg_text);
timer = (TextView) findViewById(R.id.timer);
timer.setText(String.valueOf(definitions.TIMER_START)); # LINE 50
Bundle b = getIntent().getExtras();
...
}
When this launching code runs, I get this in my logs:
33:04.338 18302-18302/com... D/AndroidRuntime: Shutting down VM
01-18 10:33:04.338 18302-18302/com... E/AndroidRuntime: FATAL EXCEPTION: main
Process: com..., PID: 18302
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.../com....Player1}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at com....Player1.onCreate(Player1.java:50)
EDIT:
I found my answer, it had to do with some object that I had in my Player1.onCreate() method. In a wierd way, android-studio raised the exception regarding getClass(). If someone knows why this happend, please share :)
use context,getApplicationContext()orgetActivity()`
Intent intent = new Intent(context, Player1.class);
Bundle b = new Bundle();
b.putInt("game_level", 1);
intent.putExtras(b);
startActivity(intent);
finish();
I'm performing file viewing operation as follows:
private void openFile(File file, String format) {
try {
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
String mimeType = "*/*";
if (format.length() > 0) {
mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(format);
if (mimeType == null)
mimeType = "*/*";
} else
mimeType = "*/*";
intent.setDataAndType(path, mimeType);
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(LoginSuccessActivity.this,
constants.Error_NoCompatibleApp, Toast.LENGTH_SHORT)
.show();
e.printStackTrace();
}
} else {
Toast.makeText(LoginSuccessActivity.this,
constants.Error_DocNotFound, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
This is working fine, as I get app chooser pop-up for the filetypes which has multiple apps related to it(for eg. kingsoft office and polaris office for word file) OR directly file is opened for the filetypes which has only one app related to it(HTMLViewer for html file).
What I don't understand is my main activity is getting destroyed in few moments after calling file viewer activity. I've checked this by placing logs in onPause(), onStop() and onDestroy(). So, after file viewing is done, when I press back key, instead of taking back to app, it navigated to main menu.
I tried with startActivityForResult(intent, 1); instead of startActivity(intent); hoping that it'll preserve my main activity as it'll be waiting for result, but to no avail.
Please note that I've added android:configChanges="orientation|screenSize" in manifest file and
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
in java file.
Am I doing anything wrong?
Any help appreciated.
Sometimes, mind you, "Sometimes", I get follwing messages on log:
file:// Uri exposed through Intent.getData()
java.lang.Throwable: file:// Uri exposed through Intent.getData()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1597)
at android.net.Uri.checkFileUriExposed(Uri.java:2338)
at android.content.Intent.prepareToLeaveProcess(Intent.java:7194)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1418)
at android.app.Activity.startActivityForResult(Activity.java:3423)
at android.app.Activity.startActivityForResult(Activity.java:3384)
at android.app.Activity.startActivity(Activity.java:3626)
at android.app.Activity.startActivity(Activity.java:3594)
at com.android.internal.app.ResolverActivity.onIntentSelected(ResolverActivity.java:407)
at com.android.internal.app.ResolverActivity.startSelected(ResolverActivity.java:299)
at com.android.internal.app.ResolverActivity.onButtonClick(ResolverActivity.java:289)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3809)
at android.view.View.performClick(View.java:4424)
at android.view.View$PerformClick.run(View.java:18383)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4998)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
at dalvik.system.NativeStart.main(Native Method)
Add these lines to your Intent and try to Start Activity,
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setType(Your_MimeType);
I m using this code in my App
String MimeType = URLConnection.guessContentTypeFromName(myFile.getAbsolutePath());
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setType(MimeType);
Uri uri_path = Uri.fromFile(myFile);
intent.setDataAndType(uri_path, MimeType);
try
{
_context.startActivity(intent);
}
catch(ActivityNotFoundException e)
{
Toast.makeText(_context,"Activity Not Found..", Toast.LENGTH_SHORT).show();
}
Refer this link also for better understanding
Hope it will help you.
Activity can get destroyed any time. If someone has some data to retain one can do as follows:
class MyActivity {
private String mMyString;
public void onSaveInstanceState(Bundle b) {
b.putString("MYDATA", mMyString);
super.onSaveInstanceState(b);
}
public void onCreate(Bundle savedState) {
super.onCreate(savedState)
if(savedState != null) {
mMyString = savedState.getString("MYDATA");
}
}
You can this way create your own subclass private static class State implements Serializable and save it in onSaveInstanceState()
i have Target.java(it is the main activity) and Layout.java.
When user clicks a button a url opens.
The button click is handled in Layout.java.
deleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DebugLog.LOGD("Within onClick event of 'GO' button ");
Target.openURL();
}
});
Target.java has a static function openURL
public static void openURL() {
Uri uri = Uri.parse("http://www.thecinema.in");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
I'd like to know how i can make this code work, since the error im getting now is "Cannot make a static reference to the non-static method startActivity(Intent) from the type Activity" . I can understand startActivity will not work within a static function, but please suggest me how i could acheive the objective ..Im a newbie to android.FYI ..Thanks guys
-Updated code :
Layout.java
deleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DebugLog.LOGD("Within onClick event of 'GO' button ");
Target iA = new Target();
iA.openURL();
}
});
Target.java
public void openURL() { //removed static keyword
DebugLog.LOGD("Within nDelete event of GO button ");
Uri uri = Uri.parse("http://www.thecinema.in");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
Exception thrown:
03-02 10:10:28.351: D/QCAR(6820): Within onClick event of 'GO' button
03-02 10:10:28.351: W/dalvikvm(6820): threadid=1: thread exiting with uncaught exception (group=0x400207d8)
03-02 10:10:28.361: E/AndroidRuntime(6820): FATAL EXCEPTION: main
03-02 10:10:28.361: E/AndroidRuntime(6820): java.lang.NullPointerException
03-02 10:10:28.361: E/AndroidRuntime(6820): at android.app.Activity.startActivityForResult(Activity.java:2817)
03-02 10:10:28.361: E/AndroidRuntime(6820): at android.app.Activity.startActivity(Activity.java:2923)
03-02 10:10:28.361: E/AndroidRuntime(6820): at com.ingage.pocs.phonegap.Layout$4.onClick(Layout.java:124)
03-02 10:10:28.361: E/AndroidRuntime(6820): at android.view.View.performClick(View.java:2408)
03-02 10:10:28.361: E/AndroidRuntime(6820): at android.view.View$PerformClick.run(View.java:8816)
03-02 10:10:28.361: E/AndroidRuntime(6820): at android.os.Handler.handleCallback(Handler.java:587)
03-02 10:10:28.361: E/AndroidRuntime(6820): at android.os.Handler.dispatchMessage(Handler.java:92)
03-02 10:10:28.361: E/AndroidRuntime(6820): at android.os.Looper.loop(Looper.java:123)
03-02 10:10:28.361: E/AndroidRuntime(6820): at android.app.ActivityThread.main(ActivityThread.java:4633)
Guys what went wrong in here..
i was able to come up with a solution for this question.
Under Target.java i created openURL() as:
public void openURL(Context context)
{
Intent intent = new Intent("com.ingage.pocs.phonegap.URL");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
I created a new Activity OpenURL.java and associated the intent "com.ingage.pocs.phonegap.URL" with it:
package com.ingage.pocs.phonegap;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
public class OpenURL extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
DebugLog.LOGD("Within BookTicketsActivity Activity GO button ");
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.thecinema.in"));
startActivity(browserIntent);
}
}
Layout.java:
private Context applicationContext;
deleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DebugLog.LOGD("Within onClick event of 'GO' button ");
ImageTargets ia =new ImageTargets();
ia.openURL(applicationContext);
iA.openURL();
}
});
The best thing is, it worked :) If you guys come up with a better or more sensible solution , pls do post here.thank you
startActivity is not static and since you call it from Target not Layout it cannot resolve call context.
You'll need to call startActivity from Layout.java or pass reference or Target to Layout class
do it like this
Layout.java:
deleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DebugLog.LOGD("Within onClick event of 'GO' button ");
Target.openURL(Layout.this);
}
});
Target.java:
public static void openURL(Context context) {
Uri uri = Uri.parse("http://www.thecinema.in");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
context.startActivity(intent);
}
You have
Targets iA = new Targets();
Did you, perhaps, mean to write
Target iA = new Target();
That would throw a NullPointerException because you're asking Java to find a class named Targets when none exists.