execute method for android:onClick - java

I faced this errors when i click the button to display the ProgressDialog
03-08 14:29:00.169 8564-8564/com.mohammedmoaayed.test2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mohammedmoaayed.test2, PID: 8564
Theme: themes:{}
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21158)
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:5471)
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.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5204) 
at android.view.View$PerformClick.run(View.java:21158) 
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:5471) 
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 'void android.app.ProgressDialog.setTitle(java.lang.CharSequence)' on a null object reference
at com.mohammedmoaayed.test2.MainActivity.buclick(MainActivity.java:26)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5204) 
at android.view.View$PerformClick.run(View.java:21158) 
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:5471) 
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) 
and this is my java code
package com.mohammedmoaayed.test2;
import android.app.Activity;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
Activity myac;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myac=this;
}
mythread t1;
ProgressDialog bardown;
public void buclick(View view) {
bardown.setTitle("Downloaing ");
bardown.setMessage("Download is >>>>");
bardown.setProgressStyle(bardown.STYLE_HORIZONTAL);
bardown.setProgress(0);
bardown.setMax(20);
bardown.show();
t1 = new mythread();
t1.start();
}
class mythread extends Thread {
public void run (){
while (bardown.getProgress()<20) {
myac.runOnUiThread(new Runnable() {
#Override
public void run() {
bardown.incrementProgressBy(1);
}
});
try {
Thread.sleep(1000);
} catch (Exception ex) {}
}
myac.runOnUiThread(new Runnable() {
#Override
public void run() {
bardown.dismiss();
}
});
}
}
}
xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mohammedmoaayed.test2.MainActivity">
<Button
android:id="#+id/button2"
android:layout_width="395dp"
android:layout_height="587dp"
android:onClick="buclick"
android:text="Button"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />

You haven't inialiase your ProgressDialog so Initialize your ProgressDialog "bardown"
Initialize in Activity
bardown = new ProgressDialog(this);// write this line
Initialize in Fragment
bardown = new ProgressDialog(getActivity());// write this line
for e.g.
public void buclick(View view) {
bardown = new ProgressDialog(this);// write this line
bardown.setTitle("Downloaing ");
bardown.setMessage("Download is >>>>");
bardown.setProgressStyle(bardown.STYLE_HORIZONTAL);
bardown.setProgress(0);
bardown.setMax(20);
bardown.show();
t1 = new mythread();
t1.start();
}

you are calling setTitle() on null object.you have to instantiate it first;
bardown = (ProgressBar)findViewById(R.id.bardown);
or if you creating it dynamically use this
bardown - new ProgressBar(this);

You haven't initialized you ProgressDialog. Initialize it before using it. Add below line before calling the setTitle method.
bardown = new ProgressDialog(MainActivity.this);

use this
initialize dialog instant
ProgressDialog dialog = new ProgressDialog(Activity_Map_Advance_Tracking.this);dialog.setMessage("Loading....");
dialog.show();

Related

NullPointerException at onClick method

I am making an app on Android Studio and I ran into the NullPointerException in my onClick method. How do I fix it?
The debugger of my app gives me this:
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:6256) 
at android.view.View$PerformClick.run(View.java:24701) 
at android.os.Handler.handleCallback(Handler.java:789) 
at android.os.Handler.dispatchMessage(Handler.java:98) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageDrawable(android.graphics.drawable.Drawable)' on a null object reference
at com.example.venttome.ventingPage.onClick(ventingPage.java:66)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409) 
at android.view.View.performClick(View.java:6256) 
at android.view.View$PerformClick.run(View.java:24701) 
at android.os.Handler.handleCallback(Handler.java:789) 
at android.os.Handler.dispatchMessage(Handler.java:98) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
The code (the onClick() method) that is wrong:
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.record_btn:
if (isRecording){
//stop recording
recordButton.setImageDrawable(getResources().getDrawable(R.drawable.record_btn_stopped, null));
isRecording = false;
} else {
//start recording
recordButton.setImageDrawable(getResources().getDrawable(R.drawable.record_btn_recording, null));
isRecording = true;
}
break;
}
}
And this is my XML file for that class, and it is a constraint layout. This is what I use for my onClick method and I don't know what's wrong with it:
<ImageView
android:id="#+id/record_btn"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_marginStart="40dp"
android:layout_marginLeft="40dp"
android:layout_marginBottom="28dp"
android:background="#android:color/white"
android:clickable="true"
android:cropToPadding="true"
android:onClick="onClick"
android:src="#drawable/record_btn_stopped"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toLeftOf="#id/final_button"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/inputFeelings"
app:layout_constraintVertical_bias="1.0"
android:focusable="true"
tools:ignore="ContentDescription" />
you are not initializing the button in your method.Please first do this in your onCreate() method or if you are using fragment then in onCreateView():
ImageView record_btn= findViewById(R.id.record_btn);
Please initialize the view inside onCreate()
Here is the working code snippet
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
ImageView recordButton;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recordButton = findViewById(R.id.record_btn);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.record_btn:
Toast.makeText(this, "Called", Toast.LENGTH_SHORT).show();
recordButton.setImageResource(R.drawable.ic_launcher_foreground);
break;
}
}}

