Parse API Data into TextView - java

I have a API link that has a json element named title, and I am trying to store that value into a textview. Here is what I have so far in my main activity code that is supposed to display the contained string:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONObject jObject;
try {
jObject = new JSONObject("https://chex-triplebyte.herokuapp.com/api/cats?page=0");
String mResponse = jObject.getString("title");
TextView t = (TextView) findViewById(R.id.title_image);
t.setText(mResponse);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The API link I provided works so you can see the value title that I am trying to obtain.

try this:
TextView t = (TextView) findViewById(R.id.title_image);
try {
url = new URL("https://chex-triplebyte.herokuapp.com/api/cats?page=0");
urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.connect();
InputStream in = urlConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
//InputStreamReader isw = new InputStreamReader(in);
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String JsonResponse= buffer.toString();
JSONObject jsonobj = new JSONObject(JsonResponse);
JSONArray jarray = jsono.getJSONArray("jsontitle");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
t.setText(object.getString("title"));
}
} catch (JSONException e) {
e.printStackTrace();
}
but you have to make sure you have a correct json format like this:
{jsontitle:[{"title":"Space Keybaord Cat","timestamp":"2017-09-11T04:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/space.jpg","description":"In space, no one can hear you purr."},{"title":"Jiji","timestamp":"2017-09-11T03:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/jiji.png","description":"You'd think they'd never seen a girl and a cat on a broom before"},{"title":"Limecat","timestamp":"2017-09-11T02:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/lime.jpg","description":"Destroyer of Clockspider and his evil followers, Limecat is the one true god."},{"title":"Astronaut Cat","timestamp":"2017-09-11T01:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/astronaut.jpg","description":"Houston, we have a purroblem"},{"title":"Grumpy Cat","timestamp":"2017-09-11T00:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/grumpy.jpg","description":"Queen of the RBF"},{"title":"Soviet cat","timestamp":"2017-09-10T23:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/soviet.jpg","description":"In soviet Russia cat pets you!"},{"title":"Serious Business Cat","timestamp":"2017-09-10T22:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/serious.jpg","description":"SRSLY GUISE"},{"title":"Sophisticated Cat","timestamp":"2017-09-10T21:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/sophisticated.PNG","description":"I should buy a boat"},{"title":"Shironeko","timestamp":"2017-09-10T20:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/shironeko.png","description":"The zen master kitty"},{"title":"Puss in Boots","timestamp":"2017-09-10T19:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/puss.jpg","description":"Don't you dare do the litter box on me!"}]}

