Trying to reference a null-object reference? - java

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.

Related

Unable to start activity ComponentInfo NPE [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am trying to make an app on Android, using Kotlin and Java.
My inspiration comes from this tutorial:
https://www.youtube.com/watch?v=Qg3L_B9--zY
I changed it a little bit, and now I have a beautiful error:
"Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference"
Here is the error log:
11-21 10:46:03.006 27125-27125/? E/libprocessgroup: failed to make and chown /acct/uid_10058: Read-
only file system
11-21 10:46:03.006 27125-27125/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
11-21 10:46:03.006 27125-27125/? I/art: Not late-enabling -Xcheck:jni (already on)
11-21 10:46:03.079 27125-27125/com.example.budgetapp I/System.out: Util Constructor
11-21 10:46:03.143 27125-27125/com.example.budgetapp E/MainActivity: before onCreate()
11-21 10:46:03.150 27125-27125/com.example.budgetapp W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
11-21 10:46:03.183 27125-27125/com.example.budgetapp E/MainActivity: after onCreate()
11-21 10:46:03.206 27125-27125/com.example.budgetapp I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
11-21 10:46:03.206 27125-27125/com.example.budgetapp I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
11-21 10:46:03.275 27125-27125/com.example.budgetapp E/MainActivity: after setContentView()
11-21 10:46:03.275 27125-27125/com.example.budgetapp D/AndroidRuntime: Shutting down VM
--------- beginning of crash
11-21 10:46:03.276 27125-27125/com.example.budgetapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.budgetapp, PID: 27125
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.budgetapp/com.example.budgetapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
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: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:149)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
at android.content.Context.obtainStyledAttributes(Context.java:437)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at Util.setupUIViews(Util.java:43)
at com.example.budgetapp.MainActivity.onCreate(MainActivity.kt:27)
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) 
And here are my classes:
MainActivity.kt:
package com.example.budgetapp
import Util
import android.app.DatePickerDialog
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class MainActivity : AppCompatActivity() {
private val tag = "MainActivity"
var util = Util()
override fun onCreate(savedInstanceState: Bundle?) {
Log.e(tag, "before onCreate()")
super.onCreate(savedInstanceState)
Log.e(tag, "after onCreate()")
setContentView(R.layout.activity_main)
Log.e(tag, "after setContentView()")
util.setupUIViews()
Log.e(tag, "after setupUIView()")
util.initToolbar()
Log.e(tag, "after initToolbar()")
util.setupListView()
Log.e(tag, "after setupListView()")
//Calendars:
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
val c2 = Calendar.getInstance()
val year2 = c2.get(Calendar.YEAR)
val month2 = c2.get(Calendar.MONTH)
val day2 = c2.get(Calendar.DAY_OF_MONTH)
Log.e(tag, "year1: $year")
Log.e(tag, "month1: $month")
Log.e(tag, "month2: $month2")
Log.e(tag, "day1: $day")
//button click to show DatePickerDialog
pickDateBtn.setOnClickListener {
val dpd = DatePickerDialog(
this,
DatePickerDialog.OnDateSetListener {_, mYear, mMonth, mDay ->
var monthSel=mMonth+1
dateTv2.text = "$mDay/$monthSel/$mYear"
},
year,
month,
day
)
dpd.show()
val dpd2 = DatePickerDialog(
this,
DatePickerDialog.OnDateSetListener {_, mYear2, mMonth2, mDay2 ->
var monthSel2=mMonth2+1
dateTv.text = "$mDay2/$monthSel2/$mYear2"
},
year2,
month2,
day2
)
dpd2.show()
}
}
}
SimpleAdapter.java:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.budgetapp.R;
public class SimpleAdapter extends BaseAdapter {
public Context mContext;
private LayoutInflater layoutInflater;
private TextView title, description;
private String[] titleArray, descriptionArray;
private ImageView imageView;
public SimpleAdapter(Context context, String[] title, String [] description){
mContext= context;
titleArray=title;
descriptionArray= description;
layoutInflater= LayoutInflater.from(context);
}
#Override
public int getCount(){
return titleArray.length;
}
#Override
public Object getItem(int position) {
return titleArray[position];
}
#Override
public long getItemId(int position){
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
layoutInflater.inflate(R.layout.main_activity_single_item, null);
}
title= convertView.findViewById(R.id.tvMain);
description = convertView.findViewById(R.id.tvDescription);
imageView = convertView.findViewById(R.id.ivMain);
title.setText(titleArray[position]);
description.setText(descriptionArray[position]);
if(titleArray[position].equalsIgnoreCase("Timetable")){
imageView.setImageResource(R.drawable.timetable);
}else if(titleArray[position].equalsIgnoreCase("Subjects")){
imageView.setImageResource(R.drawable.book);
}else if(titleArray[position].equalsIgnoreCase("Faculty")) {
imageView.setImageResource(R.drawable.play);
}else{
imageView.setImageResource(R.drawable.settings);
}
return convertView;
}
}
and Util.java:
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.example.budgetapp.R;
import java.util.logging.Logger;
public class Util extends AppCompatActivity {
public Util(){
System.out.println("Util Constructor");
}
public Toolbar getToolbar() {
return toolbar;
}
public void setToolbar(Toolbar toolbar) {
this.toolbar = toolbar;
}
public ListView getListView() {
return listView;
}
public void setListView(ListView listView) {
this.listView = listView;
}
#Override
public String toString() {
return "Util{" +
"toolbar=" + toolbar +
", listView=" + listView +
'}';
}
private Toolbar toolbar;
private ListView listView;
Logger logger;
public void setupUIViews(){
toolbar = findViewById(R.id.ToolbarMain);
logger.info("inside Util class, setupUiViews, before findViewById(lvMain)");
listView = findViewById(R.id.lvMain);
}
public void initToolbar(){
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(" App");
}
public void setupListView(){
String[] title = getResources().getStringArray(R.array.Main);
String[] description=getResources().getStringArray(R.array.Description);
SimpleAdapter simpleAdapter = new SimpleAdapter(this, title, description);
listView.setAdapter(simpleAdapter);
}
}
The code crushes before entering into setupUIViews() method from Util class.
Can you please, please take a look and tell me how can I resolve the issue ?
I debugged, but did not understand where the problem comes from.
Also, looked to other similar questions, but each exemple is specific, so I cannot extrapolate to my situation.
Thank you very much for your time and help!
you call util. setupUIViews(), in the inner method,it called findViewById(R.id.ToolbarMain). this method is belonged to Activity, we look at the source code
return getWindow().findViewById(id);
//in the window, (PhoneWindow)
#Nullable
public <T extends View> T findViewById(#IdRes int id) {
return getDecorView().findViewById(id);
}
// the DecorView is the basic view, it set when you call setContentView
public void setContentView(#LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
//PhoneWindow setContentView
#Override
public void setContentView(View view) {
setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
#Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
// decor, when theme attributes and the like are crystalized. Do not
// check the feature
// before this happens.
if (mContentParent == null) {
installDecor(); // this method init DecorView
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
...
}
but you do not call util setContenView to set its view. so it reports the error.
and your code writes way is wrong. we set view in activity or fragment own class;
we cannot use another activity to set other activities.
In android, every activity has its own window. try to move the Utils method into MainActiviy.
The util class is extending from AppCompatActivity but is not properly initialized. You can't use AppCompatActivity in that way. Instead you need to do something like:
class MainActivity : AppCompatActivity() {
private val tag = "MainActivity"
lateinit var util: Util
override fun onCreate(savedInstanceState: Bundle?) {
util = Util(this)
}
}
And the Util (in kotlin) class:
class Util(private delegate:MainActivity) {
public void setupUIViews(){
toolbar = delegate.findViewById(R.id.ToolbarMain);
listView = delegate.findViewById(R.id.lvMain);
}
}
Also, I think that using this pattern and move all view-related stuff to a "Util" class is not the best. You will have better results using other patterns like MVP or MVVM.

Android Studio Bluetooth :- attempt to invoke a virtual method on a null object reference

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();
}

Adding a class to the manifest in Android

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.

Fatal exception while starting activity using intent (null pointer exception)

The following piece of code is throwing a null pointer exception in my application.Im trying to invoke an activity through an intent, (some background info on this is that the activity being opened is triggered through the click of a button, thus I have called the startActivity() function in the button's onclickListener itself.
Here's the code:
public class CategoryButtonOnClickListener extends Activity implements View.OnClickListener {
private final int position;
public CategoriesPage categoriesPage;
Context context;
public CategoryButtonOnClickListener(int position, Context contextPassed) {
this.position = position;
this.context = contextPassed;
categoriesPage = new CategoriesPage();
}
public void onClick(View v) {
callCategoryList(this.position);
}
public void callCategoryList(int position) {
String[] categories = categoriesPage.getCategories();
Intent categoriesList = new Intent(this.context,BooksWithCategories.class);
//I tried commenting this code to fix it as seen from another post, didnt work
//categoriesList.putExtra("Category:",categories[position]);
startActivity(categoriesList);
//Toast.makeText(context,categories[position],Toast.LENGTH_LONG).show();
}
}
The error thrown is as follows:
1-17 23:27:15.076 2614-2614/com.dogra.booker E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.dogra.booker, PID: 2614
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:3736)
at android.app.Activity.startActivityForResult(Activity.java:3697)
at android.app.Activity.startActivity(Activity.java:4007)
at android.app.Activity.startActivity(Activity.java:3975)
at com.dogra.booker.UI.Model.CategoryButtonOnClickListener.callCategoryList(CategoryButtonOnClickListener.java:36)
at com.dogra.booker.UI.Model.CategoryButtonOnClickListener.onClick(CategoryButtonOnClickListener.java:29)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Any suggestions on what could be the problem are appreciated.
Place this method in your code :
Activity getAct() {
Context context = getContext();
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return (Activity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
return null;
}
and then use it for starting the activity:
Intent categoriesList = new Intent(getAct(),BooksWithCategories.class);
can try this
Intent categoriesList = new Intent(CategoryButtonOnClickListener.this,BooksWithCategories.class);

String in the MainActivity.java file makes my Android app crash

I added a String to the MainActivity.java file and now my app crashes as soon as I launch it (at the moment the debugger reaches the line of code with the String).
This is the line of code that creates the problem :
CharSequence Total = "Total:"; // getString(R.string.total);
it also creates the problem if I use String instead of CharSequence.
When I delete that line the app works perfectly.
This is the error I get in the Gradle console :
Note : /Users/ishayfrenkel1/AndroidStudioProjects/JustJava/app/src/main/java/com/howtoevery/justjava/MainActivity.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
What does it mean that the app uses or overrides a deprecated API?
And how can I Recompile with -Xlint:deprecation in Android Studio? What does it even mean?
The MainActivity.java code:
package com.howtoevery.justjava;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.text.NumberFormat;
/**
* This app displays an order form to order coffee.
*/
public class MainActivity extends ActionBarActivity {
CharSequence totalString = "Total:"; // getString(R.string.total);
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
CharSequence toastText;
// String total = getString(R.string.total);
int num = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method displays the given price on the screen.
*/
private void displayPrice(int number, CharSequence message) { // Used to be , String message
TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
priceTextView.setText(message + " " + NumberFormat.getCurrencyInstance().format(number)); // was message before Number Format
}
public void addOne(View view) {
num++;
display(num);
displayPrice(num*5, totalString); //used to have total
}
public void removeOne(View view) {
if (num > 0) {
num--;
display(num);
displayPrice(num * 5, totalString); //used to have total
}
else {
Context context = getApplicationContext();
toastText = getString(R.string.negativeCups);
Toast toast = Toast.makeText(context, toastText, duration);
toast.show();
}
}
public void reset(View view) {
if (num > 0) {
num = 0;
display(num);
displayPrice(num, totalString); //used to have total
}
else {
toastText = getString(R.string.resetted);
Toast toast = Toast.makeText(context, toastText, duration);
toast.show();
}
}
public void submitOrder(View view) {
displayToast(num);
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + number);
}
private void displayToast(int number) {
Context context = getApplicationContext();
if (number > 0) {
toastText = getString(R.string.ordering) + num + getString(R.string.ordering_cups_price) + NumberFormat.getCurrencyInstance().format(num*5);
}
else
toastText = getString(R.string.empty_order);
Toast toast = Toast.makeText(context, toastText, duration);
toast.show();
}
}
This is what I get from the logcat:
06-07 13:39:06.275 22308-22308/com.howtoevery.justjava I/art﹕ Late-enabling -Xcheck:jni
06-07 13:39:06.391 22308-22308/com.howtoevery.justjava D/AndroidRuntime﹕ Shutting down VM
06-07 13:39:06.392 22308-22308/com.howtoevery.justjava E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.howtoevery.justjava, PID: 22308
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.howtoevery.justjava/com.howtoevery.justjava.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2216)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2367)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5274)
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:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:105)
at com.howtoevery.justjava.MainActivity.<init>(MainActivity.java:16)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1572)
at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2206)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2367)
            at android.app.ActivityThread.access$800(ActivityThread.java:148)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5274)
            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:909)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
06-07 13:39:08.374 22308-22318/com.howtoevery.justjava W/art﹕ Suspending all threads took: 8.600ms
You have a problem with your context. getApplicationContext() should be moved inside the onCreate() method. Do this
public class MainActivity extends ActionBarActivity {
CharSequence totalString = "Total:"; // getString(R.string.total);
Context context;
int duration = Toast.LENGTH_SHORT;
CharSequence toastText;
// String total = getString(R.string.total);
int num = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
}
...
Class members initialization that takes place outside constructors/instance methods cannot use non static methods that require functional object instances, because at that point your object instance is not yet fully created. You have to move such initializations inside constructor, or instance method that you will either call from constructor or from your object reference.
You have to move initialization calls to getString(R.string.total), and getApplicationContext() to OnCreate method.
public class MainActivity extends ActionBarActivity {
String totalString;
Context context;
....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
totalString = getString(R.string.total);
context = getApplicationContext();
}
In your code, you actually don't have to grab application context at all, because you can use activity context to show your toast messages. Just refer to current activity reference with this
Toast toast = Toast.makeText(this, toastText, duration);

Categories

Resources