关闭应用程序后使用服务获取NullPointerException

时间:2015-01-23 14:02:24

标签: java android httprequest intentservice

我曾经使用IntentService创建AlarmService,它执行另一个类TakeUserData。该类发出一些HTTP请求。当应用程序打开时,一切正常,但在关闭过程后,我在每次服务调用时都会收到java.lang.NullPointerException。

这里的logcat:

01-23 16:27:00.999  18276-18290/com.eugnis.vktrace W/System.err﹕ java.lang.NullPointerException
    01-23 16:27:01.009  18276-18290/com.eugnis.vktrace W/System.err﹕ at com.vk.sdk.api.VKRequest.getLang(VKRequest.java:548)
    01-23 16:27:01.009  18276-18290/com.eugnis.vktrace W/System.err﹕ at com.vk.sdk.api.VKRequest.getPreparedParameters(VKRequest.java:274)
    01-23 16:27:01.009  18276-18290/com.eugnis.vktrace W/System.err﹕ at com.vk.sdk.api.httpClient.VKHttpClient.requestWithVkRequest(VKHttpClient.java:127)
    01-23 16:27:01.009  18276-18290/com.eugnis.vktrace W/System.err﹕ at com.vk.sdk.api.VKRequest.getPreparedRequest(VKRequest.java:297)
    01-23 16:27:01.009  18276-18290/com.eugnis.vktrace W/System.err﹕ at com.vk.sdk.api.VKRequest.getOperation(VKRequest.java:311)
    01-23 16:27:01.009  18276-18290/com.eugnis.vktrace W/System.err﹕ at com.vk.sdk.api.VKBatchRequest.executeWithListener(VKBatchRequest.java:76)
    01-23 16:27:01.009  18276-18290/com.eugnis.vktrace W/System.err﹕ at com.eugnis.vktrace.TakeUserData.<init>(TakeUserData.java:91)
    01-23 16:27:01.009  18276-18290/com.eugnis.vktrace W/System.err﹕ at com.eugnis.vktrace.CheckUsersService.onHandleIntent(CheckUsersService.java:107)
    01-23 16:27:01.009  18276-18290/com.eugnis.vktrace W/System.err﹕ at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
    01-23 16:27:01.009  18276-18290/com.eugnis.vktrace W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102)
    01-23 16:27:01.009  18276-18290/com.eugnis.vktrace W/System.err﹕ at android.os.Looper.loop(Looper.java:157)
    01-23 16:27:01.009  18276-18290/com.eugnis.vktrace W/System.err﹕ at android.os.HandlerThread.run(HandlerThread.java:61)

和IntentService类:

package com.eugnis.vktrace;
...

public class CheckUsersService extends IntentService {
    SaveUserData dbHelper;
    SQLiteDatabase db;
    TakeUserData take;

    public CheckUsersService() {
        super("CheckUsersService");
    }



    public int onStartCommand(Intent intent, int flags, int startId){
        Log.d("ABAB", "ON START COMMAND");
        try {
            dbHelper = new SaveUserData(this);
            db = dbHelper.getWritableDatabase();
            Cursor c = db.query("users", null, null, null, null, null, null);
            if (c.moveToFirst()) {
                int useridColIndex = c.getColumnIndex("userid");
                do {
                    int userID = c.getInt(useridColIndex);
                    take = new TakeUserData(this, userID, 1,1,1,1,1,1,1);
                } while (c.moveToNext());
            } else
                Log.d("VkDemoApp", "0 rows");
            c.close();
            Log.v(this.getClass().getName(), "Timed alarm onReceive() started at time: " + new java.sql.Timestamp(System.currentTimeMillis()).toString());
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return 1;
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d("ABAB", "INTENT STARTED");
    }
}

TakeUserData:

public class TakeUserData {

    SaveUserData dbHelper;
    String selection = null;
    String[] selectionArgs = null;
    int online=0, friends=0, status=0, pagedata=0, photovideo=0, music=0, groups=0, posts=0;
    VKApiUserFull userInfo;
    Context context;
    private static final int NOTIFY_ID = 101;

