Reputation: 157
I am trying to fetch JSON Data from Google spreadsheet but it is not showing up I don't know why.I think My JSON response is not matching with the match class do have a look and help me out
This is my AsyncResult Interface
package com.textview.android.jsonsuccessful;
import org.json.JSONObject;
interface AsyncResult {
void onResult(JSONObject object);
}
This is the class I used to fetch URL data
package com.textview.android.jsonsuccessful;
import android.os.AsyncTask;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadWebpageTask extends AsyncTask<String, Void, String> {
AsyncResult callback;
public DownloadWebpageTask(AsyncResult callback) {
this.callback = callback;
}
@Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to download the requested page.";
}
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
// remove the unnecessary parts from the response and construct a JSON
int start = result.indexOf("{", result.indexOf("{") + 1);
int end = result.lastIndexOf("}");
String jsonResponse = result.substring(start, end);
try {
JSONObject team = new JSONObject(jsonResponse);
callback.onResult(team);
} catch (JSONException e) {
e.printStackTrace();
}
}
private String downloadUrl(String urlString) throws IOException {
InputStream is = null;
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int responseCode = conn.getResponseCode();
is = conn.getInputStream();
String contentAsString = convertStreamToString(is);
return contentAsString;
} finally {
if (is != null) {
is.close();
}
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
This is my mainactivity
package com.textview.android.jsonsuccessful;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final String DEBUG_TAG = "HttpExample";
ArrayList<Team> teams = new ArrayList<Team>();
ListView listview;
Button btnDownload;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listview);
btnDownload = (Button) findViewById(R.id.btnDownload);
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
btnDownload.setEnabled(true);
} else {
btnDownload.setEnabled(false);
}
}
public void buttonClickHandler(View view) {
new DownloadWebpageTask(new AsyncResult() {
@Override
public void onResult(JSONObject object) {
processJson(object);
}
}).execute([google]"https://spreadsheets.google.com/tq?
key=1424bS7kU8nJbHdu4QdoAFdIdWDSnmEnj2NqfMb6rPTU");
}
private void processJson(JSONObject object) {
try {
JSONArray rows = object.getJSONArray("rows");
for (int r = 0; r < rows.length(); ++r) {
JSONObject row = rows.getJSONObject(r);
JSONArray columns = row.getJSONArray("c");
int Code = columns.getJSONObject(0).getInt("v");
String Name = columns.getJSONObject(1).getString("v");
String Father = columns.getJSONObject(3).getString("v");
String Sessional = columns.getJSONObject(4).getString("v");
String Comments = columns.getJSONObject(5).getString("v");
Team team = new Team(Code, Name, Father, Sessional,Comments);
teams.add(team);
}
final TeamsAdapter adapter = new TeamsAdapter(this, R.layout.team, teams);
listview.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is my matching class
package com.textview.android.jsonsuccessful;
public class Team {
private int Code;
private String Name;
private String Father;
private String Sessional;
private String Comments;
public Team(int Code, String Name, String Father, String Sessional, String Comments) {
this.setCode(Code);
this.setName(Name);
this.setFatherName(Father);
this.setSessionalMarks(Sessional);
this.setComments(Comments);
}
public int getCode() {
return Code;
}
public void setCode(int Code) {
this.Code = Code;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getFatherName() {
return Father;
}
public void setFatherName(String FatherName) {
this.Father = FatherName;
}
public String getSessionalMarks() {
return Sessional;
}
public void setSessionalMarks(String SessionalMarks) {
this.Sessional = SessionalMarks;
}
public String getComments() {
return Comments;
}
public void setComments(String Comments) {
this.Comments = Comments;
}
}
This is my adapter
package com.textview.android.jsonsuccessful;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class TeamsAdapter extends ArrayAdapter<Team> {
Context context;
private ArrayList<Team> teams;
public TeamsAdapter(Context context, int textViewResourceId, ArrayList<Team> items) {
super(context, textViewResourceId, items);
this.context = context;
this.teams = items;
}
@Override
public View getView(int Code, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.team, null);
}
Team o = teams.get(Code);
if (o != null) {
TextView Cod = (TextView) v.findViewById(R.id.Code);
TextView Name = (TextView) v.findViewById(R.id.Name);
TextView Father = (TextView) v.findViewById(R.id.Father);
TextView Comments = (TextView) v.findViewById(R.id.Comments);
TextView Sessional = (TextView) v.findViewById(R.id.Sessional);
Cod.setText(String.valueOf(o.getCode()));
Name.setText(String.valueOf(o.getName()));
Father.setText(String.valueOf(o.getFatherName()));
Sessional.setText(String.valueOf(o.getSessionalMarks()));
Comments.setText(String.valueOf(o.getComments()));
}
return v;
}
}
This is my main xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.textview.android.jsonsuccessful.MainActivity">
<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@+id/btnDownload" />
<Button
android:id="@+id/btnDownload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:enabled="false"
android:onClick="buttonClickHandler"
android:text="download table"
/>
</RelativeLayout>`
This is my team.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/Code"
android:text="201"
android:layout_width="0dp"
android:layout_weight=".35"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/Name"
android:text="ankit"
android:layout_width="0dp"
android:layout_weight=".50"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/Father"
android:text="Ramesh"
android:layout_width="0dp"
android:layout_weight=".70"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/Sessional"
android:text="maths 15 ,english 20, physics 30,computer 7,Gk 12"
android:layout_width="0dp"
android:layout_weight="1.5"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/Comments"
android:text="should put more efforts"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
</LinearLayout>
Upvotes: 2
Views: 104
Reputation: 26
While parsing JSON data you are parsing one extra object ""Comments"" which does not exist in your JSON file. Due to this your array "teams" was not populating with data.
public class MainActivity extends AppCompatActivity {
private static final String DEBUG_TAG = "HttpExample";
ArrayList<Team> teams = new ArrayList<Team>();
ListView listview;
Button btnDownload;
TeamsAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listview = (ListView) findViewById(R.id.listview);
btnDownload = (Button) findViewById(R.id.btnDownload);
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
btnDownload.setEnabled(true);
} else {
btnDownload.setEnabled(false);
}
}
public void buttonClickHandler(View view) {
new DownloadWebpageTask(new AsyncResult() {
@Override
public void onResult(JSONObject object) {
processJson(object);
}
}).execute("https://spreadsheets.google.com/tq?key=1424bS7kU8nJbHdu4QdoAFdIdWDSnmEnj2NqfMb6rPTU");
}
private void processJson(final JSONObject object) {
try {
JSONArray rows = object.getJSONArray("rows");
for (int r = 0; r < rows.length(); ++r) {
JSONObject row = rows.getJSONObject(r);
JSONArray columns = row.getJSONArray("c");
int Code = columns.getJSONObject(0).getInt("v");
String Name = columns.getJSONObject(1).getString("v");
String Father = columns.getJSONObject(3).getString("v");
String Sessional = columns.getJSONObject(4).getString("v");
//String Comments = columns.getJSONObject(5).getString("v");
String Comments = "Error";
Team team = new Team(Code, Name, Father, Sessional, Comments);
teams.add(team);
}
adapter = new TeamsAdapter(MainActivity.this, R.layout.team, teams);
listview.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Upvotes: 1