Android java.lang.NullPointerException error with BroadcastReceiver - java

Everytime the application gets to my second activity it crashes, giving the error.
My activity:
public class SecondActivity extends AppCompatActivity {
EditText barcodeText = findViewById(R.id.barcodeText);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
IntentFilter filter = new IntentFilter();
filter.addCategory(Intent.CATEGORY_DEFAULT);
filter.addAction(getResources().getString(R.string.activity_intent_filter_action));
registerReceiver(myBroadcastReceiver, filter);
}
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle b = intent.getExtras();
if (action.equals(getResources().getString(R.string.activity_intent_filter_action))) {
try {
displayScanResult(intent);
} catch (Exception e) {
}
}
}
};
private void displayScanResult(Intent initiatingIntent)
{
String decodedSource = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_source));
String decodedData = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_data));
String decodedLabelType = initiatingIntent.getStringExtra(getResources().getString(R.string.datawedge_intent_key_label_type));
barcodeText.setText(decodedData);
}
}
Logcat:
07-01 12:37:03.373 349-349/com.example.provatimer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.provatimer, PID: 349
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.provatimer/com.example.provatimer.SecondActivity}: 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:5256)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
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:438)
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.provatimer.SecondActivity.<init>(SecondActivity.java:14)
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:5256) 
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:904) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
I think it may have something to do with the context in the BroadcastReceiver, but I tried to declare it in the onCreate method but nothing changed.
Maybe I don't initialize correctly the intent in which the data should be stored, if so, how can I do it correctly?
All the Strings should be correct int the string.xml file, if the error may come from that I'll write them.

I think the error is happening here:
EditText barcodeText = findViewById(R.id.barcodeText);
You are invoking findViewById() directly in the class member declaration.
You have invoke findViewById() after setContentView()
EditText barcodeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
barcodeText = findViewById(R.id.barcodeText);
}

Related

Hi! I am new to android app development. I tried to create a simple counter but after build getting error "Unable to instantiate activity"

public abstract class MainActivity extends AppCompatActivity {
Button decrement;
Button increment;
TextView counter_view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Log.i("tag", "onCreate: Created Successfully");
increment=findViewById(R.id.inc_btn);
decrement=findViewById(R.id.dec_btn);
counter_view=findViewById(R.id.counter);
increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String cnt_text=counter_view.getText().toString();
int cnt_no= Integer.parseInt(cnt_text);
cnt_no=cnt_no+1;
counter_view.setText(cnt_no+"");
}
});
decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String cnt_text=counter_view.getText().toString();
int cnt_no=Integer.parseInt(cnt_text);
cnt_no=cnt_no-1;
counter_view.setText(cnt_no+"");
}
});
}
Error:
2021-02-10 00:29:06.870 16714-16714/? E/Zygote: v2
2021-02-10 00:29:06.871 16714-16714/? E/Zygote: accessInfo : 0
2021-02-10 00:29:07.017 16714-16714/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.counter_app, PID: 16714
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.counter_app/com.example.counter_app.MainActivity}: java.lang.InstantiationException: java.lang.Class<com.example.counter_app.MainActivity> cannot be instantiated
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2849)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Caused by: java.lang.InstantiationException: java.lang.Class<com.example.counter_app.MainActivity> cannot be instantiated
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1086)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2839)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045) 
at android.app.ActivityThread.-wrap14(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6776) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408) 
I suppose this is your first screen/activity/class that is displayed on launch i.e it is your launcher activity. If yes,
the launcher activity cannot be abstract. Because when an app is launched from the home screen on an Android device, the Android OS creates an instance of the activity in the application you have declared to be the launcher activity. And abstract classes can not be instantiated, they can only be sub-classed.
Please remove the word abstract before your class name.
add to your manifest file this line
<activity android:name="your.package.name.MainActivity"/>

Initialize an interface in an Activity

