我正在尝试将文件中的一些数据保存到数据库中。一切都很好,不使用intentService
.但是,当我使用 IntentService
时我的应用程序崩溃,并且我的 asyncTask 出现错误,如下所示:
java.lang.RuntimeException: An error occured while executing doInBackground()
Caused by: java.lang.NullPointerException
at com.example.carl.myTest.AsyncTask.doInBackground(AsyncTask.java:44)
第 44 行是:HttpResponse response = httpClient.execute(httpPost);
我的问题是为什么没有服务一切都很好,使用后会混乱?!!!出了什么问题?- 任何帮助都非常感谢。我展示我的意图服务类:
public class TheIntentService extends IntentService {
MainActivityMyTest t = new MainActivityMyTest ();
private Handler handler = new Handler();
public MyIntentService() {
super("TheIntentService ");
}
@Override
protected void onHandleIntent(Intent intent) {
t.writeToTable();
handler.post(showResult);
}
private Runnable showResult = new Runnable() {
public void run() {
Context c = TheIntentService .this.getApplicationContext();
Toast.makeText(c, "Mission accomplished", Toast.LENGTH_SHORT).show();
}
};
@Override
public void onDestroy() {
Context c = this.getApplicationContext();
Toast.makeText(c, "Exits service", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
}
从主活动,我像这样启动服务:
Intent i = new Intent(MainActivityMyTest.this, TheIntentService.class);
startService(i);
为什么没有服务一切都很好,使用后就会混乱?!!!
因为您创建了自己的 MainActivityMyTest
实例,这似乎是一个Activity
。永远不要自己创建Activity
、Service
或ContentProvider
的实例。Android的框架创造了这些,而不是你。据推测,MainActivityMyTest
在其生命周期的某个地方(例如,onCreate()
)产生了httpclient
,而这并没有发生。
请将与writeToTable()
关联的代码移动到IntentService
本身。