2014-12-02 109 views
0

我想在Android中执行JSON项目。这是我的代码。从URL解析Android JSON

由于某些原因,数据在运行时不显示在文本框中。我不确定我在哪里做错了。

这是从那里我试图获取数据的网址:http://cocoalabs.in/demo/ego/index.php/home/read_all_users

我试图抓住4个字符串并将其展示给TextViews

这是我的代码:

MainActivity.Java

public class MainActivity extends Activity 
{ 

static String CocoaInfo="http://cocoalabs.in/demo/ego/index.php/home/read_all_users"; 
static String clfName = ""; 
static String cllName = ""; 
static String clLocation = ""; 
static String clPh1 = ""; 


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

    //To perform background tasks, like grabbing info from website and write it to GUI 
    new MyAsyncTask().execute(); 
} 

public class MyAsyncTask extends AsyncTask<String, String, String> 
{ 

    @Override 
    protected String doInBackground(String... strings) 
    { 
     /*Get HTTP client that scores streaming uploads & Downloads 
     Here download RESTful information from CocoaLabs URL*/ 
     DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams()); 

     /*Use POST method to grab from data from URL*/ 
     HttpPost httpPost = new HttpPost(CocoaInfo); 

     /*Define type of service we're using - JSON service*/ 
     httpPost.setHeader("Content-type", "application/json"); 

     /*To Read data from URL*/ 
     InputStream inputStream = null; 

     /*To hold all the data we get from URL*/ 
     String result = null; 

     try 
     { 
      /*Asking for a response from the web service*/ 
      HttpResponse response = httpClient.execute(httpPost); 

      /*Has the content from URL along with header and other info*/ 
      HttpEntity entity = response.getEntity(); 

      /*Get the main content from the URL*/ 
      inputStream = entity.getContent(); 

      /*Read data from the stream until buffer is full. Helps to grab in bunch*/ 
      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"),8); 

      /*Creating StringBuilder to store the read data*/ 
      StringBuilder theStringBuilder = new StringBuilder(); 

      /*For storing the read line*/ 
      String line = null; 

      /*Read all the data from buffer until nothing is left*/ 
      while((line = reader.readLine())!=null) 
      { 
       /*Append each line to the Builder object*/ 
       theStringBuilder.append(line + "\n"); 
      } 

      /*After finishing reading all the data*/ 
      result = theStringBuilder.toString(); 

     } 

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

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

     finally 
     { 
      try 
      { 
       /*Close the InputStream*/ 
       if (inputStream!=null) 
        inputStream.close(); 
      } 
      catch (IOException e) 
      { 
       e.printStackTrace(); 
      } 
     } 

     /*Create JSON object to hold a bunch of key-value pairs from the JSON source*/ 
     JSONObject jsonObject; 

     /*To print all the information we downloaded in the LogCat for debugging*/ 
     Log.v("JSONParser RESULT ", result); 


     try 
     { 
      /*Get the JSON object with all the data*/ 
      jsonObject = new JSONObject(result); 

      clfName = jsonObject.getString("fname"); 
      cllName = jsonObject.getString("lname"); 
      clLocation = jsonObject.getString("location"); 
      clPh1 = jsonObject.getString("ph1"); 

      Log.v("JSONParser RESULT", clfName); 
      Log.v("JSONParser RESULT", cllName); 
      Log.v("JSONParser RESULT", clLocation); 
      Log.v("JSONParser RESULT", clPh1); 

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

     return result; 

    } 

    //This method is called after all background tasks are done 
    /*Writes all the information to the TextViews layout*/ 
    @Override 
    protected void onPostExecute(String result) 
    { 
     /*Find the buttons on the screen*/ 
     TextView fNameTV = (TextView) findViewById(R.id.fNameTV); 
     TextView lNameTV = (TextView) findViewById(R.id.lNameTV); 
     TextView locationTV = (TextView) findViewById(R.id.locationTV); 
     TextView ph1TV = (TextView) findViewById(R.id.ph1TV); 

     /*Change the value to be displayed on TextViews*/ 
     fNameTV.setText("First Name is" +clfName); 
     lNameTV.setText("Last Name is" +cllName); 
     locationTV.setText("Location is" +clLocation); 
     ph1TV.setText("Phone Number is" +clPh1); 

    } 
} 

}

