Hi I'm a complete beginner at Android development so I don't really know too much of what I'm doing. I keep getting nullpointerexecption and my program crashes whenever getActivity() is called. This includes in toast messages as well as when I try to start another activity with an intent. I'm not entirely sure how to use intents either so if that could be explained that would be great.
Here is the class that has the getActivity() calls as well as intent:
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;
public class loginDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.loginw)
.setItems(R.array.account_types, new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which){
if(which==0){
Toast.makeText(getActivity(),"todo",Toast.LENGTH_SHORT).show();
}else if(which==1){
Toast.makeText(getActivity(),"todo",Toast.LENGTH_SHORT).show();
}else if(which==2){
AlertDialog.Builder builder1=new AlertDialog.Builder(getActivity());
LayoutInflater inflater=getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.login_dialog,null);
builder1.setView(view);
builder1.setTitle("Login with Email Address");
builder1.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog1, int which) {
//Toast.makeText(getActivity(), "Cancel", Toast.LENGTH_SHORT).show(); //Force Closes. Nullpointer Exception? Probably because of getActivity()
//dialog1.dismiss();
}
});
builder1.setNeutralButton("Forgot Password",new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog1, int which){
dialog1.dismiss();
AlertDialog.Builder builder2=new AlertDialog.Builder(getActivity());
builder2.setTitle("Forgot Password");
builder2.setMessage("Enter your Email Address");
builder2.setPositiveButton("OK",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//TODO
}
});
builder2.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//TODO
}
});
builder2.show();
}
});
builder1.setPositiveButton(R.string.login, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog1, int which) {
//Toast.makeText(getActivity(),"Login complete",Toast.LENGTH_SHORT).show(); //Force Closes. Nullpointer Exception? Probably because of getActivity()
dialog1.dismiss();
Intent intent = new Intent(getActivity(),Groups.class);
startActivity(intent);
}
});
Dialog dialog1 = builder1.create();
dialog1.show();
}
}
});
Dialog dialog=builder.create();
return dialog;
}
}
Here is the logcat (note this is only for the intent call because the other getActivity()s are commented out):
java.lang.NullPointerException
at android.content.ComponentName.<init>(ComponentName.java:77)
at android.content.Intent.<init>(Intent.java:3813)
at com.app.u.loginDialog$1$3.onClick(loginDialog.java:67)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
You should call getActivity after the onActivityCreated method has returned in the Overriden dialogfragment class. in ur case loginDialog class. that is the safe place to call getActivity
public class LoginDialog extends DialogFragment {
Activity mAct;
#Override
public void onAttach(Activity act) {
super.onAttach(act);
mAct = act; // use this mAct instead of getActivity() function
}
You cannot create the Intent inside the dialogue popup message So you should use like this Or declare inside your dialogue Like this it will help you Definitely...All the best
Context context = activity.getApplicationContext();
Intent intent = new Intent(context, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
Try using getApplicationContext() instead
Intent intent = new Intent(getApplicationContext(), Groups.class);
startActivity(intent);
And remember to declare your new activity in your AndroidManifest file!
<activity android:name=".Groups"/>
Related
I am creating a code that checks for the current location, however, when I check for the current location, it crashes. I looked into Stack Trace and saw this. I read other forums but I am not familiar with their solutions. I am also a beginner in Java. I used an Amazon Fire Tablet to download this app. When I tried testing it on the emulator, the app did not crash.
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.settings.LOCALE_SETTINGS }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1797)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1517)
at android.app.Activity.startActivityForResult(Activity.java:3761)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
at android.app.Activity.startActivityForResult(Activity.java:3722)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
at android.app.Activity.startActivity(Activity.java:4032)
at android.app.Activity.startActivity(Activity.java:4000)
at com.example.calculatorandlocationfinderfinal.MainActivity$7.onClick(MainActivity.java:181)
at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5491)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:984)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Below is the code where it happened.
private void onGPS() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Enable GPS").setCancelable(false).setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Settings.ACTION_LOCALE_SETTINGS));
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
Always use this method to start intents other than your app's -
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
if(intent.resolveActivity(context.getPackageManager()) != null){
startActivity(intent);
}else{
//handle activity not found
}
this way you won't get ActivityNotFoundException.
You can also use try catch as -
try {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
} catch (e: ActivityNotFoundException) {
//handle activity not found
}
I suppose you want to navigate to GPS settings screen.
try this.
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
The phone/device might be missing locale settings screen altogether which leads to the crash.
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //This line solve my issue
startActivity(viewIntent);
I'm trying to make a dialogue box with a positive bottom that changes the activity from SignupAcitvity to MainActivity. So I used the intent method to do this. However, once I tried this, I got the following error message:Cannot Resolve constructor 'Intent(com.androidcodefinder.loginscreendemo.Profile.ExampleDialogue, java.lang.Class<com.androidcodefinder.loginscreendemo.MainActivity>)'. Can you help me fix this?
My code:
public class ExampleDialogue extends AppCompatDialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialayout,null);
builder.setView(view)
.setTitle("Confirm Your Email")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(SignUpActivity.class, MainActivity.class);
startActivity(intent);
}
});
return builder.create();
}
}
The reason that you are getting this error is because you are in the ExampleDialogue activity, but you are starting an intent from SignUpActivity.class to MainActivity.class. If you want to go to MainActivity.class, you will have to do:
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
Also, it can't resolve the constructor so just add this default constructor, which you can change as you wish:
public ExampleDialogue(){
//Constructor code.
}
You are trying
Intent intent = new Intent(SignUpActivity.class, MainActivity.class)
However, Intent has no constructor with 2 classes as arguments. Hence the error.
What you want, is to use the constructor Intent(Context, Class<?>). Specifially, in your case you do this:
Intent intent = new Intent(getActivity(), MainActivity.class);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
My application stopped when I finished working on the quiz application. I'm learning to make an Android application quiz using MySQL database, but I get the problem when the last question will move to the scoring page.
10-28 01:02:25.816 31874-31874/com.example.nuvo.myapplication
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.nuvo.myapplication, PID: 31874
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.nuvo.myapplication/com.example.nuvo.myapplication.Complete}:
java.lang.NullPointerException
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2429)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.access$800(ActivityThread.java:166)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
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:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at
com.example.nuvo.myapplication.Complete.onCreate(Complete.java:18)
at android.app.Activity.performCreate(Activity.java:5442)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.access$800(ActivityThread.java:166)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
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:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Complate.java
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class Complete extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complete);
int score = getIntent().getExtras().getInt("score");
AlertDialog.Builder builder = new AlertDialog.Builder(Complete.this);
builder.setTitle("Quiz Complete");
builder.setMessage("Your Score is: " +score+ " out of 10");
builder.show();
builder.setPositiveButton("Play Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
Intent intent = new Intent(Complete.this, QuizActivity.class);
startActivity(intent);
}
});
builder.setNegativeButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void restartQuiz(View view)
{
Intent intent = new Intent(Complete.this, QuizActivity.class);
startActivity(intent);
}
public void mainMenu(View view)
{
Intent intent = new Intent(Complete.this, MainActivity.class);
startActivity(intent);
}
}
QuizActivity.java
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class Complete extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complete);
int score = getIntent().getExtras().getInt("score");
AlertDialog.Builder builder = new AlertDialog.Builder(Complete.this);
builder.setTitle("Quiz Complete");
builder.setMessage("Your Score is: " +score+ " out of 10");
builder.show();
builder.setPositiveButton("Play Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
Intent intent = new Intent(Complete.this, QuizActivity.class);
startActivity(intent);
}
});
builder.setNegativeButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void restartQuiz(View view)
{
Intent intent = new Intent(Complete.this, QuizActivity.class);
startActivity(intent);
}
public void mainMenu(View view)
{
Intent intent = new Intent(Complete.this, MainActivity.class);
startActivity(intent);
}
}
This line is problematic in your code:
int score = getIntent().getExtras().getInt("score");
It seems that your Intent, which opened your Complete activity did not have an integer "score" and hence returned null, which caused NullPointerException. To avoid such problems consider using another method getInt(String key, int defaultValue) s.a. this:
int score = getIntent().getExtras().getInt("score", 0);
This way you'll not get an exception if your Intent arrives without a value, but it will be set to 0 by default.
I am not sure what I have done but for a moment my code was working smoothly and after I added a new activity the error Attempted to finish an input event but the input event receiver has already been disposed.
I need help on how to fix this.
package proj.com.desperationfinals;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
}
public void validate (View view){
String word = editText.getText().toString();
if(word.contentEquals("Sir Zalameda")) {
AlertDialog.Builder Alert = new AlertDialog.Builder(this);
Alert.setMessage("Correct!")
.create();
Alert.show();
Intent i = new Intent(MainActivity.this, Main2Activity.class);
startActivity(i);
}else{
AlertDialog.Builder Alert = new AlertDialog.Builder(this);
Alert.setMessage("Mali!")
.create();
Alert.show();
}
}
}
The problem is in the following section:
AlertDialog.Builder Alert = new AlertDialog.Builder(this);
Alert.setMessage("Correct!")
.create();
Alert.show();
Intent i = new Intent(MainActivity.this, Main2Activity.class);
startActivity(i);
You are getting the error because you are trying to show an alert right before starting a new activity. Now, the 'receiver' for the dialog is the current activity and as soon as you start new activity that is switched. To tackle this problem you can try something like this:
Alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(MainActivity.this, Main2Activity.class);
startActivity(i);
}
TL;DR: Can't show an alert right before starting a new activity.
So I have a service that contains a Timer. The service is meant to run even when the app in the background and is supposed to pull the user to the app when the timer executes the method(from another activity). The service is triggered on and off by a toggle button. Currently my R.id reference to my spinner keeps throwing a NullPointerException that i don't know how to fix. Can someone please help me out?
The Method the Timer is running:
public String TemperatureCatch()
{
/*this line throws the error */ Spinner reeferchoice = (Spinner)findViewById(R.id.optionselecti);
String reeferChoicei = reeferchoice.getSelectedItem().toString();
if (reeferChoicei.equals("Yes")) {
final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 500);
tg.startTone(ToneGenerator.TONE_CDMA_ABBR_ALERT);
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Temperature");
alert.setMessage("Input Temperature in F° (-20 to 65) ");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_PHONE);
alert.setView(input);
alert.setPositiveButton("Check-In", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
temperaturei = input.getText().toString();
Toast.makeText(getBaseContext(), "Updated", Toast.LENGTH_SHORT).show();
Updater(temperaturei);
}
});
alert.show();
} else if (reeferChoicei.equals("No")) {
temperaturei = "DRY";
Updater(temperaturei);
}
return temperaturei;
}
My service code:
import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import java.util.Timer;
import java.util.TimerTask;
public class MyService extends Service {
Locator locator;
Timer myTimer;
#Override
public void onCreate() {
locator = new Locator();
myTimer = new Timer();
}
private class MyTimerTask extends TimerTask
{
#Override
public void run() {
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
locator.TemperatureCatch();
}
}, 1000);
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
MyTimerTask myTimerTask = new MyTimerTask();
myTimer.scheduleAtFixedRate(myTimerTask, 0, 15000);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
myTimer.cancel();
}
}
the button:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isChecked)
{
startService(new Intent(this, MyService.class));
Toast.makeText(this,"Check-In will be done every 15 seconds",Toast.LENGTH_SHORT).show();
}
else
{
stopService(new Intent(this, MyService.class));
Toast.makeText(this,"Manual Check-In enabled",Toast.LENGTH_SHORT).show();
}
}
the stack trace:
Process: com.example.adrian.trucktracker, PID: 9617
java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1952)
at com.example.adrian.trucktracker.Locator.TemperatureCatch(Locator.java:192)
at com.example.adrian.trucktracker.MyService$MyTimerTask$1.run(MyService.java:32)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
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:852)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:668)
at dalvik.system.NativeStart.main(Native Method)
You should not create a instance of Activity class.
locator = new Locator(); // do not do this
This results in NullPointerException when you initialize views.
Can i Create the object of a activity in other class?
Also what you are doing seems to be a design issue.
As previous comments already pointed out, service wont have any UI, so you cannot make findViewById method call.
If you want your service to change the UI, bind to this service from your activity and using callbacks/delegates, you can notify the activity to change the UI from the service.
Activity objects are not supposed to be initialized by calling its constructor. By doing so, your overriden method onCreate() never get called, so the views are not initialized and findViewById will fail.
You should instead start the activity in the service instead of calling its contructor, something like this:
Intent t = new Intent (this, Locator.class);
t.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(t);
You can have a static getter in Locator class to get the instance of the Activity, so that you can use it in the Service.