Java 在AsycTask内的处理程序中获取Toast上的NullPointerException,当它';有人打电话给他
当我使用应用程序时,我知道在AsycTask中,除非是处理程序,否则不能直接使用Toast。因此,到目前为止,处理程序运行良好。将土司作为处理程序,如下所示Java 在AsycTask内的处理程序中获取Toast上的NullPointerException,当它';有人打电话给他,java,android,Java,Android,当我使用应用程序时,我知道在AsycTask中,除非是处理程序,否则不能直接使用Toast。因此,到目前为止,处理程序运行良好。将土司作为处理程序,如下所示 private void threadMsg(String msg) { if (!msg.equals(null) && !msg.equals("")) { Message msgObj = handler.obtainMessage(); Bundle
private void threadMsg(String msg) {
if (!msg.equals(null) && !msg.equals("")) {
Message msgObj = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("message", msg);
msgObj.setData(b);
handler.sendMessage(msgObj);
}
}
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String aResponse = msg.getData().getString("message");
if ((null != aResponse)) {
// ALERT MESSAGE
Toast.makeText(
getBaseContext(),
"Server Response: " + aResponse,
Toast.LENGTH_SHORT).show();
progressBarHolder.setVisibility(View.INVISIBLE);
}
else
{
// ALERT MESSAGE
Toast.makeText(
getBaseContext(),
"Not Got Response From Server.",
Toast.LENGTH_SHORT).show();
}
}
};
我只是打电话给threadMsg(“消息”)在我的AsycTask中,它工作正常。但在我的新需求中,我碰巧从一个服务调用了AsycTask。当我执行它时,我在Toast上得到一个空指针异常。我不明白在这种情况下会发生什么。请帮我解决这个问题 编辑:执行AsycTask的服务代码
public class FirstService extends Service {
TayKitDatabaseOpenHelper db = new TayKitDatabaseOpenHelper(this);
private MyApplication app;
/** indicates how to behave if the service is killed */
int mStartMode;
/** interface for clients that bind */
IBinder mBinder;
/** indicates whether onRebind should be used */
boolean mAllowRebind;
/** Called when the service is being created. */
@Override
public void onCreate() {
app = (MyApplication) getApplication();
AsycInvokerActivity.OrderDeliveryAsyTask sm=new
AsycInvokerActivity().new OrderDeliveryAsyTask(orderDelivered);
sm.execute();
}
public void onStart(Intent intent, int startId) {
System.out.println("insuide service omstart");
}
/** The service is starting, due to a call to startService() */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("inside FirstServece's onStartCommand");
List<OrderDeliveryModel> deliveredOrders =
db.getAllDeliveredOrdersByUserId(app.getPudoType());
System.err.println("Total Number or orders which has to be synced:
"+deliveredOrders.size());
return mStartMode;
}
/** A client is binding to the service with bindService() */
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/** Called when all clients have unbound with unbindService() */
@Override
public boolean onUnbind(Intent intent) {
return mAllowRebind;
}
/** Called when a client is binding to the service with bindService()*/
@Override
public void onRebind(Intent intent) {
}
/** Called when The service is no longer used and is being destroyed */
@Override
public void onDestroy() {
}
}
公共类FirstService扩展服务{
TayKitDatabaseOpenHelper db=新的TayKitDatabaseOpenHelper(此);
私人应用程序;
/**指示服务终止时的行为方式*/
int-mStartMode;
/**用于绑定的客户端的接口*/
朱鹭;
/**指示是否应使用onRebind*/
布尔mAllowRebind;
/**在创建服务时调用*/
@凌驾
public void onCreate(){
app=(MyApplication)getApplication();
AsycInvokerActivity.OrderDeliveryAsyTask sm=新建
AsycInvokerActivity().new OrderDeliveryAsyTask(orderDelivered);
sm.execute();
}
公共无效启动(Intent Intent,int startId){
System.out.println(“内部服务omstart”);
}
/**由于调用startService()服务,服务正在启动*/
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
System.out.println(“在FirstServece的onStart命令中”);
列出发货人=
db.getAllDeliveredOrdersByUserId(app.getPudoType());
System.err.println(“必须同步的总订单数:
“+deliveredOrders.size());
返回mStartMode;
}
/**客户端正在使用bindService()绑定到服务*/
@凌驾
公共IBinder onBind(意向){
返回mBinder;
}
/**当所有客户端都与unbindService()解除绑定时调用*/
@凌驾
公共布尔onUnbind(意图){
返回mAllowRebind;
}
/**当客户端使用bindService()绑定到服务时调用*/
@凌驾
重新绑定时的公共无效(意图){
}
/**当服务不再使用且正在销毁时调用*/
@凌驾
公共空间{
}
}
编辑:堆栈跟踪
java.lang.NullPointerException
at android.widget.Toast.<init>(Toast.java:92)
at android.widget.Toast.makeText(Toast.java:233)
at com.example.databaseUtils.offlineDataUtils.AsycInvokerActivity$OrderDeliveryAsyTask$1.run(AsycInvokerActivity.java:174)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4441)
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:823)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
at dalvik.system.NativeStart.main(Native Method)
java.lang.NullPointerException
在android.widget.Toast.(Toast.java:92)
位于android.widget.Toast.makeText(Toast.java:233)
在com.example.databaseUtils.offlineDataUtils.AsycInvokerActivity$orderdeliveryasytash$1.run(AsycInvokerActivity.java:174)
位于android.os.Handler.handleCallback(Handler.java:605)
位于android.os.Handler.dispatchMessage(Handler.java:92)
位于android.os.Looper.loop(Looper.java:137)
位于android.app.ActivityThread.main(ActivityThread.java:4441)
位于java.lang.reflect.Method.Invokenactive(本机方法)
位于java.lang.reflect.Method.invoke(Method.java:511)
在com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run上(ZygoteInit.java:823)
位于com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
在dalvik.system.NativeStart.main(本机方法)
您需要使用UI线程在异步任务中显示Toast
runOnUiThread(new Runnable(){
@Override
public void run(){
//update ui here
// display toast here
}
});
从服务调用threadMsg方法时,不能使用其上下文,因为Activty和service都有不同的生命周期
尝试使用IntentService
问题是服务没有运行UI线程。您可以通过
活动
显示烤面包片
:
@Override
public void onCreate() {
super.onCreate();
mHandler = new Handler();
}
@Override
protected void onHandleIntent(Intent intent) {
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MyIntentService.this,
"Hello Toast!", Toast.LENGTH_LONG).show();
}
});
}
从调用服务的活动中传递上下文,并将此上下文写入toast消息中,它将解决您的错误。最终找到问题的解决方案。 问题是
AsyncTask在某个活动中,我正在将其(活动的)上下文传递给Toast。每当我从同一个活动中调用AsyncTask时,它都对我有效。但是,当我试图从服务调用该AsyncTask时,我得到的是NullPointerException,因为Toast使用的是同一活动的上下文
所以我必须将服务的上下文传递给异步任务。成功了 要在android的任何地方显示Toast,我们需要一个UI线程。只有UI线程才能与UI内容交互并呈现它,例如Toast、Dialog、Progressbar等 因此,在IntentService中创建一个UI(可运行)线程,如下所述:-
private Handler handler;
handler = new Handler();
handler.post(new Runnable() {
public void run() {
try {
System.out.println("inside FirstService's onStartCommand");
List<OrderDeliveryModel> deliveredOrders = db.getAllDeliveredOrdersByUserId(app.getPudoType());
System.err.println("Total Number or orders which has to be synced: "+deliveredOrders.size());
for(OrderDeliveryModel orderDelivered : deliveredOrders) {
AsycInvokerActivity.OrderDeliveryAsyTask sm=new AsycInvokerActivity().new OrderDeliveryAsyTask(orderDelivered,context);
sm.execute();
}
} catch (Exception e) {
System.err.println("Error in catch is "+e);
//Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
IntentService的构造函数,并使用传递的上下文在处理程序的toast中成功显示toast。您可以发布服务调用代码以更好地理解…似乎是上下文问题…使用
getApplicationContext()
而不是getBaseContext()
您的getBaseContext()
可能是null
@Rustam我也使用了getApplicationContext()。但仍然是相同的结果您需要一个活动来显示Toast,如果您有一个,请检查以下内容:使用您的Activity.this而不是getBaseContext()检查
Context context;
context = getApplicationContext();