Deepzz Deepzz - 18 days ago 8
Android Question

I am trying to parse a data from the following link

"http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings" - Link Which Iam Trying to parse

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();
}

}
}

}

}


**I am Creating a premier league application which shows all the datas needed for a premier league fan. As Iam new to this I am getting confused over json parsing and getting data from apis. So Can anyone Explain to me how to change my code or Some links which would help me correct it.

Above given is my java code of Main Activity.**

Answer

Thank You Everyone for Helping out. But I found my answer from the search over the internet. Here I used VOLLEY to call the link.

JSON PARSER CLASS

 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();
            }
        }
    }

Main Activity Class

 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);
        }    
    }

Custom Class for adding datas to list view

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;
    }
}