How can I initialize an interface in the MainActivity?
I have tried it like the following, but it keeps giving error.
MainActivity:
public class MainActivity extends AppCompatActivity {
private static final Logger LOG = LoggerFactory.getLogger("MainActivity");
private ExpandableListView mExpandableListView;
private ExpandableListViewAdapter mExpandableListViewAdapter;
private List<String> mListDataGroup;
private HashMap<String, List<String>> mListDataChild;
PreselectionAplicationUseCases preselectionAplicationUseCases;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
initListeners();
initObjects();
initListData();
preselectionAplicationUseCases=(PreselectionAplicationUseCases) this;
}
Interface:
public interface PreselectionAplicationUseCases {
void setOnMsgPreselectionChanged(MSG0100.OnMsg100PreselectionChanged listener);
void setMsg100PreselectionAplication(boolean msg100PreselectionAplication);
}
Errors:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: game, PID: 18315
java.lang.RuntimeException: Unable to start activity ComponentInfo{game/game.MainActivity}: java.lang.ClassCastException: game.MainActivity cannot be cast to game.usecases.PreselectionAplicationUseCases
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389)
at android.app.ActivityThread.access$800(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1305)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5271)
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:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
Caused by: java.lang.ClassCastException: game.MainActivity cannot be cast to game.usecases.PreselectionAplicationUseCases
at game.MainActivity.onCreate(MainActivity.java:96)
at android.app.Activity.performCreate(Activity.java:6033)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2280)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389) 
at android.app.ActivityThread.access$800(ActivityThread.java:153) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1305) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5271) 
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:902) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
The problem is this: preselectionAplicationUseCases=(PreselectionAplicationUseCases) this;
You cannot cast MainActivity to PreselectionAplicationUseCases since MainActivity or any of it's superclasses don't extend PreselectionAplicationUseCases.

Error passing custom object between activities through intent

I tried passing this simple object from MainActivity to Main2Activity by implementing Serializable on the CustomObject. It results in Error. I referred the similar stack overflow questions. Nothing helped.
public class MainActivity extends Activity {
String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(this,Main2Activity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("data",new CustomObject());
//I tried i.putExtra(bundle);
i.putExtra("data",new CustomObject());
startActivity(i);
Log.d(TAG, "onCreate: ");
}
public class CustomObject implements Serializable{
public int i = 0;
public int j = 9;
CustomObject(){
}
}
}
Main2Activity
public class Main2Activity extends Activity {
String TAG = "Main2Activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent i = getIntent();
MainActivity.CustomObject c = (MainActivity.CustomObject)i.getSerializableExtra("data");
Log.d(TAG, "onCreate: "+c.i+" "+c.j);
}
}
Error Message:
07-30 13:58:58.352 26489-26489/? E/AndroidRuntime: FATAL EXCEPTION:
main
Process: gct.venkatesh.com.scrshtrebuilt, PID: 26489
java.lang.RuntimeException: Unable to start activity
ComponentInfo{gct.venkatesh.com.scrshtrebuilt/gct.venkatesh.com.scrshtrebuilt.MainActivity}:
java.lang.RuntimeException: Parcelable encountered IOException writing
serializable object (name =
gct.venkatesh.com.scrshtrebuilt.MainActivity$CustomObject)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2684)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6186)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Caused by: java.lang.RuntimeException: Parcelable encountered IOException writing
serializable object (name =
gct.venkatesh.com.scrshtrebuilt.MainActivity$CustomObject)
at android.os.Parcel.writeSerializable(Parcel.java:1527)
at android.os.Parcel.writeValue(Parcel.java:1475)
at android.os.Parcel.writeArrayMapInternal(Parcel.java:724)
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1417)
at android.os.Bundle.writeToParcel(Bundle.java:1157)
at android.os.Parcel.writeBundle(Parcel.java:764)
at android.content.Intent.writeToParcel(Intent.java:8703)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:3082)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1520)
at android.app.Activity.startActivityForResult(Activity.java:4229)
at android.app.Activity.startActivityForResult(Activity.java:4187)
at android.app.Activity.startActivity(Activity.java:4526)
at android.app.Activity.startActivity(Activity.java:4494)
at gct.venkatesh.com.scrshtrebuilt.MainActivity.onCreate(MainActivity.java:21)
at android.app.Activity.performCreate(Activity.java:6684)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2637)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6186) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779) 
Caused by: java.io.NotSerializableException:
gct.venkatesh.com.scrshtrebuilt.MainActivity
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1224)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1584)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1549)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1472)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1218)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
at android.os.Parcel.writeSerializable(Parcel.java:1522)
at android.os.Parcel.writeValue(Parcel.java:1475) 
at android.os.Parcel.writeArrayMapInternal(Parcel.java:724) 
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1417) 
at android.os.Bundle.writeToParcel(Bundle.java:1157) 
at android.os.Parcel.writeBundle(Parcel.java:764) 
at android.content.Intent.writeToParcel(Intent.java:8703) 
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:3082) 
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1520) 
at android.app.Activity.startActivityForResult(Activity.java:4229) 
at android.app.Activity.startActivityForResult(Activity.java:4187) 
at android.app.Activity.startActivity(Activity.java:4526) 
at android.app.Activity.startActivity(Activity.java:4494) 
at gct.venkatesh.com.scrshtrebuilt.MainActivity.onCreate(MainActivity.java:21) 
at android.app.Activity.performCreate(Activity.java:6684) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2637) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6186) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
by this error in logs:
java.io.NotSerializableException: gct.venkatesh.com.scrshtrebuilt.MainActivity at
MainActivity is not Serializable, i think platform wants MainActivity to be serializable because CustomObject is inner class in MainActivity ,
try to define your CustomObject in a separate local class (separate file)

