在Android应用程序选项卡活动中请求获取没有params的JSON

时间:2014-11-03 11:19:45

标签: android json

我想在我的Android应用程序中从link获取JSON。如您所见,对象没有像往常一样的参数或名称,我如何检索数据以将其发布到我的应用程序中?

这是我的JSONParser.class

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {
    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "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 == "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 (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } 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 + "\n");
            }
            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 {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

这就是我试图检索并在我的标签内容中放置数据的方式

公共类TabTwo扩展了Activity {

TextView txtType;
TextView txtFilename;
TextView txtOriginal;

// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// Profile json object
JSONObject image;
// Profile JSON url

private static final String IMAGE_URL = "http://dbt.promote.az/getUserFiles.php?user_id=1&type=image";
// ALL JSON node names
private static final String TAG_ID = "id";
private static final String TAG_TYPE = "type";
private static final String TAG_FILENAME = "filename";
private static final String TAG_ORIGINAL = "original";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tab_two);

    txtType = (TextView) findViewById(R.id.type);
    txtFilename = (TextView) findViewById(R.id.filename);
    txtOriginal = (TextView) findViewById(R.id.original);

    // Loading Image in Background Thread
    new LoadImage().execute();
}

/**
 * Background Async Task to Load profile by making HTTP Request
 * */
class LoadImage extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(TabTwo.this);
        pDialog.setMessage("Loading profile ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting Profile JSON
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        // getting JSON string from URL
        JSONObject json = jsonParser.makeHttpRequest(IMAGE_URL, "GET",
                params);

        // Check your log cat for JSON reponse
        Log.d("Profile JSON: ", json.toString());



        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                // Storing each json item in variable
                try {
                    String id = image.getString(TAG_ID);
                    String type = image.getString(TAG_TYPE);
                    String filename = image.getString(TAG_FILENAME);
                    String original = image.getString(TAG_ORIGINAL);


                    // displaying all data in textview
                    txtType.setText(type);
                    txtFilename.setText("Filename: " + filename);
                    txtOriginal.setText("Original: " + original);


                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });

    }

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.tab_two, menu);
    return true;
}

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

您需要从字符串响应

创建JSONArray
JSONArray jArray = new JSONArray(json);

然后检索JSONObjects

for(int i=0;i<jArray.length();i++)
{
    JSONObject obj = jArray.getJSONObject(i);
}

答案 1 :(得分:0)

请尝试这种方式,希望这有助于您解决问题。

而不是从makeHttpRequest获取JSONArray或JSONObject返回String响应:

static String json = "";

public String makeHttpRequest(String url, String method,List<NameValuePair> params) { 
   ......
   ......
   return json;
}

将字符串响应传递给onPostExecute(),该响应来自makeHttpRequest。

protected String doInBackground(String... args) {
   // Building Parameters
   List<NameValuePair> params = new ArrayList<NameValuePair>();

   String response = jsonParser.makeHttpRequest(IMAGE_URL, "GET",params);

   return response;
}

在响应之后准备onPostExecute()中的数据;

protected void onPostExecute(String response) {
    if(pDialog!=null&&pDialog.isShowing()){
         pDialog.dismiss();
    }
    ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
    try{
            JSONArray jsonArray = new JSONArray(response);
            for (int i=0;i<jsonArray.length();i++){
                HashMap<String,String> rowData = new HashMap<String, String>();
                rowData.put("id",jsonArray.getJSONObject(i).getString("id"));
                rowData.put("type",jsonArray.getJSONObject(i).getString("type"));
                rowData.put("filename",jsonArray.getJSONObject(i).getString("filename"));
                rowData.put("extension",jsonArray.getJSONObject(i).getString("extension"));
                rowData.put("original",jsonArray.getJSONObject(i).getString("original"));
                data.add(rowData);
            }

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

     // Use data as per your requirement.
}