unable to start activity from onPostexecute() using interface - android

I need to start another activity from the onPosExecute method of the AsyncTask. The AsyncTask is a seperate class and not in any activity class.
I have used an interface to do so. The codes are:
This is the onPostExecute() method
#Override
protected void onPostExecute(String json) {
Log.v("JSON", json);
Log.v("updateUI",""+updateUI);
updateUI.changeActivity();
}
This is the interface
public interface UpdateUIListener {
public void changeActivity();
}
And this is the part of the activity class where the interface is implemented
#Override
public void changeActivity() {
Intent blah=new Intent(this,SplashActivity.class);
startActivity(blah);
finish();
}
When I run the code, a null pointer exception shows up, at the line
Intent blah=new Intent(this,SplashActivity.class);
My stacktrace is:
java.lang.NullPointerException
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
at android.content.ComponentName.<init>(ComponentName.java:75)
at android.content.Intent.<init>(Intent.java:3546)
at com.autofoyer.SignUpActivity.changeActivity(SignUpActivity.java:79)
at com.autofoyer.common.MyClientTask.onPostExecute(MyClientTask.java:73)
at com.autofoyer.common.MyClientTask.onPostExecute(MyClientTask.java:23)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5099)
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:803)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:570)
at dalvik.system.NativeStart.main(Native Method)
I need to know what is causing and How to solve the null point exception. I need to start and activity from the onPostExecute method. Thanks in advance!

You probably instantiate updateUI with new SplashActivity() or similar. You can't do that. Instead you have to pass a Context into your AsyncTask and use that to call startActivity() . You probably start the AsyncTask from some Activity, so just pass that Activity as a Context when instantiating the AsyncTask.

Related

Starting method from class causes Null Pointer Exception

I am trying to access/call a method I have in my Activity from my class but I am getting null pointer exception when doing so.
Here's the method i am trying to call. This method is in my Activity:
public void start(Context context){
mHelper = new IabHelper(context.getApplicationContext(), base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " + result);
} else {
Log.d(TAG, "In-app Billing is set up OK");
mHelper.enableDebugLogging(true, TAG);
startPurchase();
}
}
});
}
In my class where I am calling it from, I have made an instance of the class:
ThemeActivity themeact = new ThemeActivity();
And I am trying to call it from an onClicklistener within my class:
new AlertDialog.Builder(getContext())
.setMessage(
"Would you like to purchase this theme?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog, int id) {
//Here is where I am calling it
themeact.start(getContext());
}
}).setNegativeButton("No", null).show();
And I receive the following error in LogCat:
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
at test.test.util.IabHelper.<init>(IabHelper.java:164)
at test.test.ThemeActivity.start(ThemeActivity.java:161)
at test.test.ColorCard$1$1.onClick(ColorCard.java:67)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:171)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
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:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
EDIT
I realized that I was calling the wrong method to start with, and now i am calling the correct method and it still crashes with a null pointer exception with a different error. I have tried to pass a context and it still isn't working. Whenever I try to call the method start(); from the on create of my Activity, it works. But then when trying to call the exact same method from my other class it crashes and I have no idea why. I initialize everything from within the method itself so I'm not sure why it crashes with null.
Try passing the context variable of the activity as an argument to startPurchase() method
In the end I fixed my problem by moving my class inside my activity class. I am not sure why it works now but it didn't when I had the class I was using as a separate class.

Error when working with the context in fragment

everything works. question - well I do? and how can otherwise call contexthow to call this method?
in MyActivity:
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
in my fragment I call the method:
public void setData(){
new MyAsincTask(getActivity()){
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(Document document) {
super.onPostExecute(document);
........
getActivity().setTitle("Сотрудники(city:" + city + ",holiday:" + holiday + ")");
}
}.execute(link);
}
it works. but if during the process to move to another part of the application crashes
but if you add
if (getActivity()!=null)
getActivity().setTitle("Сотрудники(city:" + city + ",holiday:" + holiday + ")");
everything works. question - well I do? and how can otherwise call context
12-24 05:18:28.805 460-460/com.managment.pavel.managmentgradle E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.managment.pavel.managmentgradle.fragments.EmployeessList$1.onPostExecute(EmployeessList.java:114)
at com.managment.pavel.managmentgradle.fragments.EmployeessList$1.onPostExecute(EmployeessList.java:69)
at android.os.AsyncTask.finish(AsyncTask.java:417)
at android.os.AsyncTask.access$300(AsyncTask.java:127)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
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)
The fragment had been detached when you navigated to another part of the app, so getActivity will return null. Since it is not meaningful to change the title of an activity that had been destroyed, it is probably OK to just put the null check in like you did.
However this can become a bigger problem if your async task must call back to the activity. I recommend using an event bus such as Otto to pass data from async task back up to the UI.
Here is my blog post on this topic: Event Bus Usage on Android

FATAL EXCEPTION: main NullPointerException in Android

I have two class. One of them is activity. I have a function in activity class and try to call in other class. In function i can't use view functions(setContentView, findViewById) These functions works well in onCreate. I try to change image position and size.
function definition like:
public void changePosition(int x, int y, int z){
}
I always got this error. Why these functions works only in onCreate?
Logcat:
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.project.scan, PID: 26122
java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1970)
at com.example.project.scan.ProjectActivity.changePosition(ProjectActivity.java:255)
at com.example.project.scan.Model$1.handleMessage(Model.java:145)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
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:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
ProjectActivity.java:255 :
image = (ImageView)findViewById(R.id.im);
Model.java:145:
myActivity.changePosition(x,y,z);
Seems like you've instantiated your myActivity with new. Never instantiate activities with new as they won't be properly initialized for anything you'd use an activity for.
Use an Intent to instantiate activities with correct lifecycle initialization, or pass the activity reference (this in an activity) to other methods that need to call methods in the activity.
You can pass the Activity reference
use below code:
public class YourClass
{
Activity activity ;
public YourClass(Activity _activity)
{
activity = _activity ;
}
}
Then use it as :
classObject.changePosition(x,y,z);
Now you can use method like :
activity.findViewById(id)
Don't forget to pass the Activity reference as:
YourClass classObject = new YourClass(ProjectActivity.this);
Hope it helps ツ