You need to make a network call first parse it to JSONArray first and then get the title from the JSON
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView t = (TextView) findViewById(R.id.title_image);
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://chex-triplebyte.herokuapp.com/api/cats?page=0";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray jArray;
try {
jArray = new JSONArray(response);
JSONObject jObject = jArray.getJSONObject(0);
String mResponse = jObject.getString("title");
t.setText(mResponse);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
But this will only show the first title in the response array
If you want to show all titles appended then you can loop over the array
JSONArray jArray;
try {
jArray = new JSONArray(response);
String mResponse = "";
for(int i=0 ;i<jArray.length();i++){
JSONObject jObject = jArray.getJSONObject(i);
mResponse += jObject.getString("title")+" ";
}
t.setText(mResponse);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
For using volley you need to include it in dependencies in build.gradle of app
dependencies {
.
.
compile 'com.android.volley:volley:1.0.0'
.
.
}

Try this...
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private String TAG = MainActivity.class.getSimpleName();
private ListView listView;
List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
rowItems = new ArrayList<RowItem>();
listView = (ListView) findViewById(R.id.item_list);
new GetList().execute();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
class GetList extends AsyncTask<Void, Void, List<RowItem>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this, "Json Data is downloading", Toast.LENGTH_LONG).show();
}
#Override
protected List<RowItem> doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "https://chex-triplebyte.herokuapp.com/api/cats?page=0";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray list = new JSONArray(jsonStr);
for (int i = 0; i < list.length(); i++) {
JSONObject c = list.getJSONObject(i);
String title = c.getString("title");
String timestamp = c.getString("timestamp");
String image_url = c.getString("image_url");
String description = c.getString("description");
RowItem item = new RowItem();
item.setTitle(title);
item.setTimestamp(timestamp);
item.setImageUrl(image_url);
item.setDescription(description);
rowItems.add(item);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return rowItems;
}
#Override
protected void onPostExecute(List<RowItem> rowItems) {
super.onPostExecute(rowItems);
if (rowItems != null) {
CustomListViewAdapter adapter = new CustomListViewAdapter(MainActivity.this, R.layout.list_item, rowItems);
listView.setAdapter(adapter);
}
}
}
}
CustomListViewAdapter.java
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
private Context context;
public CustomListViewAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.description);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.preview);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtDesc.setText(rowItem.getDescription());
holder.txtTitle.setText(rowItem.getTitle());
String url = rowItem.getImageUrl();
DownloadImageTask downloadImageTask = new DownloadImageTask(holder.imageView);
downloadImageTask.execute(url);
return convertView;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
RowItem.java
public class RowItem {
private String title;
private String timestamp;
private String imageUrl;
private String description;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/linearLayout2">
<ImageView
android:id="#+id/preview"
android:layout_width="80dp"
android:layout_height="80dp"
app:srcCompat="#mipmap/ic_launcher"
android:contentDescription="#string/app_name" />
<TextView
android:id="#+id/title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:text="#string/app_name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/preview"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/description"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/app_name"
app:layout_constraintBottom_toBottomOf="#+id/preview"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/preview"
app:layout_constraintTop_toBottomOf="#+id/title" />
</android.support.constraint.ConstraintLayout>
HttpHandler.java
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
activity_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/item_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Note:
item_list.xml has ConstraintLayout implementation.
Result:

Related

RecyclerView Not Displaying - Android

I am having a few problems with my RecyclerView in Android. When I run the project there is no display, only a white screen. Please help..
MainActivity Code:
public class MainActivity extends AppCompatActivity {
RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private MyAdapter mViewAdapter;
List<News> news_list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ParseNewsJSON().execute();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
//mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mViewAdapter= new MyAdapter(news_list);
mRecyclerView.setAdapter(mViewAdapter);
}
}
MyAdapter Code:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<News> newsArticleList;
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView title;
//description, genre;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.textView_articleHeading);
// description = (TextView) itemView.findViewById(R.id.textView_description);
// image = (TextView) itemView.findViewById(R.id.rating);
}
}
public MyAdapter (List<News> newsArticleList){
this.newsArticleList = newsArticleList;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_main, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
News news = newsArticleList.get(position);
holder.title.setText(news.getHeading());
}
#Override
public int getItemCount() {
return newsArticleList.size();
}
}
JSON Parsing Code:
public class ParseNewsJSON extends AsyncTask<String, Void, String> {
private final String JSON_URL = "https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=c80ddd850a524fe5975cad881d6f4aba";
String result ="";
ArrayList<String> article_heading = new ArrayList<>();
#Override
protected String doInBackground(String... strings) {
try {
URL url = new URL(JSON_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while(data !=-1){
char current = (char) data;
result += current;
data = reader.read();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("articles");
for(int i = 0; i<jsonArray.length(); i++){
News news = new News();
news.setHeading(String.valueOf(article_heading.add(jsonArray.getJSONObject(i).optString("title"))));
// article_heading.add(jsonArray.getJSONObject(i).optString("title"));
Log.d("news_JSON", article_heading.toString());
Log.d("news", news.getHeading().toString());
//article_heading.add(jsonArray.getJSONObject(i).optString("title"));
}
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
}
News.Java:
public class News {
private String heading;
//private String descrpiton;
private String img;
public String getHeading() {
return heading;
}
public void setHeading(String heading) {
this.heading = heading;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
}
I have read threw a few threads however they have not solved my issueThis is the output when I run the emulator
activity_main.xml:
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.RecyclerView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/recyclerView"
xmlns:android="http://schemas.android.com/apk/res/android">
</android.support.v7.widget.RecyclerView>
card_layout.xml:
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_marginTop="15dp"
android:layout_height="200dp"
app:cardCornerRadius="25dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/textView_articleHeading"
android:layout_marginLeft="5dp"
android:textStyle="bold"
android:textColor="#000000"
android:textSize="18sp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1.0"
android:id="#+id/rating"
android:scaleType="center"
/>
<TextView
android:id="#+id/textView_description"
android:textSize="15sp"
android:textColor="#000000"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
I think the problem is that your not adding any data in to your news_list ArrayList check in your ParseNewsJSON onPostExecute() method
Make change in your ParseNewsJSON like below code
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("articles");
for(int i = 0; i<jsonArray.length(); i++){
News news = new News();
news.setHeading(String.valueOf(article_heading.add(jsonArray.getJSONObject(i).optString("title"))));
// article_heading.add(jsonArray.getJSONObject(i).optString("title"));
Log.d("news_JSON", article_heading.toString());
Log.d("news", news.getHeading().toString());
news_list.add(news);
}
} catch (JSONException e) {
e.printStackTrace();
}
mViewAdapter= new MyAdapter(news_list);
mRecyclerView.setAdapter(mViewAdapter);
mViewAdapter.notifyDataSetChanged().
super.onPostExecute(s);
}
You have to add values to "news_list" in onPostExecute() of ParseNewsJSON class. And then notify the adapter.
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("articles");
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
news.setHeading(String.valueOf(article_heading.add(jsonArray.getJSONObject(i).optString("title"))));
news_list.add(news);
Log.d("news_JSON", article_heading.toString());
Log.d("news", news.getHeading().toString());
}
mViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
add your parse data to arraylist in onPostExecute() and notify adapter.
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("articles");
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
news.setHeading(String.valueOf(article_heading.add(jsonArray.getJSONObject(i).optString("title"))));
news_list.add(news);
}
mViewAdapter.notifyDataSetChanged();//add this line
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
in main activity
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
//mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setLayoutManager( new LinearLayoutManager(getApplicationContext()));
mViewAdapter= new MyAdapter(new ArrayList<News>);
mRecyclerView.setAdapter(mViewAdapter);
in post execute method
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("articles");
for(int i = 0; i<jsonArray.length(); i++){
news_list.add(jsonArray.getJSONObject(i));
news.setHeading(String.valueOf(article_heading.add(jsonArray.getJSONObject(i).optString("title"))));
//article_heading.add(jsonArray.getJSONObject(i).optString("title"))
Log.d("news_JSON", article_heading.toString());
Log.d("news", news.getHeading().toString());
}
mViewAdapter.add(news_list);
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
in adapter change this
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
if (viewHolder instanceof ViewHolder){
ViewHolder holder = (ViewHolder) viewHolder;
holder.displayDetails(newsArticleList.get(position));
}
}
add method in adapter
public void addItems(List<News> items){
if ( items != null && items.size() > 0 ) {
for (int i = 0; i < items.size(); i++) {
newsArticleList.add(items.get(i));
notifyItemInserted(newsArticleList.size() - 1);
}
}
}

Football-data API JSON parsing error

