I am totally new to Android development, so I apologize before hand if what I'm asking is really simple, I've been Googleing around for the past couple of hours with no luck.
In my MainActivity I reference AlarmReceiver.class in an Intent and then into a PendingIntent and finally it is set to an AlarmManager. Which I do to set an alarm, and this works fine, it's when the alarm is triggered the Exception happens.
Intent intent = new Intent(ourContext, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ourContext, 666, intent, 0);
AlarmManager alarmManager = (AlarmManager) ourContext.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
And then in AlarmReceiver.class it extends BroadcastReceiver, and makes an SDK call.
This part of the code in run whenever the Alarm triggers, meaning when the selected time is neigh, run this code.
public void onReceive(Context arg0, Intent arg1) {
SDK.sendNotification(arg0, new Notification("alarm", "Top Line", "Bottom Line"), new SendNotificationListener() {
#Override
public void onSuccess(String s) {
Log.d("success", s);
}
#Override
public void onFailed(String s) {
Log.d("fail", s);
}
});
}
SendNotification takes 3 variables, a context, a Notification and a NotificationListener.
What I've been able to determine, I am pretty sure that it's the NotificationListener that is the problem and causes the error.
Here is the stacktrace:
Process: com.example.timer:remote, PID: 27665
java.lang.RuntimeException: Unable to start receiver com.example.timer.AlarmReceiver: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2452)
at android.app.ActivityThread.access$1700(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
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:796)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.imer.AlarmReceiver.onReceive(AlarmReceiver.java:21)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2445)
at android.app.ActivityThread.access$1700(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
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:796)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
This is line 21:
SDK.sendNotification(arg0, new Notification("alarm", "Top Line", "Bottom Line"), new SendNotificationListener() {
If the exception is thrown here:
SDK.sendNotification(arg0,
new Notification("alarm", "Top Line", "Bottom Line"),
new SendNotificationListener() {
then the only possible explanation is that SDK is null. Check that it is properly initialized; i.e. a non-null value has been assigned to it. (And check that you don't have multiple declarations ... and that some of them are not initialized.)
You posted this as (supposed) counter-evidence.
SDK.initiate(getActivity(), "DEVCODE", new String[] { Scope },
new AuthListener() {
That doesn't set SDK to a non-null value. It doesn't set (hint: assign) anything to SDK.
(But hypothetically, it would give an NPE if SDK is a variable, it is null and initiate is an instance method.)
That statement may not be executed.
Even if that SDK variable is not null, there could be another declaration of SDK.
In short, that doesn't prove anything.
Related
I am new to android studio and I am trying to build a Notepad app.
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String title = findViewById(R.id.textView3).toString();
String note_content = findViewById(R.id.textView).toString();
FileOutputStream outputStream;
try
{
outputStream = openFileOutput(title, Context.MODE_PRIVATE);
outputStream.write(note_content.getBytes());
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
MainActivity mainActivity = new MainActivity(title);
}
});
This is the button a user clicks to save the note. Once the code saves the note, it should send the Title to MainActivity so that it can be sent to Recycleview Adapter - this will display it in viewholder as a text.
Presently, when I run the code, it crashes - however, when I remove the constructor, the app works fine.
( MainActivity mainActivity = new MainActivity(title);)
Error:
10-02 02:39:13.822 27279-27279/? D/AndroidRuntime: Shutting down VM
10-02 02:39:13.824 27279-27279/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.quicknote, PID: 27279
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.quicknote/com.example.quicknote.MainActivity}: java.lang.InstantiationException: java.lang.Class<com.example.quicknote.MainActivity> has no zero argument constructor
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2337)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.InstantiationException: java.lang.Class<com.example.quicknote.MainActivity> has no zero argument constructor
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1090)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
10-02 02:39:20.081 27279-27279/com.example.quicknote I/Process: Sending signal. PID: 27279 SIG: 9
As per the error message:
java.lang.InstantiationException: java.lang.Class has no zero argument constructor
A zero argument constructor is required for the Android system to instantiate an Activity. You should never be manually calling an Activity constructor yourself since only the system can properly create an Activity.
The Parcelables and Bundles documentation details the correct way of sending information to an Activity using the extras Bundle.
Unable to instantiate activity. Because you can't start an activity like this. You have to use intent to start activity. To sent "title" use intent extra.
Intent intent=new Intent(CurrentActivity.this, NewActivty.this);
intent.putExtra("title", title);
startActivty(intent);
Is your Activity in your AndroidManifest.xml?
If it is, you have to retrieve the title from your extras from onCreate() of MainActivity instead from the constructor.
Something like that:
//that code instead of your MainActivity mainActivity = new MainActivity(title); line
Intent intent = new Intent(YourActualActivity.this, MainActivity.class);
intent.putExtra("title", title);
startActivity(intent);
//That code in the onCreate method of your MainActivity
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title = extras.getString("title");
}
The microhonePopUp method will work in MainActivity, but I'd like for it to work from another class (MediaButtonIntentReceiver). The problem is with startActivityForResult(intent, REQUEST_CODE); - but I don't know how to resolve it.
in the MainActivity class
public void microphonePopUp(){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice your answer");
startActivityForResult(intent, REQUEST_CODE);
}
in the MediaButtonIntentReceiver class
public class MediaButtonIntentReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (KeyEvent.KEYCODE_HEADSETHOOK == event.getKeyCode()) {
MainActivity test = new MainActivity();
test.microphonePopUp();
}
}
}
}
12-09 11:20:14.803 19556-19556/com.timtennyson.priceaddition
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.timtennyson.priceaddition, PID: 19556
java.lang.RuntimeException: Unable to start receiver
com.timtennyson.priceaddition.MediaButtonIntentReceiver:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.app.ActivityThread$ApplicationThread
android.app.ActivityThread.getApplicationThread()' on a null object
reference
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3641)
at android.app.ActivityThread.access$2000(ActivityThread.java:221)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1876)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.app.ActivityThread$ApplicationThread
android.app.ActivityThread.getApplicationThread()' on a null object
reference
at android.app.Activity.startActivityForResult(Activity.java:4283)
at android.app.Activity.startActivityForResult(Activity.java:4230)
at
android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:842)
at
com.timtennyson.priceaddition.MainActivity.microphonePopUp(MainActivity.java:103)
at
com.timtennyson.priceaddition.MediaButtonIntentReceiver.onReceive(MediaButtonIntentReceiver.java:27)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3634)
at android.app.ActivityThread.access$2000(ActivityThread.java:221)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1876)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
NEVER create an instance of an activity, service, or provider yourself.
If your objective is to listen for ACTION_MEDIA_BUTTON broadcasts while MainActivity is visible:
Move MediaButtonIntentReceiver to be a nested class inside of MainActivity
Get rid of test from onReceive(), and just call microphonePopUp() (which I assume is a method on MainActivity)
Register your MediaButtonIntentReceiver using registerReceiver() in onStart() of MainActivity, and use unregisterReceiver() in onStop()
If your objective is to listen ACTION_MEDIA_BUTTON broadcasts at other points in time — by registering your receiver in the manifest — while you can do that, you cannot use microphonePopUp() from that receiver.
I have a AsyncTask in a Service. I send an ArrayList as broadcast from the AsyncTask.
When I get the ArrayList in onReceive() I get a NullpointerException.
This is how I send the ArrayList.
transits_list = new ArrayList<Transit>();
transits_list.add(trs);
Intent arrayListIntent = new Intent("arrayList");
Bundle extra = new Bundle();
extra.putSerializable("transArray", transits_list);
intent.putExtra("extra", extra);
sendBroadcast(arrayListIntent);
The Transit class implements Serializable.
Receiving the ArrayList
#Override
public void onReceive(Context context, Intent intent) {
ArrayList<Transit> myList;
Bundle extra = getIntent().getBundleExtra("extra");
ArrayList<Transit> transArrayListFromBroadCast = (ArrayList<Transit>) extra.getSerializable("transArray");
System.out.print("transArrayListFromBroadCast "+transArrayListFromBroadCast);
}
I get NullpointerException in this line:
ArrayList<Transit> transArrayListFromBroadCast = (ArrayList<Transit>) extra.getSerializable("transArray");
The exception from log:
FATAL EXCEPTION: main
java.lang.RuntimeException: Error receiving broadcast Intent { act=arrayList flg=0x10 } in com.prematix.tollsystem.avcc.AvccActivity$ArrayListReceiver#42003268
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:798)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5391)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.prematix.tollsystem.avcc.AvccActivity$ArrayListReceiver.onReceive(AvccActivity.java:271)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:788)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5391)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
Your method of getting the Intent is incorrect. I believe your BroadcastReceiver is in an activity class since, you are calling getIntent(). However, getIntent() will get you the Intent supplied to the activity and not the receiver. The Intent for receiver is provided to the method onReceive() itself. Make the following changes to your code:
Adding extra:
Intent arrayListIntent = new Intent("arrayList");
Bundle extra = new Bundle();
extra.putSerializable("transArray", transits_list);
intent.putExtra("extra", extra);
sendBroadcast(arrayListIntent);
Getting Extra:
#Override
public void onReceive(Context context, Intent intent) {
ArrayList<Transit> myList;
Bundle extra = intent.getBundleExtra("extra");
ArrayList<Transit> transArrayListFromBroadCast = (ArrayList<Transit>) extra.getSerializable("transArray");
// System.out.print("transArrayListFromBroadCast "+transArrayListFromBroadCast);
}
So I am testing my android app using Robotium and when I go to click on the item in my list it by solo.clickInList(0,1); using gives me
java.lang.RuntimeException: This method can not be called from the main application thread
at android.app.Instrumentation.validateNotAppThread(Instrumentation.java:1787)
at android.app.Instrumentation.runOnMainSync(Instrumentation.java:348)
at com.robotium.solo.Scroller.scrollListToLine(Scroller.java:326)
at com.robotium.solo.Scroller.scrollList(Scroller.java:276)
at com.robotium.solo.Scroller.scroll(Scroller.java:195)
at com.robotium.solo.Scroller.scroll(Scroller.java:156)
at com.robotium.solo.Scroller.scrollDown(Scroller.java:169)
at com.robotium.solo.Waiter.waitForView(Waiter.java:154)
at com.robotium.solo.Waiter.waitForAndGetView(Waiter.java:521)
at com.robotium.solo.Clicker.clickInList(Clicker.java:516)
at com.robotium.solo.Solo.clickInList(Solo.java:1244)
at com.teamname.tutortrader.AvailableSessionsActivityTest.testViewOneSession(AvailableSessionsActivityTest.java:119)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:214)
at android.test.InstrumentationTestCase.access$000(InstrumentationTestCase.java:36)
at android.test.InstrumentationTestCase$2.run(InstrumentationTestCase.java:189)
at android.app.Instrumentation$SyncRunnable.run(Instrumentation.java:1855)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
I am using the #UiThreadTest on top of my function.
As I found here it looks like a bug in robotium.
https://stackoverflow.com/a/20200643/6150020. You can probably do the same thing by yourself without robotium.
public void onListViewItemClick(){
Activity activity = getActivity();
final ListView listView = (ListView)activity.findViewById(android.R.id.list);
getInstrumentation().runOnMainSync(new Runnable() {
#Override
public void run() {
listView.performItemClick(listView.getAdapter().getView(0, null, null), 0, listView.getItemIdAtPosition(0));
}
});
}
I am quite new to android development and I am facing a NullPointerException when I am trying to call an AsyncTask which is an inner class in another class.
I believe it is the way I am instantiating it but this is what I have:
// This onClick is in my adapter class - which is a separate Java File and class
#Override
public void onClick(View v) {
UploadRes uploadRes = new UploadRes();
UploadRes.UploadResConfirm uploadResConfirm = uploadRes.new UploadResConfirm(v.getContext());
uploadResConfirm.execute(fileName, filePath);
}
public class UploadResConfirm extends AsyncTask<String, String, String> {
Dialog dialog;
Context context;
public UploadResConfirm(Context context){
this.context = context;
}
#Override
protected void onPreExecute(){
dialog = new Dialog(UploadRes.this);
dialog.setTitle("Currently uploading");
dialog.show();
}
I believe it has got something to do with the dialog box itself being instantiated in the AsyncTask class.
The error stack trace on Logcat - its the Dialog, I think its in the wrong place...
java.lang.NullPointerException
at codeman.androapp.UploadRes$UploadResConfirm.onPreExecute(UploadRes.java:246)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Some help if any would be much obliged.
Instead of dialog = new Dialog(UploadRes.this);
Try
dialog = new Dialog(context);
your are passing a wrong context to create dialog.