如何解析Android上的JSON?

时间:2014-07-31 18:47:29

标签: php android mysql json

我正在阅读数据库并将其解析为Android上的listview。基本上我已经使用PHP和MySQL设置了一个Web服务,现在我正在尝试将数据解析到android列表视图中。我收到以下错误:

07-31 14:24:55.570: E/AndroidRuntime(846): FATAL EXCEPTION: AsyncTask #1
07-31 14:24:55.570: E/AndroidRuntime(846): Process: com.example.test, PID: 846
07-31 14:24:55.570: E/AndroidRuntime(846): java.lang.RuntimeException: An error occured     while executing doInBackground()
07-31 14:24:55.570: E/AndroidRuntime(846):  at     android.os.AsyncTask$3.done(AsyncTask.java:300)
07-31 14:24:55.570: E/AndroidRuntime(846):  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
07-31 14:24:55.570: E/AndroidRuntime(846):  at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
07-31 14:24:55.570: E/AndroidRuntime(846):  at java.util.concurrent.FutureTask.run(FutureTask.java:242)
07-31 14:24:55.570: E/AndroidRuntime(846):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-31 14:24:55.570: E/AndroidRuntime(846):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-31 14:24:55.570: E/AndroidRuntime(846):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-31 14:24:55.570: E/AndroidRuntime(846):  at java.lang.Thread.run(Thread.java:841)
07-31 14:24:55.570: E/AndroidRuntime(846): Caused by: java.lang.NullPointerException
07-31 14:24:55.570: E/AndroidRuntime(846):  at com.example.test.Menu.updateJSONdata(Menu.java:107)
07-31 14:24:55.570: E/AndroidRuntime(846):  at com.example.test.Menu$LoadComments.doInBackground(Menu.java:189)
07-31 14:24:55.570: E/AndroidRuntime(846):  at com.example.test.Menu$LoadComments.doInBackground(Menu.java:1)
07-31 14:24:55.570: E/AndroidRuntime(846):  at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-31 14:24:55.570: E/AndroidRuntime(846):  at java.util.concurrent.FutureTask.run(FutureTask.java:237)

主要课程是:

package com.example.test;

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.os.AsyncTask;
import android.os.Bundle;
 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;

public class Menu extends ListActivity{ 

//Progress Dialog
private ProgressDialog pDialog;

// php read comments script


// testing on Emulator:
private static final String READ_COMMENTS_URL = "http://10.0.2.2:1337/webservice/lib.php";


// JSON IDS:
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_CALLING = "calling";    //calling
private static final String TAG_ACCESSION = "accession";    //accession
private static final String TAG_AUTHOR = "author";  //author


// An array of all of our comments
private JSONArray mComments = null;
// manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mCommentList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // note that use read_comments.xml instead of our single_post.xml
    setContentView(R.layout.menu);
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    // loading the comments via AsyncTask
    new LoadComments().execute();
}

/*public void addComment(View v) {
    Intent i = new Intent(ReadComments.this, AddComment.class);
    startActivity(i);
} */

/**
 * Retrieves recent post data from the server.
 */
public void updateJSONdata() {


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


    JSONParser jParser = new JSONParser();

    JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);


    try {


        mComments = json.getJSONArray(TAG_POSTS);

        // looping through all posts according to the json object returned
        for (int i = 0; i < mComments.length(); i++) {
            JSONObject c = mComments.getJSONObject(i);

            // gets the content of each tag
            String title = c.getString(TAG_TITLE);
            String author = c.getString(TAG_AUTHOR);
            String accession = c.getString(TAG_ACCESSION);
            String calling = c.getString(TAG_CALLING);

            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            map.put(TAG_TITLE, title);
            map.put(TAG_AUTHOR, author);
            map.put(TAG_ACCESSION, accession);
            map.put(TAG_CALLING, calling);

            // adding HashList to ArrayList
            mCommentList.add(map);


        }

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

/**
 * Inserts the parsed data into the listview.
 */
private void updateList() {

    ListAdapter adapter = new SimpleAdapter(Menu.this, mCommentList,
            R.layout.onepost, new String[] { TAG_TITLE, TAG_AUTHOR,
                    TAG_ACCESSION, TAG_CALLING }, new int[] { R.id.title, R.id.author,
                    R.id.accession, R.id.calling });


    setListAdapter(adapter);


    ListView lv = getListView();    
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {


        }
    });
}

public class LoadComments extends AsyncTask<Void, Void, Boolean> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Menu.this);
        pDialog.setMessage("Loading Comments...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... arg0) {
        updateJSONdata();
        return null;

    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        pDialog.dismiss();
        updateList();
    }
     }


   }

1 个答案:

答案 0 :(得分:0)