I'm having difficulty in downloading footballing data from an (http://www.football-data.org). I am trying to download the English Premier League Table by creating a new Standing object for each team and adding them to an ArrayList.
I've set up my parser class, adapter class and my view.
The error I am getting is :
org.json.JSONException: org.json.JSONException: Value {"_links":{"self":{"href":"http:\/\/api.football-data.org\/v1\/soccerseasons\/426\/leagueTable\/?matchday=37"},"soccerseason":{"href":"http:\/\/api.football-data.org\/v1\/soccerseasons\/426"}},"leagueCaption":"Premier League 2016\/17","matchday":37,"standing":[{"_links":{"team":{"href":"http:\/\/api.football-data.org\/v1\/teams\/61"}},"position":1,"teamName":"Chelsea FC","crestURI":"http:\/\/upload.wikimedia.org\/wikipedia\/de\/5\/5c\/Chelsea_crest.svg","playedGames":36,"points":87,"goals":76,"goalsAgainst":29,"goalDifference":47,"wins":28,"draws":3,"losses":5,"home":{"goals":46,"goalsAgainst":13,"wins":15,"draws":0,"losses":2},"away":{"goals":30,"goalsAgainst":16,"wins":13,"draws":3,"losses":3}},{"_links":{"team":{"href":"http:\/\/api.football-data.org\/v1\/teams\/73"}},"position":2,"teamName":"Tottenham Hotspur FC","crestURI":"http:\/\/upload.wikimedia.org\/wikipedia\/de\/b\/b4\/Tottenham_Hotspur.svg","playedGames":35,"points":77,"goals":71,"goalsAgainst":23,"goalDifference":48,"wins":23,"draws":8,"losses":4,"home":{"goals":45,"goalsAgainst":8,"wins":16,"draws":2,"losses":0},"away":{"goals":26,"goalsAgainst":15,"wins":7,"draws":6,"losses":4}},{"_links":{"team":{"href":"http:\/\/api.football-data.org\/v1\/teams\/65"}},"position":3,"teamName":"Manchester City FC","crestURI":"https:\/\/upload.wikimedia.org\/wikipedia\/en\/e\/eb\/Manchester_City_FC_badge.svg","playedGames":36,"points":72,"goals":72,"goalsAgainst":38,"goalDifference":34,"wins":21,"draws":9,"losses":6,"home":{"goals":34,"goalsAgainst":16,"wins":10,"draws":7,"losses":1},"away":{"goals":38,"goalsAgainst":22,"wins":11,"draws":2,"losses":5}},{"_links":{"team":{"href":"http:\/\/api.football-data.org\/v1\/teams\/64"}},"position":4,"teamName":"Liverpool FC","crestURI":"http:\/\/upload.wikimedia.org\/wikipedia\/de\/0\/0a\/FC_Liverpool.svg","playedGames":36,"points":70,"goals":71,"goalsAgainst":42,"goalDifference":29,"wins":20,"draws":10,"losses":6,"home":{"goals":42,"goalsAgainst":18,"wins":11,"draws":5,"losses":2},"away":{"goals":29,"goalsAgainst":24,"wins":9,"draws":5,"losses":4}},{"_links":{"team":{"href":"http:\/\/api.football-data.org\/v1\/teams\/57"}},"position":5,"teamName":"Arsenal FC","crestURI":"http:\/\/upload.wikimedia.org\/wikipedia\/en\/5\/53\/Arsenal_FC.svg","playedGames":35,"points":66,"goals":68,"goalsAgainst":42,"goalDifference":26,"wins":20,"draws":6,"losses":9,"home":{"goals":34,"goalsAgainst":15,"wins":12,"draws":3,"losses":2},"away":{"goals":34,"goalsAgainst":27,"wins":8,"draws":3,"losses":7}},{"_links":{"team":{"href":"http:\/\/api.football-data.org\/v1\/teams\/66"}},"position":6,"teamName":"Manchester United FC","crestURI":"http:\/\/upload.wikimedia.org\/wikipedia\/de\/d\/da\/Manchester_United_FC.svg","playedGames":35,"points":65,"goals":51,"goalsAgainst":27,"goalDifference":24,"wins":17,"draws":14,"losses":4,"home":{"goals":24,"goalsAgainst":12,"wins":7,"draws":10,"losses":1},"away":{"goals":27,"goalsAgainst":15,"wins":10,"draws":4,"losses":3}},{"_links":{"team":{"href":"http:\/\/api.football-data.org\/v1\/teams\/62"}},"position":7,"teamName":"Everton FC","crestURI":"http:\/\/upload.wikimedia.org\/wikipedia\/de\/f\/f9\/Everton_FC.svg","playedGames":37,"points":61,"goals":61,"goalsAgainst":41,"goalDifference":20,"wins":17,"draws":10,"losses":10,"home":{"goals":42,"goalsAgainst":16,"wins":13,"draws":4,"losses":2},"away":{"goals":19,"goalsAgainst":25,"wins":4,"draws":6,"losses":8}},{"_links":{"team":{"href":"http:\/\/api.football-data.org\/v1\/teams\/74"}},"position":8,"teamName":"West Bromwich Albion FC","crestURI":"http:\/\/upload.wikimedia.org\/wikipedia\/de\/8\/8b\/West_Bromwich_Albion.svg","playedGames":36,"points":45,"goals":41,"goalsAgainst":46,"goalDifference":-5,"wins":12,"draws":9,"losses":15,"home":{"goals":27,"goalsAgainst":22,"wins":9,"draws":2,"losses":8},"away":{"goals":14,"goalsAgainst":24,"wins":3,"draws":7,"losses":7}},{"_links":{"team":{"href":"http:\/\/api.football-data.org\/v1\/teams\/1044"}},"position":9,"teamName":"AFC Bournemouth","crestURI":"https:\/
05-13 15:39:24.798 6021-6540/com.example.oisin.premierleaguesocial W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
05-13 15:39:24.798 6021-6540/com.example.oisin.premierleaguesocial W/System.err: at org.json.JSONArray.<init>(JSONArray.java:96)
05-13 15:39:24.798 6021-6540/com.example.oisin.premierleaguesocial W/System.err: at org.json.JSONArray.<init>(JSONArray.java:108)
05-13 15:39:24.798 6021-6540/com.example.oisin.premierleaguesocial W/System.err: at com.example.oisin.premierleaguesocial.Utilities.JSONParser.parse(JSONParser.java:75)
05-13 15:39:24.799 6021-6540/com.example.oisin.premierleaguesocial W/System.err: at com.example.oisin.premierleaguesocial.Utilities.JSONParser.doInBackground(JSONParser.java:56)
05-13 15:39:24.799 6021-6540/com.example.oisin.premierleaguesocial W/System.err: at com.example.oisin.premierleaguesocial.Utilities.JSONParser.doInBackground(JSONParser.java:27)
I've been trying to resolve the issue for a few hours, but can't fix it. I think I've set up my data types correctly. I decided to only try to get the Integer data types at first for the sake of simplicity.
Any help would be very much appreciated. Thank you.
public class JSONParser extends AsyncTask<Void, Void, Boolean> {
private Context c;
private String jsonData;
private RecyclerView rv;
private ProgressDialog pd;
private ArrayList<Standing> mLeagueTable = new ArrayList<>();
public JSONParser(Context c, String jsonData, RecyclerView rv) {
this.c = c;
this.jsonData = jsonData;
this.rv = rv;
}
#Override
protected void onPreExecute () {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Parse");
pd.setMessage("Parsing..Please Wait");
pd.show();
}
#Override
protected Boolean doInBackground (Void...params){
return parse();
}
#Override
protected void onPostExecute (Boolean isParsed){
super.onPostExecute(isParsed);
pd.dismiss(); //Dismiss progress dialog.
if (isParsed) {
//BIND
rv.setAdapter(new TableAdapter(c, mLeagueTable)); //Pass in instance of adapter.
} else {
Toast.makeText(c, "Unable to Parse check your Log Output", Toast.LENGTH_SHORT).show();
}
}
private Boolean parse() {
try {
//JSONArray ja = new JSONArray(jsonData);
JSONArray ja = new JSONArray("standing");
JSONObject jo; //declare json OBJECT
mLeagueTable.clear(); //Clears the ArrayList.
Standing table; //Declare a table
for (int i = 0; i < ja.length(); i++) //iterating in JSONArray
{
jo = ja.getJSONObject(i);
int position = ja.getInt(Integer.parseInt("position"));
int points = ja.getInt(Integer.parseInt("points"));
int playedGames = ja.getInt(Integer.parseInt("playedGames"));
int goals = ja.getInt(Integer.parseInt("goals"));
int goalsAgainst = ja.getInt(Integer.parseInt("goalsAgainst"));
int goalDifference = ja.getInt(Integer.parseInt("goalDifference"));
table = new Standing(); //Create a new "User" object.
table.setPosition(position);
table.setPoints(points);
table.setPlayedGames(playedGames);
table.setGoals(goals);
table.setGoalsAgainst(goalsAgainst);
table.setGoalDifference(goalDifference);
mLeagueTable.add(table); //Add new Standing object to ArrayList mLeagueTable.
}
return true;
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
}
public class JSONDownloader extends AsyncTask<Void, Void, String> {
Context c;
String jsonURL;
RecyclerView rv;
ProgressDialog pd;
public JSONDownloader(Context c, String jsonURL, RecyclerView rv) {
this.c = c;
this.jsonURL = jsonURL;
this.rv = rv;
}
#Override
protected void onPreExecute() { //CALLED just before data is downloaded.
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Download JSON");
pd.setMessage("Downloading.... Please Wait!");
pd.show();
}
#Override
protected String doInBackground(Void... voids) {
return download();
}
#Override
protected void onPostExecute(String jsonData) {
super.onPostExecute(jsonData);
pd.dismiss();
if (jsonData.startsWith("Error"))
{
String error = jsonData;
Toast.makeText(c, error, Toast.LENGTH_SHORT).show();
} else {
//PARSER
new JSONParser(c, jsonData, rv).execute();
}
}
private String download() {
Object connection = Connector.connect(jsonURL);
if (connection.toString().startsWith("Error")) {
return connection.toString();
}
try {
HttpURLConnection con = (HttpURLConnection) connection; //Cast connection to HTTPConnection
if (con.getResponseCode() == con.HTTP_OK) {
//GET INPUT FROM STREAM
InputStream is = new BufferedInputStream(con.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer jsonData = new StringBuffer();
// READ
while ((line = br.readLine()) != null) {
jsonData.append(line + "\n");
}
//CLOSE RESOURCES
br.close();
is.close();
//RETURN JSON
return jsonData.toString();
} else {
return "Error " + con.getResponseMessage();
}
} catch (IOException e) {
e.printStackTrace();
return "Error " + e.getMessage();
}
}
}
public class MainActivity extends AppCompatActivity {
String jsonURL = "http://api.football-data.org/v1/soccerseasons/426/leagueTable";
public static final String TAG = "MainActivity";
//FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
private RecyclerView rv;
/*private ArrayList<Standing> mLeagueTable = new ArrayList<>(); //Initalise m
private TableAdapter mTableAdapter = new TableAdapter(mLeagueTable, this); */
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
rv = (RecyclerView) findViewById(R.id.rv);
if (rv != null) {
rv.setLayoutManager(new LinearLayoutManager(this));
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); //Initialze FAB
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONDownloader(MainActivity.this, jsonURL, rv).execute();
}
});
}
}
public class TableAdapter extends RecyclerView.Adapter<MyViewHolder>{
private ArrayList<Standing> mLeagueTable;
private Context c;
public TableAdapter(Context c, ArrayList<Standing> mLeagueTable) {
this.c = c;
this.mLeagueTable = mLeagueTable;
} //Constructor
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.tableitem, parent, false); //Inlfate the League Table model view.
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) { //BINDS THE data to the appropriote View
Standing s = mLeagueTable.get(position);
final int teamPosition = s.getPosition();
final String teamName = s.getTeamName();
final int playedGames = s.getPlayedGames();
final int goals = s.getGoals();
final int goalsAgainst = s.getGoalsAgainst();
final int goalDifference = s.getGoalDifference();
final int points = s.getPoints();
//holder.teamNameTxt.setText(teamName);
holder.teamPositionTxt.setText(teamPosition);
holder.playedGamesTxt.setText(playedGames);
//holder.teamImage.setImageResource(s.getTeamImage());
holder.goalsTxt.setText(goals);
holder.goalsAgainstTxt.setText(goalsAgainst);
holder.goalDifferenceTxt.setText(goalDifference);
holder.pointsTxt.setText(points);
// holder.wins.setText(s.getWins());
//holder.draws.setText(s.getDraws());
//holder.losses.setText(s.getLosses());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(int pos) {
openActivity(teamPosition, playedGames, goals, goalsAgainst, goalDifference, points);
}
});
}
#Override
public int getItemCount() {return mLeagueTable.size();}
////open Activity
private void openActivity(int...details)
{
Intent i = new Intent(c, TableActivity.class);
i.putExtra("POSITION_KEY", details[0]);
//i.putExtra("TEAMNAME_KEY", details[1]);
i.putExtra("POINTS_KEY", details[2]);
i.putExtra("PLAYEDGAMES_KEY", details[3]);
i.putExtra("GOALS_KEY", details[4]);
i.putExtra("GOALSAGAINST_KEY", details[5]);
i.putExtra("GOALDIFFERENCE_KEY", details[6]);
c.startActivity(i);
}
}
tableitem.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="wrap_content">
<TextView
android:id="#+id/teamPositionTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/primary_text" />
<TextView
android:id="#+id/teamNameTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:textColor="#color/primary_text" />
<TextView
android:id="#+id/pointsTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/primary_text"
android:textStyle="bold" />
<TextView
android:id="#+id/playedGamesTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/primary_text" />
<TextView
android:id="#+id/goalsTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/primary_text" />
<TextView
android:id="#+id/goalsAgainstTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/primary_text" />
<TextView
android:id="#+id/goalDifferenceTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/primary_text" />
</LinearLayout>
1. Create a JSONObject from string jsonData.
2. Get JSONArray (standing) from JSONObject by using jsonObj.getJSONArray("standing").
3. Inside for loop, get int values from JsonObject using jo.getInt() instead of ja.getInt().
Here is the working code:
private Boolean parse() {
try {
JSONObject jsonObj = new JSONObject(jsonData);
JSONArray ja = jsonObj.getJSONArray("standing");
mLeagueTable.clear(); //Clears the ArrayList.
for (int i = 0; i < ja.length(); i++) //iterating in JSONArray
{
JSONObject jo = ja.getJSONObject(i);
int position = jo.getInt(Integer.parseInt("position"));
int points = jo.getInt(Integer.parseInt("points"));
int playedGames = jo.getInt(Integer.parseInt("playedGames"));
int goals = jo.getInt(Integer.parseInt("goals"));
int goalsAgainst = jo.getInt(Integer.parseInt("goalsAgainst"));
int goalDifference = jo.getInt(Integer.parseInt("goalDifference"));
Standing table = new Standing(); //Create a new "User" object.
table.setPosition(position);
table.setPoints(points);
table.setPlayedGames(playedGames);
table.setGoals(goals);
table.setGoalsAgainst(goalsAgainst);
table.setGoalDifference(goalDifference);
mLeagueTable.add(table); //Add new Standing object to ArrayList mLeagueTable.
}
return true;
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
Hope this will work~
Change
JSONArray ja = new JSONArray("standing");
for
JSONObject ja = new JSONObject(jsonData);
JSONObject jo = ja.getJSONObject("soccerseason");
The information is in jo, and now you can extract each field following the right structure of the JSONObject

Insert in listView an image from json url

I'm new in android. I have a problem about loading the image from Json Url to ListView. ListView works only without image.
This is my json url:
{"infoBooks":[{"user_name":"carlo","title":"Title: Il potere del cane\nAuthor\/s: Don Winslow","author":"","urlImage":"https:\/\/books.google.it\/books\/content?id=qiLanQEACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"},{"user_name":"ff","title":"Title: Incontro con la storia. Con espansione online. Per la Scuola media\nAuthor\/s: Luisa Benucci","author":"","urlImage":"https:\/\/books.google.it\/books\/content?id=qTzFSgAACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"}]}
My SearchBooks.java :
public class SearchBooks extends AppCompatActivity {
ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_books);
String strUrl = "http://192.168.1.118:8888/webappdb/listViewBooks.php";
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(strUrl);
mListView = (ListView) findViewById(R.id.listView);
}
private String downloadUrl (String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try {
URL url = new URL(strUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
}catch (Exception e){
Log.d("Exception while downloading url", e.toString());
}finally {
iStream.close();
}
return data;
}
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (IOException e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
listViewLoaderTask.execute(result);
}
}
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
JSONObject jObject;
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try {
jObject = new JSONObject(strJson[0]);
customAdapter customAdapter = new customAdapter();
customAdapter.parse(jObject);
} catch (JSONException e) {
Log.d("JSON Exception1", e.toString());
}
customAdapter customAdapter = new customAdapter();
List<HashMap<String, Object>> books = null;
try {
books = customAdapter.parse(jObject);
} catch (Exception e){
Log.d("Exception", e.toString());
}
String infoFrom[] = {"user_name", "details"};
int infoTo[] = {R.id.user_name_search, R.id.bookDescriptionSearch};
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), books, R.layout.row_list_books, infoFrom, infoTo);
return adapter;
}
#Override
protected void onPostExecute(SimpleAdapter adapter) {
mListView.setAdapter(adapter);
for (int i = 0; i < adapter.getCount(); i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("urlImage");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("urlImage", imgUrl);
hm.put("position", i);
imageLoaderTask.execute();
}
}
}
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
#Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream = null;
String imgUrl = (String) hm[0].get("urlImage");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
File cacheDirectory = getBaseContext().getCacheDir();
File tmpFile = new File (cacheDirectory.getPath() + "/wpta_" + position + ".jpeg");
FileOutputStream fOutputStream = new FileOutputStream(tmpFile);
Bitmap b = BitmapFactory.decodeStream(iStream);
b.compress(Bitmap.CompressFormat.JPEG, 100, fOutputStream);
fOutputStream.flush();
fOutputStream.close();
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
hmBitmap.put("launcherImage", tmpFile.getPath());
hmBitmap.put("position", position);
return hmBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
String path = (String) result.get("launcherImage");
int position = (Integer) result.get("position");
SimpleAdapter simpleAdapter = (SimpleAdapter) mListView.getAdapter();
HashMap<String, Object> hm = (HashMap<String, Object>) simpleAdapter.getItem(position);
hm.put("launcherImage", path);
simpleAdapter.notifyDataSetChanged();
}
}
}
this is my customAdapter.java :
public class customAdapter{
public List<HashMap<String, Object>> parse(JSONObject JObject) {
JSONArray infoBooks = null;
try {
infoBooks = JObject.getJSONArray("infoBooks");
} catch (JSONException e) {
e.printStackTrace();
}
return getBooks(infoBooks);
}
private List<HashMap<String, Object>> getBooks(JSONArray infoBooks){
int booksCount = infoBooks.length();
List<HashMap<String, Object>> bookList = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> book;
for(int i = 0; i < booksCount; i++) {
try {
book = getBook((JSONObject) infoBooks.get(i));
bookList.add(book);
} catch (JSONException e) {
e.printStackTrace();
}
}
return bookList;
}
private HashMap<String, Object> getBook(JSONObject jBook){
HashMap<String, Object> book = new HashMap<String, Object>();
String user_name = "";
String title = "";
String author = "";
String urlImage = "";
try {
user_name = jBook.getString("user_name");
title = jBook.getString("title");
author = jBook.getString("author");
urlImage = jBook.getString("urlImage");
String details = "Title: " + title + "\n" +
"Author/s: " + author;
book.put("user_name", user_name);
book.put("details", details);
book.put("launcherImage", R.mipmap.ic_launcher);
book.put("urlImage", urlImage);
} catch (JSONException e) {
e.printStackTrace();
}
return book;
}
}
This is my logcat :
03-10 08:56:13.194 969-1433/? E/PersonaManagerService: inState(): stateMachine is null !!
03-10 08:56:13.994 969-1585/? E/PersonaManagerService: inState(): stateMachine is null !!
03-10 08:56:14.134 5005-5562/gamingproject.sellmybooks E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4
Process: gamingproject.sellmybooks, PID: 5005
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at gamingproject.sellmybooks.SearchBooks$ImageLoaderTask.doInBackground(SearchBooks.java:176)
at gamingproject.sellmybooks.SearchBooks$ImageLoaderTask.doInBackground(SearchBooks.java:169)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
at java.lang.Thread.run(Thread.java:818) 
03-10 08:56:14.244 969-1049/? E/InputDispatcher: channel '14e67292 gamingproject.sellmybooks/gamingproject.sellmybooks.Profile (server)' ~ Channel is unrecoverably broken and will be disposed!
03-10 08:56:14.254 969-1207/? E/ActivityManager: checkUser: useridlist=null, currentuser=0
03-10 08:56:14.254 969-1207/? E/ActivityManager: checkUser: useridlist=null, currentuser=0
03-10 08:56:14.254 969-1207/? E/ActivityManager: checkUser: useridlist=null, currentuser=0
03-10 08:56:14.254 969-1207/? E/ActivityManager: checkUser: useridlist=null, currentuser=0
03-10 08:56:14.264 5566-5566/? E/Zygote: v2
03-10 08:56:14.274 5566-5566/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
03-10 08:56:14.774 270-270/? E/SMD: DCD OFF
03-10 08:56:17.784 270-270/? E/SMD: DCD OFF
Thank you in advance.
Why are you making the code so complex ? Keep it simple.
I have a Demo code. Maybe it can help you.
Just Create a Model Class Which you Require. Other things are the same.
public class MainActivity extends AppCompatActivity {
private Button btnHit;
private HttpURLConnection connection = null;
private URL url;
private BufferedReader reader = null;
private StringBuffer buffer;
private ListView lvMovies;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading !! Please wait..");
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config);
lvMovies = (ListView) findViewById(R.id.lvMovies);
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesData.txt");
}
public class JSONTask extends AsyncTask<String, String, List<MovieModel>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
#Override
protected List<MovieModel> doInBackground(String... params) {
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
List<MovieModel> movieModelList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
MovieModel movieModel = gson.fromJson(finalObject.toString(), MovieModel.class);
movieModelList.add(movieModel);
}
return movieModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<MovieModel> result) {
super.onPostExecute(result);
dialog.dismiss();
MovieAdapter adapter = new MovieAdapter(getApplicationContext(), R.layout.row, result);
lvMovies.setAdapter(adapter);
// TODO Need to set Data on List
}
}
public class MovieAdapter extends ArrayAdapter {
private List<MovieModel> movieModelList;
private int resource;
private LayoutInflater inflater;
public MovieAdapter(Context context, int resource, List<MovieModel> objects) {
super(context, resource, objects);
movieModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(resource, null);
holder.ivMovieIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
holder.tvMovie = (TextView) convertView.findViewById(R.id.tvMovie);
holder.tvTagline = (TextView) convertView.findViewById(R.id.tvTagLine);
holder.tvYear = (TextView) convertView.findViewById(R.id.tvYear);
holder.tvDuration = (TextView) convertView.findViewById(R.id.tvDuration);
holder.tvDirector = (TextView) convertView.findViewById(R.id.tvDirector);
holder.rbMovieRating = (RatingBar) convertView.findViewById(R.id.rbMovie);
holder.tvCast = (TextView) convertView.findViewById(R.id.tvCast);
holder.tvStory = (TextView) convertView.findViewById(R.id.tvStory);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ProgressBar progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);
ImageLoader.getInstance().displayImage(movieModelList.get(position).getImage(), holder.ivMovieIcon, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
progressBar.setVisibility(View.GONE);
}
});
holder.tvMovie.setText(movieModelList.get(position).getMovie());
holder.tvTagline.setText(movieModelList.get(position).getTagline());
holder.tvYear.setText("Year : " + movieModelList.get(position).getYear());
holder.tvDuration.setText(movieModelList.get(position).getDuration());
holder.tvDirector.setText(movieModelList.get(position).getDirector());
// Rating Bar
holder.rbMovieRating.setRating(movieModelList.get(position).getRating() / 2);
Log.v("Rating is", "" + movieModelList.get(position).getRating() / 2);
StringBuffer stringBuffer = new StringBuffer();
for (MovieModel.Cast cast : movieModelList.get(position).getCastList()) {
stringBuffer.append(cast.getName() + ", ");
}
holder.tvCast.setText(stringBuffer);
holder.tvStory.setText(movieModelList.get(position).getStory());
return convertView;
}
class ViewHolder {
private ImageView ivMovieIcon;
private TextView tvMovie;
private TextView tvTagline;
private TextView tvYear;
private TextView tvDuration;
private TextView tvDirector;
private RatingBar rbMovieRating;
private TextView tvCast;
private TextView tvStory;
}
}
}