NullPointerException (GameActivity does not open)

Please check whats the problem with my code here :
Main Activity :
I'm using Android Studio. Import statements are managed for me. It won't be necessary to write them here
public class MainActivity extends Activity implements View.OnClickListener {
SharedPreferences prefs;
String dataName = "MyData";
String intName = "MyString";
int defaultInt = 0;
public static int highScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonPlay = (Button) findViewById(R.id.btnPlay);
TextView textHighScore = (TextView) findViewById(R.id.textHighScore);
buttonPlay.setOnClickListener(this);
prefs = getSharedPreferences(dataName, MODE_PRIVATE);
highScore = prefs.getInt(intName, defaultInt);
textHighScore.setText("High Score: " + highScore);
}
#Override
public void onClick(View view) {
Intent intent;
intent = new Intent(this, GameActivity.class);
startActivity(intent);
}
}
When I run this application Main Activity is loaded but when I hit play button application closes. I have checked the play button's ID is O.K. I had the same problem in GameActivity but at last I figured out that the problem was with the ID but this time I think problem is with the this I used in Intent();. Activity fails to load.
Exception :
06-24 01:34:05.196 12826-12826/com.cruzerblade.memorygame E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.cruzerblade.memorygame, PID: 12826
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.cruzerblade.memorygame/com.cruzerblade.memorygame.GameActivity}: 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:2327)
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 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at android.view.animation.AnimationUtils.loadAnimation(AnimationUtils.java:75)
at com.cruzerblade.memorygame.GameActivity.<init>(GameActivity.java:55)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
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) 
Please help me out! It took me too much time still I couldn't figure out the problem.
Quoting from your logcat:
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.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at android.view.animation.AnimationUtils.loadAnimation(AnimationUtils.java:75)
at com.cruzerblade.memorygame.GameActivity.<init>(GameActivity.java:55)
This last line is the only line in the trace that is your code:
Look on line 55 of GameActivity.java. It is calling loadAnimation. There is something wrong with the animation it is trying to load (probably a missing resource ID, but it could also be a null or invalid context argument for loadAnimation.)

OnClickListener in separate class won't work

I've tried to use an OnClickListener from a different class but somehow it throws me an error. Can someone help me to solve this problem?
Thanks in advance.
public class TestClass extends Activity{
View.OnClickListener l = new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Clicked", Toast.LENGTH_LONG).show();
}};}
Part of the MainActivity:
#Override protected void onCreate(Bundle savedInstanceState) {
...
btnSpeech = (ImageButton) (findViewById(R.id.microphone));
obj=new TestClass();
btnSpeech.setOnClickListener(obj.l);
...
Error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.project/com.example.user.project.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' 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 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.user.project.MainActivity.onCreate(MainActivity.java:74)
at android.app.Activity.performCreate(Activity.java:6237)
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) 
You get a NullPointerException because your btnSpeech is null. findViewById() returns null if you use a wrong id for the view, maybe this is the problem.
What is sure is that your exception has nothing to do with the OnClickListener. If you read your stacktrace carefully you see that it says that setOnClickListener() was called on a object that was null.
And, as Mike commented, you cannot instantiate activities with the new keyword. Use startActivity() with an intent or make TestClass not extend Activity.
this is what you have just done quickly, but not if this will solve your problem
public class TestClass {
public static Context context;
public static View.OnClickListener getListener(){
return new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Clicked", Toast.LENGTH_LONG).show();
}
};
}
}
In Activity
TestClass.context = this;
my_button.setOnClickListener(TestClass.getListener());
Hope this help..

Categories

Resources