This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have created an app with 5 tabs, in my 1st tab I am having a button on click of which I want to go to tab3. This is my code of button event --
moreButton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(view.getContext(), Tab3_Image.class);
view.getContext().startActivity(intent);
}
});
But while clicking the button the app crash, below is the logcat error --
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.s2s.doupnow, PID: 22481
java.lang.NullPointerException
at com.s2s.doupnow.Tab1_Home$6.onClick(Tab1_Home.java:313)
at android.view.View.performClick(View.java:4444)
at android.view.View$PerformClick.run(View.java:18457)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5113)
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:796)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
at dalvik.system.NativeStart.main(Native Method)
Change this -:
moreButton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(view.getContext(), Tab3_Image.class);
view.getContext().startActivity(intent);
}
});
To-:
private Context context=this; //make it global
Button moreButton3=(Button)findViewById(R.id.buttoninxml);
moreButton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Tab3_Image.class);
startActivity(intent);
}
});
Related
I have an AlertDialog it works fine but I noticed that it marks me an error in the line where I put dialog.show (); I do not know how I could solve it.
IngresarAdmin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder mBuilder=new AlertDialog.Builder(InicioSesion_Principal.this);
View Mview= getLayoutInflater().inflate(R.layout.zona_restrigida,null);
final EditText claveAdmin=(EditText)Mview.findViewById(R.id.Clave_proveedor);
Button EntrarClaveAdmin=(Button)Mview.findViewById(R.id.Ingresar_clave_proovedor);
EntrarClaveAdmin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!claveAdmin.getText().toString().isEmpty()){
Intent intent=new Intent(getApplicationContext(), menu_administrador.class);
startActivity(intent);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
finish();
}
else {
Toast.makeText(InicioSesion_Principal.this,"Clave incorrecta",Toast.LENGTH_SHORT).show();
}
}
});
mBuilder.setView(Mview);
AlertDialog dialog=mBuilder.create();
dialog.show();
}
});
This is the error that shows me in the dialog.show();
It does not close the application at any time, but how can I fix it?
android.view.WindowLeaked: Activity com.tienda.app.aplicaciontienda.Iniciar_Sesion_3.InicioSesion_Principal has leaked window com.android.internal.policy.PhoneWindow$DecorView{245d004 V.E...... R......D 0,0-683,503} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:375)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:299)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:319)
at com.tienda.app.aplicaciontienda.Iniciar_Sesion_3.InicioSesion_Principal$3.onClick(InicioSesion_Principal.java:119)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21163)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
try using dialog.create().show();
I had the same problem.
You need to call .dismiss();
if(dialog != null)
dialog.dismiss();
We are writing an android based Application that tracks several Mobilephone sensors now I tried compiling the code when suddenly this happend
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.max.pswi, PID: 14291
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.max.pswi/com.example.max.pswi.MainActivity}:
java.lang.ClassNotFoundException: Didn't find class "com.example.max.pswi.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.max.pswi-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2555)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.max.pswi.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.max.pswi-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at android.app.Instrumentation.newActivity(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2545)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Suppressed: java.lang.ClassNotFoundException: com.example.max.pswi.MainActivity
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 13 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
I have no Idea why this error occurs
Im programming on Android Studio
Heres the MainActivity-Code that creates the error:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
int currentVersionCode = 0;
try {
currentVersionCode = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode;
} catch (PackageManager.NameNotFoundException e1) {
e1.printStackTrace();
}
final ImageButton export = (ImageButton) findViewById(R.id.export);
final ImageButton clear = (ImageButton) findViewById(R.id.clear);
final ToggleButton toggle = (ToggleButton) findViewById(R.id.anaus);
final ImageButton settingsBtn = (ImageButton) findViewById(R.id.settings);
final ImageButton aktualisieren = (ImageButton) findViewById(R.id.aktualisieren);
final ListView liste = (ListView)findViewById(R.id.infos);
if (CheckIfServiceIsRunning())
toggle.setChecked(true);
Boolean status = CheckIfServiceIsRunning();
aktualisieren.setVisibility(View.VISIBLE);
export.setVisibility(View.VISIBLE);
toggle.setVisibility(View.VISIBLE);
settingsBtn.setVisibility(View.VISIBLE);
/* clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SensorManager.getInstance().clearValues(SensorManager.getInstance().getContext());
}
});
export.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SensorManager.getInstance().exportValues(SensorManager.getInstance().getContext());
}
});
settingsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
}
});
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
Boolean status = CheckIfServiceIsRunning();
ComponentName cn = new ComponentName(getApplicationContext(), NLService.class);
String flat = Settings.Secure.getString(getApplicationContext().getContentResolver(), "enabled_notification_listeners");
final boolean enabled = (flat != null && flat.contains(cn.flattenToString()));
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
if (!enabled) {
final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setCancelable(false);
alertDialog.setTitle("Notificationlistener aktivieren");
alertDialog.setMessage("Bitte aktivieren sie den Notificationlistener für die App PSWI");
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Aktivieren", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.cancel();
Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
Intent i = new Intent(getApplicationContext(), MainService.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startService(i);
status = true;
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "zurueck", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.cancel();
}
});
alertDialog.show();
} else {
Intent i = new Intent(getApplicationContext(), MainService.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startService(i);
status = true;
}
} else {
// The toggle is disabled
Intent i = new Intent(getApplicationContext(), MainService.class);
getApplicationContext().stopService(i);
status = false;
}
}
});
// SensorManager.getInstance().populateListView(liste);
settings = PreferenceManager.getDefaultSharedPreferences(this);
if (settings.getBoolean("first_start", true)) {
// set initial version code, set first_start true and create ID
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("first_start", false);
editor.putBoolean("SMSSensor:ObserverStarted", false);
editor.putString("CallSensor:lastIntent", null);
editor.putBoolean("serviceStarted", false);
editor.putString("version", "" + currentVersionCode);
editor.putString("ID", ""
+ ((TelephonyManager) getApplicationContext()
.getSystemService(TELEPHONY_SERVICE))
.getDeviceId().hashCode());
editor.apply();
}
// getLoaderManager().initLoader(0, null, (android.app.LoaderManager.LoaderCallbacks<Cursor>) this);
*/
}
I would be glad if someone could take a look at this I'm getting desperate
Have you declared this MainActivity in AndroidManifest file?
Check AndroidManifest.xml
You should see your activity within the application tag like so:
<activity android:name="com.example.max.pswi.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm generating a click event in android and i used wrote the code in this way
public class LoginActivity extends AppCompatActivity {
Button btnLogin;
EditText inputEmail,inputPassword;
protected String enteredEmail;
String enteredPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// inputEmail = (EditText) findViewById(R.id.email);
// inputPassword = (EditText) findViewById(R.id.password);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(i);
}});}
but getting the below error
TextInputLayout: EditText added is not a TextInputEditText. Please
> switch to using that class instead. 03-11 01:41:52.214
> 21936-21936/com.example.smartlayer.myhive_app I/TextInputLayout:
> EditText added is not a TextInputEditText. Please switch to using that
> class instead. 03-11 01:41:52.294
> 21936-21936/com.example.smartlayer.myhive_app D/AndroidRuntime:
> Shutting down VM 03-11 01:41:52.294
> 21936-21936/com.example.smartlayer.myhive_app W/dalvikvm: threadid=1:
> thread exiting with uncaught exception (group=0xb4ae3ba8) 03-11
> 01:41:52.334 21936-21936/com.example.smartlayer.myhive_app
> E/AndroidRuntime: FATAL EXCEPTION: main
> Process: com.example.smartlayer.myhive_app, PID: 21936
> java.lang.RuntimeException: Unable to start activity
How i solve this error ?
You are missing to initialize Button
btnLogin = (Button) findViewById(R.id.Set_Button_Id);
Like
btnLogin = (Button) findViewById(R.id.Set_Button_Id);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(i);
}});}
When trying to move to another activity the app crashes...
logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{myact.julianhernandez.com.counterapp/myact.julianhernandez.com.counterapp.CounterDisplay}: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:244)
at android.widget.TextView.setText(TextView.java:3888)
at myact.julianhernandez.com.counterapp.CounterDisplay.onCreate(CounterDisplay.java:31)
at android.app.Activity.performCreate(Activity.java:5231)
MainActivity.class Code
public class MainActivity extends AppCompatActivity {
Button moveActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
moveActivity = (Button) findViewById(R.id.list1_button);
moveActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent toCounter = new Intent(MainActivity.this , CounterDisplay.class);
startActivity(toCounter);
}
});
CounterDisplay.class Code
public class CounterDisplay extends AppCompatActivity {
private TextView countView;
private Button addButton;
private Button subtractButton;
//int initialCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counter_display);
countView = (TextView) findViewById(R.id.currentCount);
addButton = (Button) findViewById(R.id.add);
subtractButton = (Button) findViewById(R.id.subtract);
countView.setText(0);
//increment counter by 1
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currentCount;// = initialCount;
for(currentCount=0;currentCount>=0;currentCount++){
countView.setText(currentCount);
}
}
});
}
}
Why does this code crash when switching activities?
Textview.setText(int) method takes a resource ID, not the text you are trying to display. Because there are no resource strings matching the ID you pass in (which is 0 on line 31), an exception gets thrown.
There are additional overloads of the setText() method that allow you to pass in a char[] if you don't want to use resource strings. View the documentation for more information. http://developer.android.com/reference/android/widget/TextView.html
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.