Results not showing in the ListView Android

I've been working on an android app ... I am stuck at a point ... after getting the JSON data from the internet I am having trouble to show it in the ListView ... Below is my code ...
public class MainListActivityFragment extends Fragment {
protected String[] mBlogPostTitles;
protected JSONObject mBlogData;
public static final String LOG_TAG = MainListActivityFragment.class.getSimpleName();
public static ArrayAdapter<String> titleAdapter;
public MainListActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_list, container, false);
if(isNetworkAvailable()) {
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
} else {
Toast.makeText(getContext(),"No Network Available", Toast.LENGTH_LONG).show();
}
List<String> blogTitles = new ArrayList<>(Arrays.asList(mBlogPostTitles));
titleAdapter = new ArrayAdapter<>(
getActivity(),
R.layout.name_lst_view,
R.id.name_list_view_textview,
blogTitles
);
ListView listView = (ListView) rootView.findViewById(R.id.listview_name);
listView.setAdapter(titleAdapter);
return rootView;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
public class GetBlogPost extends AsyncTask<Object, Void, JSONObject> {
public final int NUMBER_OF_POSTS = 5;
int responseCode = -1;
JSONObject jsonResponse = null;
#Override
protected JSONObject doInBackground(Object... params) {
try {
URL blogFeedUrl = new URL("http://www.example.com/api/get_category_posts/?slug=americancuisines&count="+NUMBER_OF_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
String blogDataJsonStr = buffer.toString();
jsonResponse = new JSONObject(blogDataJsonStr);
}else {
Log.i(LOG_TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
}
catch (MalformedURLException e){
Log.e(LOG_TAG,"Exception Caught: ",e);
}
catch (IOException e) {
Log.e(LOG_TAG, "IO Exception Caught: ",e);
}
catch (Exception e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
}
}
}
From the above code you can see that i am getting that data through doInBackground method of AsyncTask ... Data is coming through perfectly as I can see through the logcat ... The issue is somewhere in this method which I can't seem to figure out ..
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
The above method is called in onPostExecute I mean if i print to logcat within this method I can see the results being printed but when I try to show those results in the onCreateView method results don't show up not even in the logcat ... Any help will be appreciated ... Thanks
Change your code as following:
public class MainListActivityFragment extends Fragment {
protected String[] mBlogPostTitles;
protected JSONObject mBlogData;
public static final String LOG_TAG = MainListActivityFragment.class.getSimpleName();
public static ArrayAdapter<String> titleAdapter;
ListView listView;
public MainListActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_list, container, false);
listView = (ListView) rootView.findViewById(R.id.listview_name);
if(isNetworkAvailable()) {
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
} else {
Toast.makeText(getContext(),"No Network Available", Toast.LENGTH_LONG).show();
}
return rootView;
}
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
public class GetBlogPost extends AsyncTask<Object, Void, JSONObject> {
public final int NUMBER_OF_POSTS = 5;
int responseCode = -1;
JSONObject jsonResponse = null;
#Override
protected JSONObject doInBackground(Object... params) {
try {
URL blogFeedUrl = new URL("http://www.example.com/api/get_category_posts/?slug=americancuisines&count="+NUMBER_OF_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
String blogDataJsonStr = buffer.toString();
jsonResponse = new JSONObject(blogDataJsonStr);
}else {
Log.i(LOG_TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
}
catch (MalformedURLException e){
Log.e(LOG_TAG,"Exception Caught: ",e);
}
catch (IOException e) {
Log.e(LOG_TAG, "IO Exception Caught: ",e);
}
catch (Exception e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
List<String> blogTitles = new ArrayList<>(Arrays.asList(mBlogPostTitles));
titleAdapter = new ArrayAdapter<String>(
getActivity(),
R.layout.name_list_view,
R.id.name_list_view_textview,
blogTitles
);
listView.setAdapter(titleAdapter);
}
}
}
Use same array list in both update and initialize so globally declare a single array list and update it in updateList() method,
Try like this,
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];//remove this and use the
//same as you are using in adapter
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
titleAdapter.notifyDataSetChanged();//here
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
OR even you can use in onPostExecute
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
titleAdapter.notifyDataSetChanged();//here
}
find the listview : ListView listView = (ListView) rootView.findViewById(R.id.listview_name); before calling
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
and put this line listView.setAdapter(titleAdapter); in your onPostExecute method.

App crashes at setImageResource()

I am getting a NullPointerException at
image.setImageResource(R.drawable.cover);
Here's my code:
NewsFeed.this.runOnUiThread(new Runnable(){
#Override
public void run() {
//Your code to run in GUI thread here
image.setImageResource(R.drawable.cover);
}
});
This code is running in a doInBackground() method. This is my ImageView in XML:
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true" />
NewsFeed.java
public class NewsFeed extends ListActivity {
MainActivity mainAct = new MainActivity();
private ProgressDialog pDialog;
// json url
// json tags
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_ID = "id";
private static String TAG_MESSAGE = "message";
private static final String TAG_CREATETIME = "created_time";
protected static final String JSONObject = null;
// contacts JSONArray
JSONArray contacts = null;
TimerTask timerTask;
Handler handler;
Timer ourtimer;
String url, gotToken, static_token, imgUrl, nextUrl = "none",
prevUrl = "none", paging;
ImageView image;
Bitmap myBitmap;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Bundle gotBasket = getIntent().getExtras();
// gotToken = gotBasket.getString("Access_Token");
static_token = "xxxxxxxxxxxxxxxx";
url = "https://graph.facebook.com/v2.2/awaaziitkgp/feed?access_token="
+ static_token;
setContentView(R.layout.news_feed);
image = (ImageView) findViewById(R.id.imageView1);
final TextView button1 = (TextView) findViewById(R.id.button1);
final TextView newPosts = (TextView) findViewById(R.id.nextPosts);
final TextView prevPosts = (TextView) findViewById(R.id.previousPosts);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Calling async task to get json
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_DATA);
JSONObject pagingObj = jsonObj.getJSONObject("paging");
// String nextObj = pagingObj.getString("next");
nextUrl = pagingObj.getString("next");
// JSONObject prevObj= pagingObj.getJSONObject("previous");
prevUrl = pagingObj.getString("previous");
Log.d("contact.length", String.valueOf(contacts.length()));
// looping through All Contacts
for (int i = 0; i < 25; i++) {
JSONObject c = contacts.getJSONObject(i);
// tmp hashmap for single contact
HashMap<String, String> data = new HashMap<String, String>();
String message = null;
String id = c.getString(TAG_ID);
data.put(TAG_ID, id);
if (c.has("description") == true) {
message = c.getString("description");
Log.d("Getting Description", message);
}
if (c.has("picture") == true) {
try {
Log.d("IT HAS PICTURE! TADA!!", "Image Found");
imgUrl = c.getString("picture");
Thread thread = new Thread(){
public void run(){
System.out.println("Thread Running");
NewsFeed.this.runOnUiThread(new Runnable(){
#Override
public void run() {
//Your code to run in GUI thread here
URL newUrl = null;
try {
newUrl = new URL(imgUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myBitmap = getBitmapFromUrl(newUrl);
image.setImageBitmap(myBitmap);
}
});
}
};
thread.start();
} catch (Exception e) {
Log.d("ERROR LOADING IMAGE",
"Why you do this, InputStream? Why?");
}
}else{
NewsFeed.this.runOnUiThread(new Runnable(){
#Override
public void run() {
//Your code to run in GUI thread here
((ImageView) findViewById(R.id.imageView1)).setImageResource(R.drawable.cover);
}
});
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
Here you can get a solution.
((ImageView)findViewById(R.id.image_view1)).setImageResource(R.drawable.cover);
XML Snippet:
<ImageView
android:id="#+id/image_view1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
You are trying to inflate a layout then use a view from another layout..
since you used R.layout.activity_main you can only use the views inside that layout nothing more..
but in your case you used the image1 = (ImageView) findViewById(R.id.dice1); which will reference a null value because it reside in your MAIN.xml not in activity_main.
So what you need to do is instead of using the activity_main layout use the appropriate layout which is setContentView(R.layout.MAIN);

Categories

Resources