Getting "on a null object reference" [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
So i'm getting " on a null object reference" on my l1 and have no idea how to fix it after googling. I've tried multiple coding discords but they say it's because of the depreciated code but when I googled it shows that the depreciated code still works and the youtube tutorial I was following for it worked fine .
MainActivity -
package com.getcontacts;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends AppCompatActivity {
ListView l1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l1 = findViewById(R.id.listView);
}
public void get(View v) {
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
startManagingCursor(cursor);
String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone._ID};
int[] to = {android.R.id.text1,android.R.id.text2};
SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,cursor,from,to,1);
l1.setAdapter(simpleCursorAdapter);
l1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
}
and this is the error -
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.getcontacts, PID: 599
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:5205)
at android.view.View$PerformClick.run(View.java:21164)
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:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:5205) 
at android.view.View$PerformClick.run(View.java:21164) 
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:730) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.getcontacts.MainActivity.get(MainActivity.java:42)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
at android.view.View.performClick(View.java:5205) 
at android.view.View$PerformClick.run(View.java:21164) 
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:730) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620) 
apparently this : findViewById(R.id.listView); returns null please double check your tags and wether this element actually exists at the time of the call
Check the l1 you are trying to reference in your layout file to ensure you provided the id and spelled it exactly as you are calling it in the Java.

Get String[] from the other class

This is my main class:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Context con;
protected void onClickCityBreak(View v) {
String [] arrayCityBreak = con.getResources().getStringArray(R.array.citybreak);
Intent myintent = new Intent(MainActivity.this, ActivityTo.class);
myintent.putExtra("PLACES",arrayCityBreak);
startActivity(myintent);
}
}
And this is the class i want to send myintent array to:
public class ActivityTo extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String[] arrayCityBreak = getIntent().getStringArrayExtra("PLACES");
ArrayAdapter<String> adapterCityBreak = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayCityBreak);
ListView myview = getListView();
myview.setAdapter(adapterCityBreak);
}
}
My AndroidManifest.xml file:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ActivityTo">
</activity>
I can't find the problem in this. My application shuts down when i click the button to get to the new intent. It is because of the String[] i try to send, but I don't see why is won't work.
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ivarrreyna.assignment, PID: 2626
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
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)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
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) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at com.ivarrreyna.assignment.MainActivity.onClickCityBreak(MainActivity.java:24)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
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) 
Application terminated.
There is no need to pass array to , since ActivityTo is also an activity so can fetch the resources array here too
public class ActivityTo extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String [] arrayCityBreak = getResources().getStringArray(R.array.citybreak);
ArrayAdapter<String> adapterCityBreak = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayCityBreak);
ListView myview = getListView();
myview.setAdapter(adapterCityBreak);
}
}
To remove current error,
either do this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
con=this;
}
or
use this in MainActivity because con is not initialized
String [] arrayCityBreak = getResources().getStringArray(R.array.citybreak);
instead of
String [] arrayCityBreak = con.getResources().getStringArray(R.array.citybreak);
My application shuts down when i click the button to get to the new intent. It is because of the String[] i try to send, but I don't see why is won't work.
It is caused by this con, because the context is null:
Context con;
Use this like:
String [] arrayCityBreak = this.getResources().getStringArray(R.array.citybreak);
or
String [] arrayCityBreak = getResources().getStringArray(R.array.citybreak);

Android findViewById() returning null for custom view

