【问题标题】:Why my app crash when i use an intentService to save data?当我使用 intentService 保存数据时,为什么我的应用程序会崩溃?
【发布时间】:2015-04-18 12:20:39
【问题描述】:

我正在尝试将一些数据从文件保存到数据库。不使用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);

我的问题是为什么没有服务一切都很好,使用后又乱了?!!!出了什么问题? - 非常感谢任何帮助。我展示了我的 intentService 类:

 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();
        }
}

然后从 MainActivity 我像这样启动服务:

Intent i = new Intent(MainActivityMyTest.this, TheIntentService.class);
            startService(i);

【问题讨论】:

    标签: android android-asynctask android-intentservice


    【解决方案1】:

    为什么没有服务一切都好,用了之后就乱了?!!!

    因为您创建了自己的MainActivityMyTest 实例,它似乎是Activity从不自己创建ActivityServiceContentProvider 的实例。 Android 的框架创建了这些,而不是您。据推测,MainActivityMyTest 在其生命周期的某处创建了httpclient(例如,onCreate()),但这并没有发生。

    请将与writeToTable() 关联的代码移动到IntentService 本身。

    【讨论】:

    • writeToTable() 正在从另一个方法获取字符串!我正在使用broadcastReceiverAsyncTask 获取结果。我可以把整个东西移到IntentService 本身吗?!
    • @carl:“我可以把整个东西移到 IntentService 本身吗?!” - 我不知道。你所描述的听起来过于复杂。更重要的是IntentService给你一个后台线程;你不应该从onHandleIntent() 分叉其他后台线程(包括AsyncTask)。而且您的IntentService 不能自己创建活动实例。
    • 在尝试像我的示例一样在线保存一些数据时,是否可以在不使用AsyncTask 的情况下获得servlet
    • 或者只是使用IntentService是个坏主意?
    • 感谢您的帮助。你解释了一些我以前不知道的重要事情。我将专注于其他内容,例如to binde a service to an Activity
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    相关资源
    最近更新 更多