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.
Related
Having problems debugging an android networking application. I think I might have some problems with the import but I don't know which. If you can see the problem, please do let me know. Thank you.
MainActivity.java
package com.example.networkingfinals;
import androidx.appcompat.app.AppCompatActivity;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Loader;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<BookInfo>> {
private String url;
private String input;
private BookAdapter bookAdapter;
private int LOADER_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.submit);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.input);
input = String.valueOf(editText.getText());
url = "https://www.googleapis.com/books/v1/volumes?q="+input+"&maxResults=3";
}
});
LoaderManager loaderManager = getLoaderManager();
getLoaderManager().initLoader(LOADER_ID, null, this);//Set loader manager to call asyncloader in onCreateLoader
//TODO: Implement AsyncTaskLoader and LoadManager fetching network data on parallel thread
}
#Override
public Loader<List<BookInfo>> onCreateLoader(int id, Bundle args) {
Loader<List<BookInfo>> books = new BookAsync(this, url);
return books;
//Call oncreate Loader , fetching List of Book Info
}
#Override
public void onLoadFinished(Loader<List<BookInfo>> loader, List<BookInfo> data) {
Log.v("onLoadFinished", "Return " + data);
bookAdapter.addAll(data);
}
#Override
public void onLoaderReset(Loader loader) {
bookAdapter.clear();
}
Logcat
2021-01-10 18:44:55.950 13590-13590/com.example.networkingfinals V/onCreateLoader: Return BookAsync{814c192 id=0}
2021-01-10 18:44:56.045 13590-13590/com.example.networkingfinals V/onLoadFinished: Return null
2021-01-10 18:44:56.045 13590-13590/com.example.networkingfinals D/AndroidRuntime: Shutting down VM
2021-01-10 18:44:56.055 13590-13590/com.example.networkingfinals E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.networkingfinals, PID: 13590
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.networkingfinals.BookAdapter.addAll(java.util.Collection)' on a null object reference
at com.example.networkingfinals.MainActivity.onLoadFinished(MainActivity.java:61)
at com.example.networkingfinals.MainActivity.onLoadFinished(MainActivity.java:17)
at android.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:497)
at android.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:465)
at android.content.Loader.deliverResult(Loader.java:157)
at android.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:274)
at android.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:97)
at android.os.AsyncTask.finish(AsyncTask.java:755)
at android.os.AsyncTask.access$900(AsyncTask.java:192)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:772)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7458)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)
2021-01-10 18:44:56.138 13590-13590/com.example.networkingfinals I/Process: Sending signal. PID: 13590 SIG:
I think I don't understand how onCreateLoader() and onLoadFinished() works. I tried and find that onCreateLoader return non-null data but in onLoadFinished() the data passed into it was null.
This error is because your adapter is not initialized yet you need to initialize it in onCreate
this.bookAdapter = new BookAdapter();
the error message says
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.networkingfinals.BookAdapter.addAll(java.util.Collection)' on a null object reference
that means is your adapter is null and you call addAll from the null object reference
My app keeps crashing since I started using a TextWatcher...
As you can see below i made a TextWatcher to 3 EditText fields...
And i made a button which listens to the 3 EditText..
If they are empty the button become disabled.
When the fields are filled the button should become enabled..
package com.example.magazijnapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.MenuPopupWindow;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.sql.Array;
public class MainActivity extends AppCompatActivity {
Spinner spinnermagazijn;
Button knop;
private EditText EditTextregisternummerbalk;
private EditText EditTextticketnummerbalk;
private EditText EditTextartikelnummerbalk;
private Button knopconfirm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditTextregisternummerbalk = findViewById(R.id.registernummerbalk);
EditTextticketnummerbalk = findViewById(R.id.ticketnummerbalk);
EditTextartikelnummerbalk = findViewById(R.id.artikelnummerbalk);
knopconfirm = findViewById(R.id.knop);
EditTextregisternummerbalk.addTextChangedListener(invulTextWatcher);
EditTextticketnummerbalk.addTextChangedListener(invulTextWatcher);
EditTextartikelnummerbalk.addTextChangedListener(invulTextWatcher);
}
private TextWatcher invulTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String registernummerinput = EditTextregisternummerbalk.getText().toString().trim();
String ticketnummerinput = EditTextticketnummerbalk.getText().toString().trim();
String artikelnummerinput = EditTextartikelnummerbalk.getText().toString().trim();
knopconfirm.setEnabled(!registernummerinput.isEmpty() && !ticketnummerinput.isEmpty() &&! artikelnummerinput.isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
}
};
{
spinnermagazijn = findViewById(R.id.spinnermagazijn);
knop = findViewById(R.id.knop);
populatespinnermagazijn();
// Dit is het stukje voor de Knop afboeken waarmee je een melding genereerd, String aanpassen voor ander resultaat.
knop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, (R.string.succes), Toast.LENGTH_SHORT) .show();
}
});
}
// Dit gedeelte is voor de spinner.
private void populatespinnermagazijn() {
ArrayAdapter<String> magazijnenAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.steunpunten));
magazijnenAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnermagazijn.setAdapter(magazijnenAdapter);
}
}
And this is my logcat...
03-19 21:04:06.293 21151-21151/? E/libprocessgroup: failed to make and chown /acct/uid_10060: Read-only file system
03-19 21:04:06.293 21151-21151/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
03-19 21:04:06.293 21151-21151/? I/art: Not late-enabling -Xcheck:jni (already on)
03-19 21:04:06.313 21151-21161/? I/art: Debugger is no longer active
03-19 21:04:06.351 21151-21151/? D/AndroidRuntime: Shutting down VM
03-19 21:04:06.354 21151-21151/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.magazijnapp, PID: 21151
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.magazijnapp/com.example.magazijnapp.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:2236)
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 com.example.magazijnapp.MainActivity.<init>(MainActivity.java:73)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
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)
03-19 21:04:07.996 21151-21151/? I/Process: Sending signal. PID: 21151 SIG: 9
There are two findViewById(R.id.knop);
remove this line:
knop = findViewById(R.id.knop);
and change :
knopconfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, (R.string.succes), Toast.LENGTH_SHORT) .show();
}
});
You are saying your app is crashing since you started using TextWatcher. So why don't you stop using it?
you can achieve the same thing without using TextWatcher by doing this.
knop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String registernummerinput = EditTextregisternummerbalk.getText().toString().trim();
String ticketnummerinput = EditTextticketnummerbalk.getText().toString().trim();
String artikelnummerinput = EditTextartikelnummerbalk.getText().toString().trim();
if((!registernummerinput.isEmpty() && !ticketnummerinput.isEmpty() &&! artikelnummerinput.isEmpty())) {
Toast.makeText(MainActivity.this, (R.string.succes), Toast.LENGTH_SHORT) .show();
}
}
});
you will not need any TextWathcer just modify the listner
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.
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);
This is the error message which shows up when I run the apk on my virtual device.
05-03 13:00:03.652 2354-2354/de.hochrad.hochradapp I/art﹕ Not late-enabling -Xcheck:jni (already on)
05-03 13:00:05.966 2354-2354/de.hochrad.hochradapp D/AndroidRuntime﹕ Shutting down VM
05-03 13:00:05.970 2354-2354/de.hochrad.hochradapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.hochrad.hochradapp, PID: 2354
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.hochrad.hochradapp/de.hochrad.hochradapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:250)
at de.hochrad.hochradapp.MainActivity.onCreate(MainActivity.java:26)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
05-03 13:00:08.238 2354-2354/de.hochrad.hochradapp I/Process﹕ Sending signal. PID: 2354 SIG: 9
Somehow it cannot find the required Resources.
I hope you can help me!!!
Thx for all answers!!!
package de.hochrad.hochradapp;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
ArrayAdapter<String> klassen_adapter;
Vertretungsplan vertretungsplan;
Spinner klassen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(null, "Laden...", Toast.LENGTH_SHORT).show();
klassen_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
klassen = (Spinner) findViewById(R.id.klassenspinner);
Thread downloadThread = new Thread() {
public void run() {
vertretungsplan = new Vertretungsplan("1");
runOnUiThread(new Runnable() {
#Override
public void run() {
if (vertretungsplan.Ex != null) {
klassen_adapter.add("Fehler!");
} else {
klassen_adapter.add("Wähle deine Klasse!");
for (Klassenvertretung s : vertretungsplan.Klassen) {
klassen_adapter.add(s.Bezeichnung);
}
}
}
});
}
};
downloadThread.start();
klassen.setAdapter(klassen_adapter);
klassen.setSelection(0);
klassen.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
package de.hochrad.hochradapp;
import java.util.ArrayList;
import java.util.List;
public class Klassenvertretung {
public String Bezeichnung;
public List<Vertretung> Vertretungen = new ArrayList<Vertretung>();
public void Hinzufügen(Vertretung neuesElement) {
Vertretungen.add(neuesElement);
}
}
package de.hochrad.hochradapp;
public class Vertretung {
public String Klasse;
public String Stunde;
public String Art;
public String Fach;
public String Raum;
public String stattFach;
public String stattRaum;
public String Informationen;
}
package de.hochrad.hochradapp;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Vertretungsplan {
public Vertretungsplan(String woche) {
Woche = woche;
Einlesen(woche);
}
public String Woche;
public Exception Ex;
public List<Klassenvertretung> Klassen = new ArrayList<Klassenvertretung>();
private void Hinzufügen(Klassenvertretung neuesElement) {
Klassen.add(neuesElement);
}
private void Einlesen(String woche) {
try {
for (int webseite = 1; webseite < 10000; webseite++) {
Klassenvertretung klassenvertretung = new Klassenvertretung();
String teilseite = "0000";
if (webseite < 10)
teilseite = teilseite + "0";
teilseite = teilseite + webseite;
Connection connection = Jsoup
.connect("www.gymnasium-hochrad.de/Vertretungsplan/Vertretungsplan_Internet/"
+ woche + "/w/w" + teilseite + ".htm");
Document doc = connection.get();
Element h2 = doc.select("h2").get(0);
klassenvertretung.Bezeichnung = h2.text();
Element table = doc.select("table").get(1);
Element[] elemente = table.select("tr").toArray(new Element[0]);
for (int i = 1; i < elemente.length; i++) {
Element[] tds = elemente[i].select("td").toArray(
new Element[0]);
Vertretung vertretung = new Vertretung();
vertretung.Klasse = tds[0].text();
vertretung.Stunde = tds[1].text();
vertretung.Art = tds[2].text();
vertretung.Fach = tds[3].text();
vertretung.Raum = tds[4].text();
vertretung.stattFach = tds[5].text();
vertretung.stattRaum = tds[6].text();
vertretung.Informationen = tds[7].text();
klassenvertretung.Hinzufügen(vertretung);
}
Hinzufügen(klassenvertretung);
}
} catch (IOException io) {
if (Klassen.size() == 0) {
Ex = io;
}
} finally {
}
}
}
okay here is my code. I am form germany and so lots of Names are german (i hope thats not a problem.
Maybe it helps.
I guess the error must be in the main activity in one of the toasts. But dont hesitate to look at the other lines.
A/c to logcat error your are getting null reference error. try to update this line
Toast.makeText(parent.getContext(),
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
with the following code
Toast.makeText(MainActivity.this,
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
You have not initialised your adapter namely "klassen_adapter" in your main activity. It's null and invoking any method on it will be null pointer exception