So I've checked all of the other threads on this topic repeatedly but none have yielded the solution. Here's the code:
The XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.turingtechnologies.materialscrollbar.DragScrollBar
android:layout_width="wrap_content"
android:id="#+id/dragScrollBar"
android:layout_height="match_parent"/>
</RelativeLayout>
The Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Stuff
recyclerView = (RecylerView)findViewById(R.id.recyclerView); //I've verified that this works properly.
DragScrollBar dragScrollBar = (DragScrollBar)findViewById(R.id.dragScrollBar);
if (dragScrollBar == null) { Log.d("d", "fail"); }
dragScrollBar.bindRecyclerView(recyclerView);
}
DragScrollBar.java
public class DragScrollBar extends MaterialScrollBar<DragScrollBar>{
public DragScrollBar(Context context, AttributeSet attrs){
super(context, attrs);
}
}
MaterialScrollBar.java
abstract class MaterialScrollBar<T> extends RelativeLayout {
MaterialScrollBar(Context context, AttributeSet attrs){
super(context, attrs);
initialise(context);
}
//Stuff
}
It draws correctly on the preview but returns a nullPointerException when dragScrollBar is used and 'fail' is printed to the console.
I've omitted the other normal constructors but when included they don't make a difference.
EDIT: Here's the stack trace
fail
Shutting down VM
FATAL EXCEPTION: main
Process: com.turingtechnologies.materialscrollbardemo, PID: 31890 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.turingtechnologies.materialscrollbardemo/com.turingtechnologies.materialscrollbardemo.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object com.turingtechnologies.materialscrollbar.DragScrollBar.bindRecyclerView(android.support.v7.widget.RecyclerView)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object com.turingtechnologies.materialscrollbar.DragScrollBar.bindRecyclerView(android.support.v7.widget.RecyclerView)' on a null object reference
at com.turingtechnologies.materialscrollbardemo.MainActivity.onCreate(MainActivity.java:26)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 
I had run setID() inside of initalise as part of an earlier scheme and hadn't thought to remove it during refactoring.

Android studio crossfade drawables crashes app

I am trying to make basic app that crossfades one image for another and then back again.
The app however keeps crashing when I click the first image.
The crossfade method fade works on it's own. It has just begun crashing since I added the second method to transition the images back.
I see the InvocationTargetException and the NullPointerException but I don't understand how/why this is happening.
Also the onClick within the content setup is set to the correct methods.
package com.example.richardcurteis.layoutdemo;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView obama;
ImageView will;
public void fade(View view) {
obama = (ImageView) findViewById(R.id.obama);
will = (ImageView) findViewById(R.id.will);
obama.animate().alpha(0f).setDuration(2000);
will.animate().alpha(1f).setDuration(2000);
}
public void fadeBack(View view) {
will.animate().alpha(1f).setDuration(2000);
obama.animate().alpha(0f).setDuration(2000);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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);
}
}
Activity Main xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.richardcurteis.layoutdemo.MainActivity"
tools:showIn="#layout/activity_main"
android:clickable="false">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/obama"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:src="#drawable/obama"
android:onClick="fade" />
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/will"
android:layout_alignTop="#+id/obama"
android:layout_alignParentStart="true"
android:src="#drawable/will"
android:alpha="0"
android:onClick="fadeBack" />
</RelativeLayout>
Errors:
12-29 17:17:32.003 3368-3368/com.example.richardcurteis.layoutdemo E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.richardcurteis.layoutdemo, PID: 3368
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:275)
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)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270)
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) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.ViewPropertyAnimator android.widget.ImageView.animate()' on a null object reference
at com.example.richardcurteis.layoutdemo.MainActivity.fadeBack(MainActivity.java:29)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270) 
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) 
You are initializing views obama and will only in fade(). If fadeBack() is called before fade() values of obama and will are both null. That's why you are getting a null pointer exception.
Move this code from fade() to onCreate(),
obama = (ImageView) findViewById(R.id.obama);
will = (ImageView) findViewById(R.id.will);
So that it will get initiated at the time of view creation itself.
MainActivity should look like this :
public class MainActivity extends AppCompatActivity {
ImageView obama;
ImageView will;
public void fade(View view) {
obama.animate().alpha(0f).setDuration(2000);
will.animate().alpha(1f).setDuration(2000);
}
public void fadeBack(View view) {
will.animate().alpha(1f).setDuration(2000);
obama.animate().alpha(0f).setDuration(2000);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
obama = (ImageView) findViewById(R.id.obama);
will = (ImageView) findViewById(R.id.will);
......
}
......
}

Categories