如何使用JSON对象解析JSON数据&从服务到android中的sqlite数据库的JSON数组?

时间:2014-08-06 13:50:42

标签: android json sqlite

当我第一次安装Android应用程序时,我试图将数据从服务存储到设备上的本地sqlite数据库中。但调试中的应用程序在logcat中的异步任务中给出致命异常,应用程序突然关闭。任何有解释的帮助都可以,我还在学习android开发。以下是我的代码&服务参考,谢谢。请进一步帮助我如何将这些数据存储在本地sqlite数据库中。

来自服务的JSON响应:

{"GetData":[{"Email":"hans@gmail.com",
"FirstName":"Hansel",
"GroupName":"FB",
"HomeAddress":"E-8\/9, UGF, Second Suite, NY",
"ID":"hans@gmail.com",
"LastName":"Gretel",
"MobileNumbers":["+128990068","+12399884"],
"Name":"Hansel Gretel",
"OfficeAddress":"D-82, Second Floor, London Boulevard, NJ",
"TelephoneNumbers":["01312300534","+128790084"]},

{"Email":"ishyk@gmail.com",
"FirstName":"Airina",
"GroupName":"FB",
"HomeAddress":"E-8\/9, UGF, Second Suite, NY",
"ID":"ishyk@gmail.com",
"LastName":"Shyk",
"MobileNumbers":["+1 (287) 304-5115","+1 (285) 304-5115"],
"Name":"Airina Shyk",
"OfficeAddress":"D-82, Third Floor, London Boulevard, NJ",
"TelephoneNumbers":["+1 (125) 367-6085","+1 (125) 367-6087"]}]}

我的MainActivity类:

package com.fb.jsondata;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class MainActivity extends ListActivity {

    private ProgressDialog pDialog;

    // URL to get contacts JSON
    private static String url = "http://fb.mysite.com/CDService/CDService.svc/GetMyData///johndow@gmail.com";

    // JSON Node names
    private static final String TAG_CONTACTS = "GetData";
    private static final String TAG_ID = "ID";
    private static final String TAG_FIRST_NAME = "FirstName";
    private static final String TAG_LAST_NAME = "LastName";
    private static final String TAG_NAME = "Name";
    private static final String TAG_EMAIL = "Email";
    private static final String TAG_HOME_ADDRESS = "HomeAddress";
    private static final String TAG_OFFICE_ADDRESS = "OfficeAddress";
    private static final String TAG_GROUP_NAME = "GroupName";
    private static final String TAG_PHONE = "TelephoneNumbers";
    private static final String TAG_PHONE_MOBILE = "MobileNumbers";

    // contacts JSONArray
    JSONArray contacts = null;

    // mobile JSONArray
    JSONArray mobiles = null;

    // telephone JSONArray
    JSONArray telephones = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList;

    ArrayList<String> myMob;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        contactList = new ArrayList<HashMap<String, String>>();

        ListView lv = getListView();

        // Listview on item click listener
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String name = ((TextView) view.findViewById(R.id.name))
                        .getText().toString();
                String cost = ((TextView) view.findViewById(R.id.email))
                        .getText().toString();
                String description = ((TextView) view.findViewById(R.id.mobile))
                        .getText().toString();

                // Starting single contact activity
                Intent in = new Intent(getApplicationContext(),
                        SingleContactActivity.class);
                in.putExtra(TAG_NAME, name);
                in.putExtra(TAG_EMAIL, cost);
                in.putExtra(TAG_PHONE_MOBILE, description);
                startActivity(in);

            }
        });

        // Calling async task to get json
        new GetContacts().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     * */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    contacts = jsonObj.getJSONArray(TAG_CONTACTS);

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);
                        String email = c.getString(TAG_EMAIL);
                        String address = c.getString(TAG_HOME_ADDRESS);
                        String address1 = c.getString(TAG_OFFICE_ADDRESS);
                        String gender = c.getString(TAG_GROUP_NAME);

                        // Phone node is JSON Object
                        mobiles = c.getJSONArray(TAG_PHONE_MOBILE);                        
                        for(int n=0;n<mobiles.length();n++)
                        {
                              String mobile = (String) mobiles.get(n);
                              myMob.add(mobile);
                        }

                        // tmp hashmap for single contact
                        HashMap<String, String> contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        contact.put(TAG_ID, id);
                        contact.put(TAG_NAME, name);
                        contact.put(TAG_EMAIL, email);
                        contact.put(TAG_PHONE_MOBILE, myMob.toString());

                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, contactList,
                    R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
                            TAG_PHONE_MOBILE }, new int[] { R.id.name,
                            R.id.email, R.id.mobile });

            setListAdapter(adapter);
        }

    }
}

服务处理程序类:

