duancong7358 2015-07-30 21:26
浏览 92

使用循环从android sqlite解析列表到远程数据库

Part of the android app I am building requires me to save a list of users in an sqlite database. The user can then enter an activity which shows the list of users currently stored in the sqlite datebase within a listview.

I have then tried to implement a function to sync this list of users to a remote database, using Async Tasks, JSON, and a PHP service, by using a FOR LOOP to cycle through the database tables 'users'.

The problem is that the sync only works for the first item in the list. After this has been passed through to the remote database, the activity crashes. The log reads:

E/JSON Parser﹕ Error parsing data org.json.JSONException: Value data of type java.lang.String cannot be converted to JSONObject

E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #3 Process: example.prguru.com.pi_prototype_30, PID: 5139 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:304) ...

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference at example.prguru.com.pi_prototype_30.ShowAdmins$syncUser.doInBackground(ShowAdmins.java:137) at example.prguru.com.pi_prototype_30.ShowAdmins$syncUser.doInBackground(ShowAdmins.java:87)

Line 137 in the java code is:

 Log.d("Sync Attempt", jobj.toString());

PHP CODE:

require_once 'config.php';

if(!empty($_POST)){
$row = $_POST['table_id'];
$type = $_POST['type'];
$id_num = $_POST['id_number'];
$name = $_POST['name'];
$email  = $_POST['email'];
$course = $_POST['course'];
$password = $_REQUEST['password'];

$ins = mysql_query("INSERT INTO pi_prototype_inventory_30.users (table_id, type, id_number, name, email, course, password) 
VALUES('$row','$type','$id_num','$name', '$email', '$course', '$password')");

if(!$ins)
{
    echo (mysql_error());
}
else
{
    echo ("data inserted");
}
}
else {
echo (mysql_error());
}

SYNC CLASS:

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        // Check for success tag
        int success;

        DBHandler dbAdapter = DBHandler.getDBHandlerInstance(getApplicationContext());
        try {
            dbAdapter.createDataBase();
        } catch (IOException e) {
            Log.i("*** select ", e.getMessage());
        }

        dbAdapter.openDataBase();
        String query = "SELECT * FROM users";
        ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
        dbAdapter.close();

        try {

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(7);
            for (int i = 0; i < stringList.size(); i++) {
                ArrayList<String> list = stringList.get(i);
                nameValuePairs.add(new BasicNameValuePair("table_id", list.get(0)));
                nameValuePairs.add(new BasicNameValuePair("type", list.get(1)));
                nameValuePairs.add(new BasicNameValuePair("id_number", list.get(2)));
                nameValuePairs.add(new BasicNameValuePair("name", list.get(3)));
                nameValuePairs.add(new BasicNameValuePair("email", list.get(4)));
                nameValuePairs.add(new BasicNameValuePair("course", list.get(5)));
                nameValuePairs.add(new BasicNameValuePair("password", list.get(6)));

                Log.d("Request!", "Starting!");

                jobj = jsonParser.makeObjHttpRequest(REG_URL, "POST", nameValuePairs);

                Log.d("Sync Attempt", jobj.toString());

            }//forLoop
                success = jobj.getInt(TAG_SUCCESS);
                if (success == 1){
                    Log.d("SYNCED!", jobj.toString());
                    return jobj.getString(TAG_MESSAGE);
                }
                else {
                    Log.d("Sync failure!", jobj.getString(TAG_MESSAGE));
                    return jobj.getString(TAG_MESSAGE);
                }



        } catch (JSONException e){
            e.printStackTrace();
        }
        return null;
    }//doInBackground

JSON PARSER CLASS:

public JSONObject makeObjHttpRequest(String url, String method,
                                  List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method.equals("POST")){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method.equals("GET")){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("
");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        Log.i("tagconvertstr", "["+json+"]");
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

Do I need to implement some sort of loop in my PHP code so it accepts more than one entry from the list? I don't know how I would go about coding that because I will never be sure how many entries will need to be synced at any one time. Or is the problem within the java code itself? I'm not quite sure how to make sense of the errors presented in the log.

  • 写回答

1条回答 默认 最新

  • du4629 2015-08-03 16:28
    关注

    Your parser is returning a null object. Logcat is pretty clear about this. First there is this message:

    E/JSON Parser﹕ Error parsing data org.json.JSONException: Value data of type java.lang.String cannot be converted to JSONObject
    

    This matches exactly what's in one of your catch blocks in the parser:

    try {
        Log.i("tagconvertstr", "["+json+"]");
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString()); // <- HERE
    }
    

    If an exception is thrown in this block, jObj will not be assigned. If you want the parser to never return null, then you need to assign jObj in the catch block. Otherwise, your other code needs to check that the value returned is not null before trying to use it.

    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?