使用JSON从api获取信息

时间:2012-07-19 11:54:21

标签: android json

我从这个api中读到了麻烦

http://api.xhanch.com/islamic-get-prayer-time.php?lng=67&lat=24&yy=2012&mm=7&gmt=5&m=json

这是我的代码:

new Read().execute("sunrise");

public JSONObject retrieveInfo(String user) throws ClientProtocolException,IOException, JSONException {
        StringBuilder url = new StringBuilder(URL);
        url.append(user);

        HttpGet get = new HttpGet(url.toString());
        HttpResponse r = client.execute(get);
        HttpEntity e = r.getEntity();
        String data = EntityUtils.toString(e);
        JSONArray timeline = new JSONArray(data);
        JSONObject last = timeline.getJSONObject(1);
        return last;
    }

    public class Read extends AsyncTask<String, Integer, String> {

        protected String doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            try {
                json = retrieveInfo("");
                return json.getString(arg0[0]);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

此方法始终返回空字符串,而不是我需要的信息。

3 个答案:

答案 0 :(得分:3)

这里有一个工作示例

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;

public class GetPrayerTime extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.custom_component);

        new Read().execute("sunrise");

    }

    public JSONObject retrieveInfo(String user) throws ClientProtocolException,
            IOException, JSONException {
        StringBuilder url = new StringBuilder(
                "http://api.xhanch.com/islamic-get-prayer-time.php?lng=67&lat=24&yy=2012&mm=7&gmt=5&m=json");
        url.append(user);

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet get = new HttpGet(url.toString());
        HttpResponse r = httpclient.execute(get);
        HttpEntity e = r.getEntity();
        String data = EntityUtils.toString(e);
        JSONObject timeline = new JSONObject(data);
        return timeline.getJSONObject("1");
    }

    private class Read extends AsyncTask<String, Integer, String> {

        ProgressDialog pd = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = new ProgressDialog(GetPrayerTime.this);
            pd.setTitle("Downloading...");
            pd.setMessage("Please wait...");
            pd.setCancelable(false);
            pd.show();

        }

        protected String doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            try {
                JSONObject json = retrieveInfo("");
                return json.getString(arg0[0]);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String status) {
            super.onPostExecute(status);
            pd.dismiss();

            AlertDialog alertDialog = new AlertDialog.Builder(
                    GetPrayerTime.this).create();
            alertDialog.setTitle("Prayer time");
            alertDialog.setMessage(status);
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    GetPrayerTime.this.finish();
                    dialog.cancel();
                }
            });
            alertDialog.setIcon(android.R.drawable.ic_dialog_info);
            alertDialog.show();

        }

    }

}

答案 1 :(得分:0)

JSON响应中没有数组,您可能需要:

JSONObject timeline = new JSONObject (data);
JSONObject last = timeline.getJSONObject("1");

答案 2 :(得分:0)

This link可能对您有所帮助......非常简单但有效地解释了。

public class ParseJSON extends Activity {

/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    String readTwitterFeed = readTwitterFeed();
    try {
        JSONArray jsonArray = new JSONArray(readTwitterFeed);
        Log.i(ParseJSON.class.getName(),
                "Number of entries " + jsonArray.length());
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Log.i(ParseJSON.class.getName(), jsonObject.getString("your_text"));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public String readTwitterFeed() {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet("http://xhanch.com/api/islamic-get-prayer-time.php?lng=67&lat=24&yy=2012&mm=7&gmt=5&m=json");
    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            Log.e(ParseJSON.class.toString(), "Failed to download file.");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return builder.toString();
}
} 

试试这个......