+0

什么是logcat输出 – 2014-12-02 09:20:43

回答

4

尝试类似如下:

try { 
    JSONArray main = new JSONArray(responsestring); 

    for(i=0;i<main.length();i++){ 
    JSONObject mainobj = main.getJSONObject(i); 
    String uid = mainobj.getString("uid"); 
    String uname = mainobj.getString("uname"); 
    } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
} 
+0

谢谢你的罚款答案。这是最简单的解决方法。 :) – George 2014-12-02 09:50:16

+0

将mainobj声明移至循环外 – Rafiq 2014-12-02 10:47:14

5

这是因为给定的JSON是一个数组的不是对象。

你需要,如果转换为阵列之前和迭代它:

JSONArray myArray = new JSONArray(result); 

,而不是

jsonObject = new JSONObject(result); 

要遍历数组的简单的应该这样做:

for(i=0;i<myArray.length();i++){ 
    JSONObject anObjectOfTheArray= myArray.getJSONObject(i); 
    Log.v("CONTENT",anObjectOfTheArray.getString("uname")); 
    } 
+0

是的。谢谢。 :) – George 2014-12-02 09:56:47

0
Actually that url contains JSONARRAY and inside jsonobject 

    To get the jsonobject in the JSON array 

     JSONObject object = jsonarray.getJSONObject(index); 


    To get the values from JSON object 

    Json values should be Key and value pair format 

     JSONObject myJson = new JSONObject(myJsonString); 

     String name = myJson.get("name"); 

    **Example** 

    String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}"; 
     JSONObject jObject = new JSONObject(s); 
     JSONObject menu = jObject.getJSONObject("menu"); 

     Map<String,String> map = new HashMap<String,String>(); 
     Iterator iter = menu.keys(); 
     while(iter.hasNext()){ 
      String key = (String)iter.next(); 
      String value = menu.getString(key); 
      map.put(key,value); 
     } 
**FOR your thing, You have to do like this** 

JSONArray arr = new JSONArray(result); 
JSONObject jObj = arr.getJSONObject(inedx); 
String uid= jObj.getString("uid"); 

call this in iteration for total number of objects. 
-1

使用这个follwing类去g等的JSONObject:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.StatusLine; 
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.json.JSONException; 
import org.json.JSONObject; 

import android.util.Log; 

public class JSONParser { 
    static InputStream is = null; 
    static JSONObject jarray = null; 
    static String json = ""; 
    String result = null; 

    public JSONParser() { 

    } 

    public JSONObject getJSONFromUrl(String url) { 

     StringBuilder builder = new StringBuilder(); 
     HttpClient client = new DefaultHttpClient(); 
     HttpGet httpGet = new HttpGet(url); 
     System.out.println(url); 
     try { 
      System.out.println("httpGet:" + httpGet); 
      HttpResponse response = client.execute(httpGet); 
      System.out.println("response" + response); 
      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); 
        result = builder.toString(); 
        System.out.println(builder.toString()); 

       } 
      } else { 
       Log.e("==>", "Failed to download file"); 
      } 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      jarray = new JSONObject(result); 
     } catch (JSONException e1) { 
      Log.e("JSON Parser", "Error parsing data " + e1.toString()); 
     } 
     // return JSON String 
     return jarray; 

    } 
} 

把下面的代码在你做背景...

JSONObject c = JSONParser.getJSONFromUrl("put your url here"); 

try { 
clfName= c.getString("fname"); 
cllName= c.getString("lname"); 
clLocation= c.getString("location"); 
clph1 = c.getString("ph1"); 

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

我想从您的最终所有的代码都是正确的,但有一些问题,你收到的JSON。你可以在运行你的应用程序后显示logcat消息。我发现它给了Json异常。你需要检查json。