I ran into this problem just now, scratching my head on how to tackle this problem.
Basically, I have MainActivity, and a lot of classes in my app, such as RootUtils, LegalProsecution, CameraSilencer, etc, etc. MainActivity is the only activity in this app, and the rest is just classes for executing code, showing dialogs, etc.
The particular class I have problem with is LegalProsecution.java, which is responsible for opening a dialog on first launch and show the users legal stuff. However, the stack trace points to line 48, which is simply dialog.show();
Here is the full stack trace:
05-01 19:01:08.075 21777-21777/ideaman924.camerasilencer E/AndroidRuntime: FATAL EXCEPTION: main
Process: ideaman924.camerasilencer, PID: 21777
Theme: themes:{}
java.lang.RuntimeException: Unable to start activity ComponentInfo{ideaman924.camerasilencer/ideaman924.camerasilencer.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2504)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5458)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.support.v7.app.AppCompatDelegateImplV7.createSubDecor(AppCompatDelegateImplV7.java:340)
at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:309)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:273)
at android.support.v7.app.AppCompatDialog.setContentView(AppCompatDialog.java:80)
at android.support.v7.app.AlertController.installContent(AlertController.java:214)
at android.support.v7.app.AlertDialog.onCreate(AlertDialog.java:256)
at android.app.Dialog.dispatchOnCreate(Dialog.java:394)
at android.app.Dialog.show(Dialog.java:295)
at ideaman924.camerasilencer.LegalProsecution.warningShow(LegalProsecution.java:48)
at ideaman924.camerasilencer.MainActivity.onCreate(MainActivity.java:20)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2504)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5458)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Anybody know what's the problem? Thanks.
EDIT: Here is LegalProsecution.java, which handles dialog creation:
package ideaman924.camerasilencer;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
public class LegalProsecution {
Context context = MyApp.getContext();
AppPreference appprefs = AppPreference.getInstance(context);
public void warningShow()
{
if(appprefs.loadSettings() == 1);
else
{
AlertDialog.Builder builder1 = new AlertDialog.Builder(MyApp.getContext());
builder1.setTitle(context.getResources().getString(R.string.warning));
builder1.setMessage(context.getResources().getString(R.string.warning_description));
builder1.setCancelable(true);
builder1.setPositiveButton(
context.getResources().getString(R.string.yes),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Got promise from user, now setting first_run to 1
appprefs.storeSettings(1);
dialog.cancel();
}
}
);
builder1.setNegativeButton(
context.getResources().getString(R.string.no),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Okay, cool, bye! No CS for you!
dialog.cancel();
((Activity)context).finish();
System.exit(0);
}
}
);
AlertDialog alert1 = builder1.create();
alert1.show();
}
}
}
And here is MyApp.java, which I used as a workaround to solve the stupid context issue:
package ideaman924.camerasilencer;
import android.app.Application;
import android.content.Context;
public class MyApp extends Application
{
private static MyApp instance;
public static MyApp getInstance() {
return instance;
}
public static Context getContext(){
return instance.getApplicationContext();
}
#Override
public void onCreate() {
super.onCreate();
instance = this;
}
}
Don't use
MyApp.getContext();
Create a constructor, and assign a context like
public LegalProsecution(Context context){
this.context = context;
}
Then when you create an instance, Create like this
LegalProsecution lp = new LegalProsecution(MyActivity.this);
Then don't forget to create alert dialog using the context you just assigned to
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
I think the activity you are trying to apply the dialog theme to is extending ActionBarActivity. Try to extends AppCompat instead.
Verify that your app theme is set to AppCompat android:theme="#style/Theme.AppCompat.light
cause Dialog require it.
If that's true, this is probably due to the inheritance of your main class wich set the theme to an other one.
Related
I have integrated Trusted Web Activity in my Android App when launching TwalauncherActivity as main Activity, App is not opening, it's stopping suddenly & closing automatically.
I have followed this link to add Trusted web Activity.
Logcat:-
FATAL EXCEPTION: main
Process: com.therightdoctors.cathlab, PID: 2906
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.therightdoctors.cathlab/com.therightdoctors.cathlab.TwaLauncherActivity}: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=android.support.customtabs.action.CustomTabsService }
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.IllegalArgumentException: Service Intent must be explicit: Intent { act=android.support.customtabs.action.CustomTabsService }
TwaLauncherActivity.java:-
package com.therightdoctors.dpmpatient;
import android.net.Uri;
import android.os.Bundle;
import android.support.customtabs.CustomTabsIntent;
import android.support.v7.app.AppCompatActivity;
public class TwaLauncherActivity extends AppCompatActivity
implements TwaSessionHelper.TwaSessionCallback {
private static final String TWA_ORIGIN = "https://dpmp.therightdoctors.com";
private static final String TARGET_URL = TWA_ORIGIN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twa_launcher);
Uri originUri = Uri.parse(TWA_ORIGIN);
TwaSessionHelper twaSessionHelper = TwaSessionHelper.getInstance();
twaSessionHelper.setTwaSessionCallback(this);
twaSessionHelper.bindService(this, originUri);
}
#Override
protected void onDestroy() {
super.onDestroy();
TwaSessionHelper twaSessionHelper = TwaSessionHelper.getInstance();
twaSessionHelper.setTwaSessionCallback(null);
}
public void openTwa() {
TwaSessionHelper twaSessionHelper = TwaSessionHelper.getInstance();
// Set an empty transition from TwaLauncherActivity to the TWA splash screen.
CustomTabsIntent customTabsIntent = twaSessionHelper.createIntentBuilder()
.setStartAnimations(this, 0, 0)
.build();
Uri openUri = Uri.parse(TARGET_URL);
twaSessionHelper.openTwa(this, customTabsIntent, openUri);
}
#Override
public void onTwaSessionReady() {
openTwa();
}
#Override
public void onTwaSessionDestroyed() {
}
#Override
public void onTwaOpened() {
finishAndRemoveTask();
}
}
The linked demo is outdated (the link is currently broken too, as the demo was moved here)
This is the current code for the update LauncherActivity, inside the Support Library.
The latest version of the Support Library supporting TWAs is being hosted in JitPack temporarily.
It will be merged into the official support library in the near future.
This is the weirdest thing.. A few weeks ago I ran into this issue and found the solution to be to update the Gradle Runtime, which I did on both computers. I decided I wanted to sit at my desk with my iMac and work last night, but could not get the app to run do to a Kotlin Typecast Exception. I switched to the remote branch I have pulled on my MacBook, but got this error:
09-23 12:28:29.112 4141-4141/com.example.pmarl.peedeehealthadvisor E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.pmarl.peedeehealthadvisor, PID: 4141
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.pmarl.peedeehealthadvisor/com.example.pmarl.peedeehealthadvisor.MainActivity}: kotlin.TypeCastException: null cannot be cast to non-null type android.widget.Button
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: kotlin.TypeCastException: null cannot be cast to non-null type android.widget.Button
at com.example.pmarl.peedeehealthadvisor.MainActivity.onCreate(MainActivity.kt:31)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I panic'd and tested the MacBook again, but it worked fine.
`
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
private Button MyHealthData;
private Button MyHealthResources;
private boolean firstStart;
#Override
protected void onCreate(Bundle saveInstanceState)
{
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_main);
/*First time open code*/
SharedPreferences app_preferences = getApplicationContext()
.getSharedPreferences("MyPref",0);
SharedPreferences.Editor editor = app_preferences.edit();
firstStart = app_preferences.getBoolean("first_time_start",true);
/*If statement to see if the app has been open before or not*/
if(firstStart)
{
/*If the app hasn't been opened before, it runs the following code
* and sets firstStart to false*/
editor.putBoolean("first_time_start",false);
editor.commit();
//do your one time code here
launchFirstTimeLogIn();
//Toast.makeText(this,"This is first app run!", Toast.LENGTH_LONG).show();
}
else
{
//app open directly
Toast.makeText(this, "Welcome!!!", Toast.LENGTH_LONG).show();
}
this.MyHealthData = (Button) findViewById(R.id.MyHealthData);
this.MyHealthData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
launchMyHealthData();
}
});
this.MyHealthResources = (Button) findViewById(R.id.HealthResources);
this.MyHealthResources.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
launchSearchServiceActivity();
}
});
}
private void launchMyHealthData()
{
Intent intent = new Intent (this, MyHealthDataActivity.class);
intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK | intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
private void launchSearchServiceActivity()
{
Intent intent = new Intent (this, SearchServiceActivity.class);
intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK | intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
private void launchFirstTimeLogIn()
{
Intent intent = new Intent(this, FirstTimeLogin.class);
intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK | intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
`
Both are the same Gradle versions, and the same version of Android Studio. I"m not sure what this would be caused by? My logic says that if it is the Button causing the issue, like the posts I found say, it wouldn't work on my MacBook.
Thank you for the help everyone!
null cannot be cast to non-null type android.widget.Button
I'm assuming that you declared a Button like this: (for example)
mineBtn = findViewById(R.id.yourbtnid) as Button
Add "?" after the as:
mineBtn = findViewById(R.id.yourbtnid) as? Button
Then error should be gone.
Edit: Remove this. before declaring widgets. And declare a widget like this:
MyHealthData = (Button) findViewById(R.id.MyHealthData);
Note that it's better to change R.id.MyHealthData from xml layout to be make sure it won't cause other issues in future.
I am building a simple app which switches on the Bluetooth of a device and sets it to visible.
I have a separate java class file which has the Bluetooth functions I need, and these are called from another java class which is linked to my activity, through an object of the said class.
This is my code:
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
/**
* Created by mark on 11/11/2016.
*/
public class Bluetooth_API extends AppCompatActivity{
BluetoothAdapter blueAdp;
public Bluetooth_API() {
blueAdp = BluetoothAdapter.getDefaultAdapter();
}
protected int bluetooth_ON() {
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 0);
//blueAdp.enable(); //instead of above line - without alert dialog for permission
return 0;
}
protected int bluetooth_OFF() {
blueAdp.disable(); //
return 0;
}
protected int bluetooth_setVisible() {
if(!blueAdp.isDiscovering()) {
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE), 0);
}
return 0;
}
}
And this is the part of the code from the other activity which is calling my functions:
scanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent nextLayout = new Intent(getApplicationContext(), com.ai.mark.robot_dancing.Scanning_Devices.class);
startActivity(nextLayout);
blue.bluetooth_ON();
//blue.bluetooth_setVisible();
}
});
I am getting the error below once I run my code, I believe it has to do with the activity not being the right one since my Bluetooth functions are in another file (I also tried copying the methods to my activity class and they worked beautifully).
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ai.mark.robot_dancing, PID: 21314
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread
android.app.ActivityThread.getApplicationThread()' on a null object
reference
at android.app.Activity.startActivityForResult(Activity.java:3951)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:77)
at android.app.Activity.startActivityForResult(Activity.java:3912)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
at com.ai.mark.robot_dancing.Bluetooth_API.bluetooth_ON(Bluetooth_API.java:20)
at com.ai.mark.robot_dancing.Bluetooth_Panel$6.onClick(Bluetooth_Panel.java:146)
at android.view.View.performClick(View.java:5210)
at android.view.View$PerformClick.run(View.java:21328)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5551)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Any ideas on what is causing this?
Thanks.
Don't invoke such code in Activity constructor:
blueAdp = BluetoothAdapter.getDefaultAdapter();
Use onCreate(android.os.Bundle) for that:
#Override
protected void onCreate(Bundle savedInstanceState) {
blueAdp = BluetoothAdapter.getDefaultAdapter();
}
I've been trying to get a dialog message to work on android and the app always crash when it reaches "dialog.show();"
public class Logic extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
dialogBuilder.setTitle("Alarm");
dialogBuilder.setMessage(messageActivity.getMes());
dialogBuilder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = dialogBuilder.create();
dialog.show();
}
}
Here is my logcat:
FATAL EXCEPTION: main
Process: it226.myapplicationit226androidapp, PID: 19598
java.lang.RuntimeException: Unable to start receiver it226.myapplicationit226androidapp.Logic: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2732)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:571)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:310)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:319)
at it226.myapplicationit226androidapp.Logic.onReceive(Logic.java:65)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2725)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
You can't create dialog from receiver.
Creating dialogs is allowed only from UI components (which have looper).
You could start transparent activity with dialog, which would be the same for user.
You can't create a dialog using the context of a BroadcastReceiver, you has two options to solve this problem:
first one is to create a regular Activity which has only the size of the dialog as a shown part and the full remaining is transparent:
Intent newIntent = new Intent(context, Displayer.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(newIntent);
second one is to hold your Activity context and then use it in creating the dialog, but at this method you have to make sure what is the activity that is currently open:
// in your activity onCreate
ctx = YourActivity.this; // let's suppose ctx is static and general var
////////////////////////////////////////////////
// in the BroadcastReceiver
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(YourActivity.ctx);
so I've been working on a simple app that mutes and un-mutes the camera and yes, I know this app would be illegal in many countries, but! I'm willing to try. And anyway, disclaimers are there if things get rough.
While developing, I ran into this issue when trying to call out SharedPreferences. This is how my code is formulated right now.
MainActivity.java, initializes everything, and calls...
LegalProsecution.java, which tries to warn the user if the first_run is set..
AppPreferences.java handles giving first_run status to LP.java.
So, I've been having problems with AppPreferences.java. Here is the code:
package ideaman924.camerasilencer;
import android.content.Context;
import android.content.SharedPreferences;
public class AppPreference
{
SharedPreferences prefs;
public AppPreference(String buffer, Context context)
{
prefs = context.getSharedPreferences("ideaman924.camerasilencer.first_run", Context.MODE_PRIVATE);
}
public void storeSettings(String buffer, int num)
{
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(buffer, num);
editor.apply();
}
public int loadSettings(String buffer)
{
return prefs.getInt(buffer,0);
}
}
This is the line that is giving me the ultimatum:
prefs = context.getSharedPreferences("ideaman924.camerasilencer.first_run", Context.MODE_PRIVATE);
Here is a crash log from logcat:
05-05 10:10:33.233 9099-9099/ideaman924.camerasilencer E/AndroidRuntime: FATAL EXCEPTION: main
Process: ideaman924.camerasilencer, PID: 9099
Theme: themes:{}
java.lang.RuntimeException: Unable to start activity ComponentInfo{ideaman924.camerasilencer/ideaman924.camerasilencer.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2504)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5458)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
at ideaman924.camerasilencer.AppPreference.<init>(AppPreference.java:12)
at ideaman924.camerasilencer.LegalProsecution.<init>(LegalProsecution.java:11)
at ideaman924.camerasilencer.MainActivity.onCreate(MainActivity.java:19)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2504)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5458)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
From my guesses, SharedPreferences prefs churns out a null object, and I'm trying to reference that. But why? Why would it be a null object? And also, I'm trying to initialize the prefs, not reference it!
Any help would be appreciated.
EDIT1: Seems like error is in LegalProsecution.java, as mentioned by cricket_007:
package ideaman924.camerasilencer;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
public class LegalProsecution
{
private Context context;
public LegalProsecution(Context context)
{
this.context = context;
}
AppPreference appprefs = new AppPreference("settings",this.context);
public void warningShow()
{
if(appprefs.loadSettings("first_run") != 1) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setTitle(context.getResources().getString(R.string.warning));
builder1.setMessage(context.getResources().getString(R.string.warning_description));
builder1.setCancelable(true);
builder1.setPositiveButton(
context.getResources().getString(R.string.yes),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Got promise from user, now setting first_run to 1
appprefs.storeSettings("first_run", 1);
dialog.cancel();
}
}
);
builder1.setNegativeButton(
context.getResources().getString(R.string.no),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Okay, cool, bye! No CS for you!
dialog.cancel();
((Activity) context).finish();
System.exit(0);
}
}
);
AlertDialog alert1 = builder1.create();
alert1.show();
}
}
}
Any problems?
Rewrite like so
AppPreference appprefs;
public LegalProsecution(Context context)
{
this.context = context;
this.appprefs = new AppPreference("settings", context);
}
Because this.context will be null until the constructor is called.