This question already has answers here:
How exactly does the android:onClick XML attribute differ from setOnClickListener?
(17 answers)
Closed 6 years ago.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.juliandrach.eatfit, PID: 2223
java.lang.IllegalStateException: Could not find method aldirindersalami(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Basically the error occurs when I am updating a variable by pressing a button and then trying to display the value of the variable with a toast in the same task.
public class Mahlzeiten extends AppCompatActivity {
public static int proteine = 0;
public static int carbs = 0;
public static int fette = 0;
public static int kcal = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mahlzeiten);
String text = "Hallo" + proteine + "danke";
Toast.makeText(Mahlzeiten.this, text, Toast.LENGTH_SHORT).show();
}
public void aldirindersalami (int proteine){
proteine++;
// String text1 = "Hallo" + proteine + "danke";
// Toast.makeText(Mahlzeiten.this, text1, Toast.LENGTH_SHORT).show();
}
}
You have an onClick listener set in the xml but you didn't implement the onClick method in the code. You need the following method
public void aldirindersalami(View v) {}
to handle the click on the button.
Related
The below code gives null pointer exception in android studio
please help me to solve that
02-10 22:42:11.702 30997-30997/? I/art: Late-enabling -Xcheck:jni
02-10 22:42:11.749 30997-30997/? D/TidaProvider: TidaProvider()
02-10 22:42:11.757 30997-30997/? W/ReflectionUtils: java.lang.NoSuchMethodException: android.os.MessageQueue#enableMonitor()#bestmatch
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:338)
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:375)
at miui.util.ReflectionUtils.callMethod(ReflectionUtils.java:800)
at miui.util.ReflectionUtils.tryCallMethod(ReflectionUtils.java:818)
at android.os.BaseLooper.enableMonitor(BaseLooper.java:47)
at android.os.Looper.prepareMainLooper(Looper.java:111)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
02-10 22:42:11.789 30997-30997/com.androidexample.courtcounter W/ResourceType: No package identifier when getting name for resource number 0x00000000
02-10 22:42:11.803 30997-30997/com.androidexample.courtcounter W/System: ClassLoader referenced unknown path: /data/app/com.androidexample.courtcounter-1/lib/arm64
02-10 22:42:11.826 30997-30997/com.androidexample.courtcounter D/AndroidRuntime: Shutting down VM
02-10 22:42:11.827 30997-30997/com.androidexample.courtcounter E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.androidexample.courtcounter, PID: 30997
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.androidexample.courtcounter/com.androidexample.courtcounter.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:2396)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2545)
at android.app.ActivityThread.access$1100(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5601)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
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:160)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:109)
at android.content.Context.obtainStyledAttributes(Context.java:517)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:839)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:806)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:630)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:223)
at com.androidexample.courtcounter.MainActivity.(MainActivity.java:19)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2386)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2545)
at android.app.ActivityThread.access$1100(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5601)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
public class MainActivity extends AppCompatActivity {
int team_a_Score=0;
int team_b_Score=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
final Button button1=(Button)findViewById(R.id.score2);
final Button button_teamB1=(Button)findViewById(R.id.TeamB_score1);
final Button buttonScore3A=(Button)findViewById(R.id.score3);
final Button buttonScore3B=(Button)findViewById(R.id.TeamB_score3);
final Button buttonScore_freeshotA=(Button)findViewById(R.id.freeshot);
final Button buttonScore_freeshotB=(Button)findViewById(R.id.TeamB_freeshot);
public void onClick(View v) {
if (v.equals(button1)) {
team_a_Score = team_a_Score + 1;
TextView text = (TextView) findViewById(R.id.score_team_a);
text.setText(team_a_Score);
} else if (v.equals(button_teamB1)) {
team_b_Score = team_b_Score + 1;
TextView text = (TextView) findViewById(R.id.score_teamB);
text.setText(team_b_Score);
} else if (v.equals(buttonScore3A)) {
team_a_Score = team_a_Score + 3;
TextView text = (TextView) findViewById(R.id.score_team_a);
text.setText(team_b_Score);
} else if (v.equals(buttonScore3B)) {
team_b_Score = team_b_Score + 3;
TextView text = (TextView) findViewById(R.id.score_teamB);
text.setText(team_b_Score);
} else if (v.equals(buttonScore_freeshotA)) {
team_a_Score = team_a_Score + 4;
TextView text = (TextView) findViewById(R.id.score_team_a);
text.setText(team_a_Score);
} else if (v.equals(buttonScore_freeshotB)) {
team_b_Score = team_b_Score + 4;
TextView text = (TextView) findViewById(R.id.score_teamB);
text.setText(team_b_Score);
}
}
}
List item
It looks like this code:
final Button button1=(Button)findViewById(R.id.score2);
final Button button_teamB1=(Button)findViewById(R.id.TeamB_score1);
final Button buttonScore3A=(Button)findViewById(R.id.score3);
final Button buttonScore3B=(Button)findViewById(R.id.TeamB_score3);
final Button buttonScore_freeshotA=(Button)findViewById(R.id.freeshot);
is member variable definitions outside of a method. That doesn't work on Android, because this code executes at object instantiation time and you cannot call findViewById() before setContentView() is called. You are calling setContentView() in onCreate() which is correct, but onCreate() is called after the object is instantiated.
You need to split the member variable definitions from the initialization. To do that, declare the member variables without initialization outside of a method:
final Button button1;
final Button button_teamB1;
final Button buttonScore3A;
final Button buttonScore3B;
final Button buttonScore_freeshotA;
Then, in onCreate(), after calling setContentView(), you can initialize the member variables like this:
button1=(Button)findViewById(R.id.score2);
button_teamB1=(Button)findViewById(R.id.TeamB_score1);
buttonScore3A=(Button)findViewById(R.id.score3);
buttonScore3B=(Button)findViewById(R.id.TeamB_score3);
buttonScore_freeshotA=(Button)findViewById(R.id.freeshot);
Heyho.
Is it possible that I put all onClick() Methods in a single class to have a better Overview?
That's what I've tried:
public class ButtonHandler extends MainActivity
{
public ButtonHandler()
{
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void OnClick1(View v)
{
if (_inputTextView != null)
{
_inputTextView.append("1");
}
}
}
But this gives me the following Exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.fayt.taschenrechner, PID: 4009
java.lang.IllegalStateException: Could not find method OnClick1(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'btn_1'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
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: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)
Is that even possible or am I trying something impossible?
Greets
Your app crash is because you pass your view as parameter. Currently you are setting android:onClick which there is no parameter in android system which will cause IllegalStateException. Learn how to make onClick programatically then you could put all your event inside on class. You could simply create another java class inside your project for handle all the click event rather than extends a mainActivity .
This question already has answers here:
android.content.res.Resources$NotFoundException: String resource ID #0x0
(8 answers)
Closed 6 years ago.
I need a thread that waits some time then changes a text in a TextView.
My search found how to use runOnUiThread
I understood the first answer and tried to use it in my code but I get an error when calling setText in the thread.
Here is my code
(start is the onClick function of a button):
public class MainActivity extends AppCompatActivity {
public int i = 0;
private TextView mText;
private Thread thread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mText = (TextView)findViewById(R.id.text);
}
public void start (View v) {
runThread();
}
private void runThread() {
new Thread() {
public void run() {
while (true) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
i++;
mText.setText((i));
}
});
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
Here is my error
09-26 20:26:34.054 22254-22254/com.horizon.testtimerthread E/AndroidRuntime: FATAL EXCEPTION: main
android.content.res.Resources$NotFoundException: String resource ID #0x1
at android.content.res.Resources.getText(Resources.java:1058)
at android.support.v7.widget.ResourcesWrapper.getText(ResourcesWrapper.java:52)
at android.widget.TextView.setText(TextView.java:3866)
at com.horizon.testtimerthread.MainActivity$1$1.run(MainActivity.java:39)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:177)
at android.app.ActivityThread.main(ActivityThread.java:4947)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
Thank you in advance for your help.
mText.setText((i)) is the problem.
Android thinks that you are referencing a String ID and is crashing because it cannot find a String with an ID of 1. If you meant to set the text to "1", "2" ect... then write mText.setText((Integer.toString(i)))
Since i has type int, you are calling setText(int resourceId) variant of function, what is obvious not you want. setText(String.valueOf(i)) should work.
Building on a theme from yesterday...I'm getting an NPE accessing a method in a singleton Application class from within an AlertDialog.
Activity SavedMealsActivity sets OnLongClickListenerSavedMeals as the listener for a series of TextViews in a ScrollView. OnLongClickListenerSavedMeals is defined as a separate class.
OnLongClickListenerSavedMeals displays an AlertDialog which gives the option of going to a different Activity, but it first needs to fire the methods of an Application class which is defined as a singleton (MealTimerApplication). This is the first line of the onClick method (line 25 in the first code sample below), and it throws the NPE because the activity is null at the time.
I've tried passing in the activity from the calling Activity (SavedMealsActivity) but for some reason it's not working as I'd hoped. Any ideas?
OnLongClick listener class - OnLongClickListenerSavedMeals:
public class OnLongClickListenerSavedMeals implements OnLongClickListener {
Context context;
String id;
private Activity activity;
public OnLongClickListenerSavedMeals(Activity activity) {
this.activity = activity;
this.context = activity;
}
#Override
public boolean onLongClick(View view){
// TODO Auto-generated method stub
this.context = context;
id = view.getTag().toString();
final CharSequence[] items = { "Edit", "Delete" };
//Set activity to allow context to be used in the OnClickListener/onClick method below
this.activity = activity;
new AlertDialog.Builder(context).setTitle("Meal Item")
.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
//Set the global meal_id variable and invoke the MealActivity
((MealTimerApplication) activity.getApplication()).setMealId(Long.getLong(id));
Intent myIntent = new Intent(activity.getBaseContext(),MealActivity.class);
activity.startActivityForResult(myIntent, 0);
}
else if (item == 1) {
boolean deleteSuccessful = new TableControllerMeal(context).delete(id);
if (deleteSuccessful){
Toast.makeText(context, "Record was deleted.", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Unable to delete record.", Toast.LENGTH_SHORT).show();
}
((SavedMealsActivity) context).readRecords();
}
dialog.dismiss();
}
}).show();
return false;
}
Calling Activity - SavedMealsActivity:
public class SavedMealsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_meals);
//Read saved meal records from the database and display them
readRecords();
}
public void readRecords() {
LinearLayout linearLayoutRecords = (LinearLayout) findViewById(R.id.linearLayoutRecords);
linearLayoutRecords.removeAllViews();
List<meal> meal = new TableControllerMeal(this).read();
if (meal.size() > 0) {
for (meal obj : meal) {
long id = obj.id;
String MealDesc = obj.meal_desc;
int MealMinutes = obj.meal_ready_time;
String textViewContents = MealDesc + " - ready at "
+ Utilities.formatTime(MealMinutes);
TextView textViewItem = new TextView(this);
textViewItem.setPadding(0, 10, 0, 10);
textViewItem.setText(textViewContents);
textViewItem.setTag(Long.toString(id));
textViewItem.setOnLongClickListener(new OnLongClickListenerSavedMeals(this));
linearLayoutRecords.addView(textViewItem);
}
}
else {
TextView Item = new TextView(this);
Item.setPadding(8, 8, 8, 8);
Item.setText("No records yet.");
linearLayoutRecords.addView(Item);
}
}
Application class:
public class MealTimerApplication extends Application {
private static MealTimerApplication singleton;
private long mealId = 0;
// Returns the application instance
public static MealTimerApplication getInstance() {
return singleton;
}
public final void onCreate() {
super.onCreate();
singleton = this;
}
public void setMealId(long mealId) {
this.mealId = mealId;
}
public long getMealId() {
return this.mealId;
}
}
Logcat:
05-28 16:48:03.637: E/AndroidRuntime(4241): java.lang.NullPointerException
05-28 16:48:03.637: E/AndroidRuntime(4241): at com.ian.mealtimer.OnLongClickListenerSavedMeals$1.onClick(OnLongClickListenerSavedMeals.java:39)
05-28 16:48:03.637: E/AndroidRuntime(4241): at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:941)
05-28 16:48:03.637: E/AndroidRuntime(4241): at android.widget.AdapterView.performItemClick(AdapterView.java:299)
05-28 16:48:03.637: E/AndroidRuntime(4241): at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
05-28 16:48:03.637: E/AndroidRuntime(4241): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2904)
05-28 16:48:03.637: E/AndroidRuntime(4241): at android.widget.AbsListView$3.run(AbsListView.java:3638)
05-28 16:48:03.637: E/AndroidRuntime(4241): at android.os.Handler.handleCallback(Handler.java:733)
05-28 16:48:03.637: E/AndroidRuntime(4241): at android.os.Handler.dispatchMessage(Handler.java:95)
05-28 16:48:03.637: E/AndroidRuntime(4241): at android.os.Looper.loop(Looper.java:136)
05-28 16:48:03.637: E/AndroidRuntime(4241): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-28 16:48:03.637: E/AndroidRuntime(4241): at java.lang.reflect.Method.invokeNative(Native Method)
05-28 16:48:03.637: E/AndroidRuntime(4241): at java.lang.reflect.Method.invoke(Method.java:515)
05-28 16:48:03.637: E/AndroidRuntime(4241): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-28 16:48:03.637: E/AndroidRuntime(4241): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-28 16:48:03.637: E/AndroidRuntime(4241): at dalvik.system.NativeStart.main(Native Method)
You get NPE because of autoboxing. Long.getLong(String) is not what you actually you need, check its description:
Returns the Long value of the system property identified by string.
It definitely returns null in your case. Moreover it returns null reference to Long object, but your MealTimerApplication.setMealId expects argument with primitive type long. Here is the point where auto-boxing implicitly trying to cast your Long object returned by getLong method to the long primitive. But as value was null auto-boxing fails and you get NPE.
You should just use Long.valueOf(String) instead of Long.getLong(String).
I am very new to android. I have a counter on some SomeActivity, but when I get to the page corresponding to SomeActivity, my app crashes :
final TextView counter = (TextView) findViewById(R.id.laws_counter);
ImageView handDown = (ImageView) findViewById(R.id.handViewDown);
counter.setText("" + 0);
I want that on click of the handown, the counter is idented by -1. Here's
handDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(NewsActivity.this,
"The favorite list would appear on clicking this icon",
Toast.LENGTH_LONG).show();
setDown();
}
private void setDown() {
String count = counter.getText().toString();
int now_count = Integer.parseInt(count) +1;
counter.setText(String.valueOf(now_count));
}
});
Is this code correct ?
Update : here's the logcat
10-22 00:18:05.579: ERROR/AndroidRuntime(378): FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.donnfelker.android.bootstrap/com.donnfelker.android.bootstrap.ui.NewsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.donnfelker.android.bootstrap.ui.NewsActivity.onCreate(NewsActivity.java:41)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
... 11 more
There are many ways that you can implement that functionality but think this would be an easy solution.
Make a helper method:
public class PreferencesData {
public static void saveInt(Context context, String key, int value) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
sharedPrefs.edit().putInt(key, value).commit();
}
public static int getInt(Context context, String key, int defaultValue) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPrefs.getInt(key, defaultValue);
}
}
Then simply call the putInt method to save the counter in any Activity and getInt to get it again in any other Activity. As long as you use the same key both places.