service crashing on start

// PPS.java
package com.domain.Servicecrasher;
import android.app.Service;
import android.view.Gravity;
import android.widget.Toast;
public abstract class PPS extends Service
{
#Override
public void onCreate()
{
Toast toasty = Toast.makeText(PPS.this, "service created!", 500);
toasty.setGravity(Gravity.CENTER, 0, 200);
toasty.show();
};
public void onDestroy()
{
Toast toasted = Toast.makeText(PPS.this, "service destroyed!", 500);
toasted.setGravity(Gravity.CENTER, 0, -200);
toasted.show();
};
};
tried to call the service using two methods:
method 1.
{
{
{
startService(new Intent(MainMenu.this, PPS.class));
}
}
}
method 2
{
{
{
Intent startPPS = new Intent(MainMenu.this, PPS.class);
startPPS.putExtra("com.domain.Servicecrasher.PPS", false);
startService(startPPS);
}
}
}
these both return an error on the emulator saying the app quit unexpectedly and i click force close, but the main activity doesn't close, so i'm assuming it's the service that i am force closing. below is the DDMS output:
java.lang.RuntimeException: Unable to instantiate service com.domain.Servicecrasher.PPS
at android.app.ActivityThread.handleCreateService(ActivityThread.java:1929)
at android.app.ActivityThread.access$2500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:985)
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(Zygote.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
caused by: java.lang.InstantiationException: com.domain.Servicecrasher.PPS
at java.lang.Class.newInstaceImp1(Native Method)
at java.lang.Class.newInstaceI(Class.java:1409)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:1926)
... 10 more
just a couple simple questions.
what am i doing wrong?
what is the proper way to do this?
eventually i need the service to be capable of loading settings from a SQL base and continue recording audio to a file after the main activity loses focus or is closed.
for now i'd be happy if i could just launch a simple service.
Abstract classes, be they Services or other things, cannot be instantiated. Eclipse no doubt suggested that you add the abstract keyword to your class because you had not implemented all the necessary methods to make a concrete instance.
I don't know if Eclipse has an option like this (I assume it does), but IntelliJ IDEA has an option where you can select "implement methods" when you have an incomplete class and it'll add all the stubs you need to fill in. Try that, or consult the documentation for a full list.

App is crashing after Home is pressed. Unable to pause - Derived class did not call super.onSaveInstanceState()

When I press the Home button, the app should be paused, save all state and work fine.
Instead I get this error:
java.lang.RuntimeException: Unable to
pause activity
{be.test.tester/be.test.tester.DataScreen}:
java.lang.IllegalStateException:
Derived class did not call
super.onSaveInstanceState() at
android.app.ActivityThread.performPauseActivity(ActivityThread.java:3641)
at
android.app.ActivityThread.performPauseActivity(ActivityThread.java:3598)
at
android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3574)
at
android.app.ActivityThread.access$2500(ActivityThread.java:136)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:2186)
at
android.os.Handler.dispatchMessage(Handler.java:99)
at
android.os.Looper.loop(Looper.java:143)
at
android.app.ActivityThread.main(ActivityThread.java:5068)
at
java.lang.reflect.Method.invokeNative(Native
Method) at
java.lang.reflect.Method.invoke(Method.java:521)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at
dalvik.system.NativeStart.main(Native
Method)
Caused by:
java.lang.IllegalStateException:
Derived class did not call
super.onSaveInstanceState() at
android.view.View.dispatchSaveInstanceState(View.java:6087)
at
android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:1207)
at
android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:1207)
at
android.view.View.saveHierarchyState(View.java:6068)
at
com.android.internal.policy.impl.PhoneWindow.saveHierarchyState(PhoneWindow.java:1475)
at
android.app.Activity.onSaveInstanceState(Activity.java:1106)
at
android.app.Activity.performSaveInstanceState(Activity.java:1056)
at
android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1289)
at
android.app.ActivityThread.performPauseActivity(ActivityThread.java:3623)
... 12 more
My activity reacts on touch:
public class DataScreen extends Activity implements OnGestureListener{
I'm getting some extra's from the intent:
totUsage = Integer.parseInt(getIntent().getStringExtra("extraTotUsage"));
limit = Integer.parseInt(getIntent().getStringExtra("extraLimit"));
Bundle bundle = getIntent().getExtras();
mylist = (ArrayList<HashMap<String, String>>) bundle.get("extraMyList");
A custom view is showing data (canvas). When you scroll on screen, data changes in custom view (set, get method) and redraws itself.
I don't really manage the onSaveInstanceState here, don't really know if I have to.
My app is onTop of the stack, because of:
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
I don't understand the error.
You should override onSaveInstanceState and call its super method like shown below. At least it helped me with the same problem.
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// your stuff or nothing
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// your stuff or nothing
}
I've just been dealing with this problem. In my app the main activity allows a second activity to be called to display info/instructions etc, it also has a surface view that draws the runtime element of the app.
The main activity has a variable to hold the surface view, if that variable hasn't been set before the info/instructions activity is called I get this error. I simply moved the surface view variable assignment into the main activity onCreate and all is well.
It is also possible that one uses a custom preference (e.g. custom dialog preference) that does not call "super.onSavedInstanceState()" which leads to the same error.

Categories

Resources