2016-11-16 73 views
-5

http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings」解析數據 - 鏈接,蔭試圖解析我想從以下鏈接

public class MainActivity extends AppCompatActivity { 

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


     final Button GetServerData = (Button) findViewById(R.id.GetServerData); 
     GetServerData.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       // WebServer Request URL 
       String serverURL = "http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings"; 

       // Use AsyncTask execute Method To Prevent ANR Problem 
       new LongOperation().execute(serverURL); 
      } 
     }); 
    } 
     private class LongOperation extends AsyncTask<String, Void, Void> { 
      private final HttpClient Client = new DefaultHttpClient(); 
      private String Content; 
      private String Error = null; 
      private ProgressDialog Dialog = new ProgressDialog(MainActivity.this); 
      String data = ""; 
      TextView uiUpdate = (TextView) findViewById(R.id.textView2); 
      TextView jsonParsed = (TextView) findViewById(R.id.textView3); 
      int sizeData = 0; 
      EditText serverText = (EditText) findViewById(R.id.textView); 

      protected void onPreExecute() { 
       // NOTE: You can call UI Element here. 

       //Start Progress Dialog (Message) 

       Dialog.setMessage("Please wait.."); 
       Dialog.show(); 

       try { 
        // Set Request parameter 
        data += "&" + URLEncoder.encode("data", "UTF-8") + "=" + serverText.getText(); 

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

      } 

      @Override 
      protected Void doInBackground(String... urls) { 
       /************ Make Post Call To Web Server ***********/ 
       BufferedReader reader = null; 
       // Send data 
       try { 
        // Defined URL where to send data 
        URL url = new URL(urls[0]); 
        // Send POST data request 
        URLConnection conn = url.openConnection(); 
        conn.setDoOutput(true); 
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
        wr.write(data); 
        wr.flush(); 

        // Get the server response 
        reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
        StringBuilder sb = new StringBuilder(); 
        String line = null; 
        // Read Server Response 
        while ((line = reader.readLine()) != null) { 
         // Append server response in string 
         sb.append(line + ""); 
        } 
        // Append Server Response To Content String 
        Content = sb.toString(); 
       } catch (Exception e) { 
        Error = e.getMessage(); 
       } finally { 
        try { 

         reader.close(); 
        } catch (Exception ex) { 
        } 
       } 
       return null; 
      } 


      protected void onPostExecute(Void unused) { 
       // NOTE: You can call UI Element here. 

       // Close progress dialog 
       Dialog.dismiss(); 
       if (Error != null) { 

        uiUpdate.setText("Output : " + Error); 

       }else 
       { 
        //Show Response Json Onscreen(Activity) 
        uiUpdate.setText(Content); 

        /****************** Start Parse Response JSON Data *************/ 

        String OutputData = ""; 
        try { 
         JSONObject jsono = new JSONObject(Content); 
         JSONObject mainObject = jsono.getJSONObject("data"); 
         JSONArray jsonArray = mainObject.getJSONArray("standing"); 
         for (int i = 0; i < jsonArray.length(); i++) { 
          JSONObject object = jsonArray.getJSONObject(i); 
          // get details2 JSONObject 
          String position = object.optString("position").toString(); 
          String team = object.optString("team").toString(); 

          OutputData += "Position: " + position + " " 
            + "Team Name  : " + team + " "; 
         } 
         /****************** End Parse Response JSON Data *************/ 
         //Show Parsed Output on screen (activity) 
         jsonParsed.setText(OutputData); 
        }catch (JSONException e) { 

         e.printStackTrace(); 
        } 

       } 
      } 

     } 

} 

**,我創建英超應用程序,它顯示需要的英超聯賽中所有提交的數據風扇。正如Iam剛剛對此解釋的,我對json解析和從apis獲取數據感到困惑。所以任何人都可以向我解釋如何更改我的代碼或一些可以幫助我糾正它的鏈接。

上面給出的主要活動我的Java代碼**

+0

甲你能從服務器獲取數據嗎? – AndroidHacker

+0

定義*我越來越困惑於json解析*。你不明白什麼?什麼是問題? – Selvin

+0

你面對的錯誤是什麼? – SaravInfern