我已完成2个课程以获取http请求结果。非常容易使用。

BasicHttpRequest.java

public class BasicHttpRequest
{
    private JSONObject      _result         = null;
    private int             _err            = -1;
    private String          _errMessage     = null;
    private HttpRequestBase _request        = null;
    private String          _requestError   = null;
    private UrlBuilder      _urlBuilder     = null;

    public BasicHttpRequest(RequestType requestType, UrlBuilder urlBuilder)
    {
        this._urlBuilder = urlBuilder;
        if (requestType.equals(RequestType.POST))
            this.createPostRequest();
        if (requestType.equals(RequestType.GET))
            this.createGetRequest();
    }

    private void createPostRequest()
    {
        HttpPost post = new HttpPost(this._urlBuilder.getUrlBase());

        try
        {
            post.setEntity(new UrlEncodedFormEntity(this._urlBuilder.getArrayList()));
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
            return;
        }
        this._request = post;
    }

    private void createGetRequest()
    {
        HttpGet get = new HttpGet(this._urlBuilder.getUrl());

        this._request = get;
    }

    /**
     * This function executes the request passed by the constructor.
     * @return Returns false if an error occurred, true otherwise. For more informations about the error, use getRequestError.
     */
    public boolean executeRequest()
    {
        InputStream iStream = null;
        String result = "";

        try
        {
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(this._request);
            HttpEntity entity = response.getEntity();
            iStream = entity.getContent();
        } catch (Exception e)
        {
            Log.e("ReqError", "[Error in HTTP Connection] : " + e.toString());
            this._requestError = ErrorMessage.CONNECTION_ERROR;
            return false;
        }

        try
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(iStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null)
                sb.append(line + "\n");
            result = sb.toString();
        } catch (Exception e)
        {
            Log.e("ConversionError", "[Error while converting result] : " + e.toString());
            this._requestError = ErrorMessage.DATA_ERROR;
            return false;
        }

        JSONObject jObject;
        try
        {
            jObject = new JSONObject(result);
            this._err = jObject.getInt("err");
            this._errMessage = jObject.getString("errMessage");

        } catch (JSONException e)
        {
            Log.e("JSONError", "[Error parsing data] : " + e.toString());
            this._requestError = ErrorMessage.DATA_ERROR;
            return false;
        }
        this._result = jObject;
        return true;
    }

    public String getValueForKey(String key)
    {
        String value = null;

        if (this._result == null)
            return null;
        try
        {
            value = this._result.getString(key);
        } catch (JSONException e)
        {
            e.printStackTrace();
            return null;
        }
        if (value.equals("null"))
            return null;
        return value;
    }

    public boolean hasError()
    {
        if (this._err == 0)
            return false;
        return true;
    }

    public String getErrMessage()
    {
        return this._errMessage;
    }

    public JSONObject getResult()
    {
        return this._result;
    }

    /**
     * This function gives you the reason of the request error.
     * @return Returns an error message if an error occurred during the request execution, null otherwise.
     */
    public String getRequestError()
    {
        return this._requestError;
    }
}

UrlBuilder.java

public class UrlBuilder
{
    private String _urlBase;
    private HashMap<String, String> _urlArgs;

    public UrlBuilder(String urlBase)
    {
        this._urlArgs = new HashMap<String, String>();
        this._urlBase = urlBase;
    }

    public UrlBuilder addArgument(String name, String value)
    {
        this._urlArgs.put(name, value);
        return this;
    }

    public void removeArgument(String name)
    {
        this._urlArgs.remove(name);
    }

    public boolean argumentExists(String name)
    {
        return this._urlArgs.containsKey(name);
    }

    public String getUrl()
    {
        int i = 0;
        String url = this._urlBase;

        for (Map.Entry<String, String> entry : this._urlArgs.entrySet())
        {
            url += (i == 0 ? "?" : "&");
            try
            {
                url += URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8");
            } catch (UnsupportedEncodingException e)
            {
                Log.e("UrlEncoder", "Error while trying to encode URL");
                e.printStackTrace();
            }
            i++;
        }
        return url;
    }

    public String getUrlBase()
    {
        return this._urlBase;
    }

    public List<NameValuePair> getArrayList()
    {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        for (Map.Entry<String, String> entry : this._urlArgs.entrySet())
        {
            nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return nameValuePairs;
    }
}

只需使用您的服务器网址来实例化UrlBuilder,例如&#34; http://api.yoursite.fr/page&#34;并使用方法addArgument添加您的参数。然后,使用先前的UrlBuilder实例和请求类型(它只是一个带有POST和GET的枚举)实例化BasicHttpRequest对象。最后,使用BasicHttpRequest方法获取结果getValueForKey。

问我是否有任何问题。

希望它有所帮助。