    public TakeUserData(Context v, final int userID, final int chkonline, final int chkfriends, final int chkpagedata, final int chkphotovideo, final int chkmusic, final int chkgroups, final int chkposts)
    {
        context=v;
        dbHelper = new SaveUserData(context);

        final SQLiteDatabase db = dbHelper.getWritableDatabase();

        Log.d("VkDemoApp", "--- Rows in mytable: ---");

        selection = "userid="+userID;
        Cursor c = db.query("users", null, selection, null, null, null, null);

        if(c.getCount()==1) {
            if (c.moveToFirst()) {

                int onlineColIndex = c.getColumnIndex("online");
                int friendsColIndex = c.getColumnIndex("friends");
                //  int statusColIndex = c.getColumnIndex("status");
                int pagedataColIndex = c.getColumnIndex("pagedata");
                int photovideoColIndex = c.getColumnIndex("photovideo");
                int musicColIndex = c.getColumnIndex("music");
                int groupsColIndex = c.getColumnIndex("groups");
                int postsColIndex = c.getColumnIndex("posts");

                online = c.getInt(onlineColIndex);
                friends = c.getInt(friendsColIndex);
                pagedata = c.getInt(pagedataColIndex);
                photovideo = c.getInt(photovideoColIndex);
                music = c.getInt(musicColIndex);
                groups = c.getInt(groupsColIndex);
                posts = c.getInt(postsColIndex);

            } else
                Log.d("VkDemoApp", "0 rows");
            c.close();
        }



        if (c.moveToFirst()) {

            VKRequest requestUserInformation = VKApi.users().get(VKParameters.from(VKApiConst.USER_ID, userID, VKApiConst.FIELDS, "photo_200, counters, last_seen, status, photo_id, city, contacts, education, relatives, relation, personal, connections, activities, interests, music, movies, tv, books, games, about, quotes"));
            VKRequest requestUserPosts = VKApi.wall().get(VKParameters.from(VKApiConst.OWNER_ID, userID));
            VKBatchRequest batch = new VKBatchRequest(requestUserInformation, requestUserPosts);


            batch.executeWithListener(new VKBatchRequest.VKBatchRequestListener() {  //Error from this column
                @Override

                public void onComplete(VKResponse[] responses) {

                    String tlast_seen=null, tfriends_count=null, tsubscribers_count=null, tphoto_200=null, tcity=null, tmobile_phone=null, thome_phone=null,
                            trelatives=null, trelation=null, tpersonal=null, tconnections=null, tactivities=null, tinterests=null, tmovies=null, ttv=null, tbooks=null,
                            tgames=null, tabout=null, tquotes=null, tphoto_count=null, tvideo_count=null, tmusic_count=null, tgroups_count=null, tposts_count=null;

                    super.onComplete(responses);
                    Log.d("VkDemoApp", "TakeResp1 " + responses[0].json.toString());
                    Log.d("VkDemoApp", "TakeResp2 " + responses[1].json);
                    userInfo = ((VKList<VKApiUserFull>)responses[0].parsedModel).get(0);
                    String[] arrayPosts = responses[1].json.toString().split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");

                    ...

    }
           @Override
            public void onError(VKError error) {
                Toast.makeText(context, "Error" + error.toString(), Toast.LENGTH_SHORT).show();
            }
        });

    } else
        Log.d("VkDemoApp", "0 rows");
    c.close();

}

选中在没有HTTP请求的情况下启动 - 一切都很好。我确定这是因为HTTP请求但我不知道如何修复它。

VKRequest.getLang

private String getLang() {
    String result = mPreferredLang;
    if (useSystemLanguage) {
        result = VKUIHelper.getApplicationContext().getResources().getConfiguration().locale.getLanguage();
        if (result.equals("uk")) {
            result = "ua";
        }

        if (!Arrays.asList(new String[]{"ru", "en", "ua", "es", "fi", "de", "it"})
                .contains(result)) {
            result = mPreferredLang;
        }
    }
    return result;
}

VKUIHelper.java

public class VKUIHelper {
    private static Activity sTopActivity;
    private static Context  sApplicationContext;

    public static Activity getTopActivity()
    {
        return sTopActivity;
    }
    public static Context getApplicationContext() { return sApplicationContext; }
    /**
     * Call it in onCreate for of activities where you using VK SDK
     * @param activity Your activity
     */
    public static void onCreate(Activity activity)
    {
        if (sTopActivity != activity)
            sTopActivity = activity;
        if (sApplicationContext == null && activity != null) {
            sApplicationContext = activity.getApplicationContext();
        }
    }

    /**
     * Call it in onResume for of activities where you using VK SDK
     * @param activity Your activity
     */
    public static void onResume(Activity activity)
    {
        if (sTopActivity != activity)
            sTopActivity = activity;
        if (sApplicationContext == null && activity != null) {
            sApplicationContext = activity.getApplicationContext();
        }
    }

    /**
     * Call it in onDestroy for of activities where you using VK SDK
     * @param activity Your activity
     */
    public static void onDestroy(Activity activity)
    {
        if (sTopActivity == activity)
            sTopActivity = null;
    }

    /**
     * Call it in onActivityResult of all activities where you using VK SDK
     * @param requestCode Request code for startActivityForResult
     * @param resultCode Result code of finished activity
     * @param data Result data
     * @deprecated Use onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) instead
     */
    public static void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        onActivityResult(sTopActivity, requestCode, resultCode, data);
    }

    /**
     * Call it in onActivityResult of all activities where you using VK SDK
     * @param requestCode Request code for startActivityForResult
     * @param resultCode Result code of finished activity
     * @param data Result data
     */
    public static void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        sTopActivity = activity;
        if (requestCode == VKSdk.VK_SDK_REQUEST_CODE) {
            VKSdk.processActivityResult(requestCode, resultCode, data);
        }
    }
}

0 个答案:

没有答案