回答

0

謝謝大家幫忙。但是我通過互聯網找到了我的答案。在這裏,我使用VOLLEY來調用鏈接。

JSON解析器類

public class ParseJSON { 

     public static String[] position1; 
     public static String[] team; 
     public static String[] points; 

     public static final String JSON_ARRAY = "data"; 

     public static final String CHILD_ARRAY = "standings"; 

     public static final String KEY_ID = "position"; 
     public static final String KEY_NAME = "team"; 

     private JSONObject users = null; 
     private JSONArray user2=null; 
     private JSONObject user3=null; 

     private String json; 

     public ParseJSON(String json){ 
      this.json = json; 
     } 
     protected void parseJSON() { 
      JSONObject jsonObject = null; 
      try { 
       jsonObject = new JSONObject(json); 
       users = jsonObject.getJSONObject(JSON_ARRAY); 
       try { 
        user2=users.getJSONArray(CHILD_ARRAY); 
        position1 = new String[user2.length()]; 
        team = new String[user2.length()]; 
        points=new String[user2.length()]; 
        for (int i = 0; i < user2.length(); i++) { 

         JSONObject jo = user2.getJSONObject(i); 
         try { 
          user3=jo.getJSONObject("overall"); 
          points[i] = user3.getString("points"); 
          System.out.println("Message me: "+points[i]); 
         }catch (Exception e) 
         { 
          e.printStackTrace(); 
         } 
         position1[i] = jo.getString(KEY_ID); 
         team[i] = jo.getString(KEY_NAME); 
         System.out.println("Message me: "+position1[i]); 
         System.out.println("Message me: "+team[i]); 


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

主要活動類

public class MainActivity extends AppCompatActivity implements View.OnClickListener { 


     public static final String JSON_URL="http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings"; 
     private Button buttonGet; 
     private ListView listView; 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 
      buttonGet = (Button) findViewById(R.id.buttonGet); 
      buttonGet.setOnClickListener(this); 
      listView = (ListView) findViewById(R.id.listView); 
     } 

     @Override 
     public void onClick(View v) { 
      sendRequest(); 
     } 
     private void sendRequest() { 
      final StringRequest stringRequest = new StringRequest(JSON_URL, 
        new Response.Listener<String>() { 
         @Override 
         public void onResponse(String response) { 
          showJSON(response); 

         } 
        }, 
        new Response.ErrorListener() { 
         @Override 
         public void onErrorResponse(VolleyError error) { 
          Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show(); 
         } 
        }); 
      RequestQueue requestQueue = Volley.newRequestQueue(this); 
      requestQueue.add(stringRequest); 
     } 
     private void showJSON(String json){ 
      ParseJSON pj = new ParseJSON(json); 
      pj.parseJSON(); 
      CustomList cl = new CustomList(this, ParseJSON.position1,ParseJSON.team,ParseJSON.points); 
      listView.setAdapter(cl); 
     }  
    } 

自定義類添加DATAS到列表視圖

public class CustomList extends ArrayAdapter<String> { 

    private String[] position1; 
    private String[] team; 
    private String[] points; 
    private Activity context; 

    public CustomList(Activity context, String[] position1, String[] team, String[] points) { 
     super(context, R.layout.list_view_layout, position1); 
     this.context = context; 
     this.position1 = position1; 
     this.team = team; 
     this.points = points; 

    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     LayoutInflater inflater = context.getLayoutInflater(); 
     View listViewItem = inflater.inflate(R.layout.list_view_layout, null, true); 
     TextView pos1 = (TextView) listViewItem.findViewById(R.id.position1); 
     TextView teamname = (TextView) listViewItem.findViewById(R.id.teamname); 
     TextView points1 = (TextView) listViewItem.findViewById(R.id.points); 


     pos1.setText("Position: "+position1[position]); 
     teamname.setText("Team: "+team[position]); 
     points1.setText("Points: "+points[position]); 


     return listViewItem; 
    } 
} 
-1

第1步:使用Retroft + RxJava異步API調用

第2步:使用GSON序列化和反序列化。

步驟3:使用JSON到POJO有一個模型類

簡化代碼。