package com.fb.jsondata;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class ServiceHandler {

    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;

    public ServiceHandler() {

    }

    /**
     * Making service call
     * @url - url to make request
     * @method - http request method
     * */
    public String makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method, null);
    }

    /**
     * Making service call
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     * */
    public String makeServiceCall(String url, int method,
            List<NameValuePair> params) {
        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }

                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);

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

        return response;

    }

}

Logcat响应:

08-06 17:41:27.980: E/AndroidRuntime(362): FATAL EXCEPTION: AsyncTask #1
08-06 17:41:27.980: E/AndroidRuntime(362): java.lang.RuntimeException: An error occured while executing doInBackground()
08-06 17:41:27.980: E/AndroidRuntime(362):  at android.os.AsyncTask$3.done(AsyncTask.java:200)
08-06 17:41:27.980: E/AndroidRuntime(362):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-06 17:41:27.980: E/AndroidRuntime(362):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-06 17:41:27.980: E/AndroidRuntime(362):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-06 17:41:27.980: E/AndroidRuntime(362):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-06 17:41:27.980: E/AndroidRuntime(362):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
08-06 17:41:27.980: E/AndroidRuntime(362):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
08-06 17:41:27.980: E/AndroidRuntime(362):  at java.lang.Thread.run(Thread.java:1096)
08-06 17:41:27.980: E/AndroidRuntime(362): Caused by: java.lang.ClassCastException: java.lang.String
08-06 17:41:27.980: E/AndroidRuntime(362):  at com.bnk.jsondata.MainActivity$GetContacts.doInBackground(MainActivity.java:160)
08-06 17:41:27.980: E/AndroidRuntime(362):  at com.bnk.jsondata.MainActivity$GetContacts.doInBackground(MainActivity.java:1)
08-06 17:41:27.980: E/AndroidRuntime(362):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
08-06 17:41:27.980: E/AndroidRuntime(362):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-06 17:41:27.980: E/AndroidRuntime(362):  ... 4 more
08-06 17:41:30.931: E/WindowManager(362): Activity com.bnk.jsondata.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@45f61928 that was originally added here
08-06 17:41:30.931: E/WindowManager(362): android.view.WindowLeaked: Activity com.bnk.jsondata.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@45f61928 that was originally added here
08-06 17:41:30.931: E/WindowManager(362):   at android.view.ViewRoot.<init>(ViewRoot.java:247)
08-06 17:41:30.931: E/WindowManager(362):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
08-06 17:41:30.931: E/WindowManager(362):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
08-06 17:41:30.931: E/WindowManager(362):   at android.view.Window$LocalWindowManager.addView(Window.java:424)
08-06 17:41:30.931: E/WindowManager(362):   at android.app.Dialog.show(Dialog.java:241)
08-06 17:41:30.931: E/WindowManager(362):   at com.bnk.jsondata.MainActivity$GetContacts.onPreExecute(MainActivity.java:109)
08-06 17:41:30.931: E/WindowManager(362):   at android.os.AsyncTask.execute(AsyncTask.java:391)
08-06 17:41:30.931: E/WindowManager(362):   at com.bnk.jsondata.MainActivity.onCreate(MainActivity.java:94)
08-06 17:41:30.931: E/WindowManager(362):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-06 17:41:30.931: E/WindowManager(362):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
08-06 17:41:30.931: E/WindowManager(362):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
08-06 17:41:30.931: E/WindowManager(362):   at android.app.ActivityThread.access$2300(ActivityThread.java:125)
08-06 17:41:30.931: E/WindowManager(362):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
08-06 17:41:30.931: E/WindowManager(362):   at android.os.Handler.dispatchMessage(Handler.java:99)
08-06 17:41:30.931: E/WindowManager(362):   at android.os.Looper.loop(Looper.java:123)
08-06 17:41:30.931: E/WindowManager(362):   at android.app.ActivityThread.main(ActivityThread.java:4627)
08-06 17:41:30.931: E/WindowManager(362):   at java.lang.reflect.Method.invokeNative(Native Method)
08-06 17:41:30.931: E/WindowManager(362):   at java.lang.reflect.Method.invoke(Method.java:521)
08-06 17:41:30.931: E/WindowManager(362):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-06 17:41:30.931: E/WindowManager(362):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-06 17:41:30.931: E/WindowManager(362):   at dalvik.system.NativeStart.main(Native Method)

我已经添加了logcat,看看。

2 个答案:

答案 0 :(得分:0)

我可以在

的日志中看到 ClassCastException
for(int n=0;n<mobiles.length();n++)
  {
    String mobile = (String) mobiles.get(n);
    myMob.add(mobile);
  }

请改用mobiles.getString(n)。希望这会对你有所帮助。

答案 1 :(得分:0)

我很惊讶你没有获得nullpointerexception ...因为你没有初始化myMob ArrayList .... 我建议你首先初始化ArrayList myMob ...然后查看结果..