JSON - Help Converting JSONArray to Arraylist and populate a listview. - java

I am fairly new to android and java. I am trying to add JSON data to a listview. I have the JSON data coming in and printing to log, but I am having a hard time getting the data to the list view. I've tried and arraylist on row numbers and it works, but don't know how to get the JSON data there. Any pointers or advice would be appericated.
I am looking for a result Like
(Keys)ID Name Tourn_ID
(Values) 1 Tournamnet1 MI2016
(Values) 2 Tournamnet2 UT2016
(Values) 3 Tournamnet4 USNC2016
etc.
Here is my code Java.
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static android.R.*;
import static android.R.layout.simple_list_item_1;
import static java.util.Arrays.asList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
task.execute("http://www.goalballscoreboard.net/mobile/downloads/WebServices/Tournnames/Tournnames.php?rows=all");
ListView tournListView = (ListView) findViewById(R.id.tournListView);
final ArrayList<String> myTournList = new ArrayList<String>(asList("ROW 1", "ROW 2", "Row3"));
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, simple_list_item_1, myTournList);
tournListView.setAdapter(arrayAdapter);
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String tournInfo = jsonObject.getString("posts");
Log.i("Tourn INFO", tournInfo);
JSONArray arr = new JSONArray(tournInfo);
List<String> list = new ArrayList<String>();
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
JSONObject jsonObjectPost = jsonPart.getJSONObject("post");
//Log.i("Each Tournament Object", jsonPart.getString("post"));
Log.i("ID", jsonObjectPost.getString("ID"));
Log.i("Name of Tournament", jsonObjectPost.getString("NAME"));
Log.i("TOURN_ID", jsonObjectPost.getString("TOURN_ID"));
String id = jsonObjectPost.get("ID").toString();
String name = jsonObjectPost.get("NAME").toString();
String tournID = jsonObjectPost.get("TOURN_ID").toString();
list.add(jsonObjectPost.getString("ID") + ", " + jsonObjectPost.getString("NAME") + "," + jsonObjectPost.getString("TOURN_ID") + "\n");
}
System.out.println("" + list.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}

Create a JAVA file named Model.java
public class Model {
public String ID ;
public String Name;
public Tourn_ID;
}
Now at the time of parsing data
ArrayList<Model> modelArrayList = new ArrayList();
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
JSONObject jsonObjectPost = jsonPart.getJSONObject("post");
Model model;
model.ID = jsonObjectPost.get("ID").toString();
model.Name = jsonObjectPost.get("NAME").toString();
Model.Tourn_ID = jsonObjectPost.get("TOURN_ID").toString();
modelArrayList .add(model);
}
Adapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class CustomAdapter extends BaseAdapter{
ArrayList<Model> result = new ArrayList();
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(Context context, ArrayList<Model> result) {
// TODO Auto-generated constructor stub
this.result=result;
this.context=context;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.size;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv,tv2,tv3;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.custom_adapter, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.tv2=(TextView) rowView.findViewById(R.id.textView2);
holder.tv3=(TextView) rowView.findViewById(R.id.textView3);
holder.tv.setText(result[position].ID);
holder.tv2.setText(result[position].Name);
holder.tv3.setText(result[position].Tour_ID);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
}
});
return rowView;
}
}
in custom_adapter.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:text="TextView" />
<TextView
android:id="#+id/textView3"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:text="TextView" />
</LinearLayout>
now listview
listview = (Listview).findViewById(R.id.idOfYpurListview);
Adapter adapter = new Adapter(Activity.this,modelArrayList);
listview.setAdapter(adapter);

Related

java.lang.ClassCastException: CustomAdapter cannot be cast to android.widget.ArrayAdapter in java

I am trying to load json data into a scrollable spinner. But I am getting the error that the CustomAdapter is not able to cast into ArrayAdapter. Can you help me with this?
Provide_Food.xml: This is the file where the spinner is located
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/grdnt"
tools:context=".Provide_food">
<com.toptoche.searchablespinnerlibrary.SearchableSpinner
android:id="#+id/select_food"
android:layout_width="120dp"
android:layout_height="50dp"
android:layout_marginTop="250dp"
android:background="#color/bgcolor"
app:hintText="Select Item"
/>
<Button
android:id="#+id/select_food_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/select_food"
android:layout_marginTop="250dp"
android:layout_marginLeft="40dp"
android:text="Add Item"/>
</RelativeLayout>
Provide_Food.java: The java class for loading the json data into the spinner
package com.example.helping_hands_individual;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentResolver;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.textclassifier.TextLinks;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.database.annotations.Nullable;
import com.google.gson.JsonArray;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class Provide_food extends AppCompatActivity {
Spinner spinner;
String url = "api_link"; //can't mention the link here
List<Item_Model> list = new ArrayList<>();
List<String> list1 = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_provide_food);
spinner = (Spinner)findViewById(R.id.select_food);
new Getdata().execute();
}
class Getdata extends AsyncTask<Void,Void,String>{
String result;
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
CustomAdapter adapter = new CustomAdapter(Provide_food.this, list);
spinner.setAdapter(adapter);
}
#Override
protected String doInBackground(Void... voids) {
try {
URL mainurl = new URL(url);
HttpURLConnection connection = (HttpURLConnection)mainurl.openConnection();
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null){
builder.append(line);
}
result = builder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONArray array = new JSONArray(result);
for (int i=0; i<array.length(); i++){
Item_Model item_model = new Item_Model();
JSONObject object = array.getJSONObject(i);
String itemname = object.getString("Item Name");
item_model.setItemname(itemname);
list.add(item_model);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
}
Item_Model.java: The model class for getting the item name from the json api
package com.example.helping_hands_individual;
public class Item_Model {
String itemname;
public String getItemname() {
return itemname;
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
}
CustomAdapter.java: The custom adapter used for parsing the data into the spinner
package com.example.helping_hands_individual;
import android.content.Context;
import android.transition.Slide;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class CustomAdapter extends BaseAdapter {
LayoutInflater inflater;
Context context;
List<Item_Model> list;
public CustomAdapter(Context applicationContext, List<Item_Model> list){
this.context = applicationContext;
this.list = list;
inflater = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflater.inflate(R.layout.item,null);
TextView itemname = (TextView)view.findViewById(R.id.item_names);
itemname.setText(list.get(i).itemname);
return view;
}
}
item.xml: The sample layout file where it contains only the textview which will be displayed in the spinner
<?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">
<TextView
android:id="#+id/item_names"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:textSize="18dp"
android:text="Demo"/>
</LinearLayout>
Your CustomAdapter should extends ArrayAdapter, so you can change your class in this way:
public class CustomAdapter extends ArrayAdapter {
LayoutInflater inflater;
Context context;
List<Item_Model> list;
public CustomAdapter(Context applicationContext, int resources, List<Item_Model> list) {
super(applicationContext, resources);
this.context = applicationContext;
this.list = list;
inflater = (LayoutInflater.from(applicationContext));
}
//...
}
Consider using the parameterized ArrayAdapter<T> feature

Unable to retrieve data from MySQL database and put it in a list view on my android app

I'm trying to do a search function on my database. I first tried to retrieve all data from my database and put it into a listview and then performed a search on that list. The problem is that my app doesn't put those retrieved data from my SQL database to the listview. I tried running my PHP code separately and it works, so I think it's a problem in my java code in android.
companylist.php
<?php
include 'db_connect.php';
$sql = "SELECT * FROM company";
$result = $con->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$con->close();
?>
Search.java
package com.example.activitymanagement;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Search extends Fragment {
ListView SubjectListView;
ProgressBar progressBarSubject;
String ServerURL = "http://10.0.2.2/member/companylist.php";
EditText editText ;
List<String> listString = new ArrayList<String>();
ArrayAdapter<String> arrayAdapter ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
//return inflater.inflate(R.layout.fragment_search, container, false);
View rootView = inflater.inflate(R.layout.fragment_search, container, false);
SubjectListView = (ListView)rootView.findViewById(R.id.listview1);
progressBarSubject = (ProgressBar)rootView.findViewById(R.id.progressBar);
editText = (EditText)rootView.findViewById(R.id.edittext1);
new GetHttpResponse(getActivity()).execute();
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
Search.this.arrayAdapter.getFilter().filter(charSequence);
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Search");
}
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
String ResultHolder;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpServicesClass httpServiceObject = new HttpServicesClass(ServerURL);
try
{
httpServiceObject.ExecutePostRequest();
if(httpServiceObject.getResponseCode() == 200)
{
ResultHolder = httpServiceObject.getResponse();
if(ResultHolder != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(ResultHolder);
JSONObject jsonObject;
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
listString.add(jsonObject.getString("subjects").toString()) ;
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpServiceObject.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBarSubject.setVisibility(View.GONE);
SubjectListView.setVisibility(View.VISIBLE);
arrayAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_2, android.R.id.text1, listString);
SubjectListView.setAdapter(arrayAdapter);
}
}
}
fragment_search.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/searchlayout"
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">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/edittext1"
android:hint="Search Here"
android:gravity="center"/>
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listview1"
android:layout_below="#id/edittext1" />
</RelativeLayout>
According your companylist.php file response you are getting wrong parameter inside response, instead of getting name you are getting subjects, please check below code
try {
JSONArray jsonArray=new JSONArray(ResultHolder);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
listString.add(jsonObject.getString("name")) ;
}
} catch (JSONException e) {
e.printStackTrace();
}

How to implement a custom ArrayList in AsyncTask?

i am building an Android application that takes an API(The Movie Database), and extracts the JSON array. Upon extraction, the appropriate JSONObject is sent to a model. This model is a class composed of setters and getters to extract the object and assign it to variables which i can use. All of this is done on the AsyncTask. However, i am having a hard time understanding the doInBackground method as it expects me to return something. I have done all of the work on the getMovieJson method and i know i must return something from the doInBackground because it is required to update my custom adapter on the onPostExecute method. This custom adapter is an ArrayAdapter that creates the appropriate views to populate in my gridView.
This is my Model
package com.xxcanizeusxx.erick.moviesnow;
/**
* This class acts as the model base for our
* array of JSON Objects that need to be populated.\
* This class uses getters and setters to achieve its task.
*/
public class Movie {
private String title;
private String vote_average;
private String overview;
private String release_date;
private String poster_path;
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title = title;
}
public String getOverview(){
return overview;
}
public void setOverview(String overview){
this.overview = overview;
}
public String getRelease_date(){
return release_date;
}
public void setRelease_date(String release_date){
this.release_date = release_date;
}
public String getVote_average(){
return vote_average;
}
public void setVote_average(String vote_average){
this.vote_average = vote_average;
}
public String getPoster_path(){
return poster_path;
}
public void setPoster_path(String poster_path){
this.poster_path = poster_path;
}
}
This my Fragment
package com.xxcanizeusxx.erick.moviesnow;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import org.json.JSONArray;
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;
import java.util.ArrayList;
/**
* Created by Erick on 1/4/2017.
*/
public class MovieFragment extends Fragment {
//Initialize our array adapter and components.
private ArrayList<Movie> mMovieData;
private MovieAdapter mMovieAdapter;
//Empty constructor
public MovieFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.movie_fragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.popular_movies) {
updateMovie();
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateMovie() {
FetchMovieTask fetchMovie = new FetchMovieTask();
fetchMovie.execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Initialize our array adapter
mMovieData = new ArrayList<>();
mMovieAdapter = new MovieAdapter(getActivity(), R.layout.grid_movie_item, mMovieData);
View rootView = inflater.inflate(R.layout.gird_layout, container, false);
//Get a reference to the gridView and attach the adapter to it
GridView mGridView = (GridView) rootView.findViewById(R.id.gridView);
mGridView.setAdapter(mMovieAdapter);
return rootView;
}
#Override
public void onStart() {
super.onStart();
updateMovie();
}
public class FetchMovieTask extends AsyncTask<String[], Void, String[]> {
private final String LOG = FetchMovieTask.class.getSimpleName();
private String[] getMovieJson(String movieJsonStr) throws JSONException {
final String OWM_RESULTS = "results";
String title;
String posterPath;
JSONObject movieJson = new JSONObject(movieJsonStr);
JSONArray movieJsonArray = movieJson.getJSONArray(OWM_RESULTS);
Movie movieItem = new Movie();
//Newly created array that will house the data in order to check for views on the onPostExecute method
String[] results = new String[movieJsonStr.length()];
for (int i = 0; i < movieJsonArray.length(); i++) {
JSONObject movieObject = movieJsonArray.getJSONObject(i);
title = movieObject.getString("title");
posterPath = movieObject.getString("poster_path");
movieItem.setTitle(title);
movieItem.setPoster_path(posterPath);
results[i] = movieObject.getString(posterPath) +" " + movieObject.getString(posterPath);
}
mMovieData.add(movieItem);
return results;
}
#Override
protected String[] doInBackground(String[]... params) {
//Establish a connection
HttpURLConnection urlConnection = null;
BufferedReader bufferedReader = null;
//Will contain the raw JSON as a string
String movieJsonStr = null;
//String as placeholders
String descriptionHolder = "popularity.desc";
try {
//String to hold the Base url
final String TMDB_BASE_URL = "http://api.themoviedb.org/3/discover/movie?";
final String APPID = "api_key";
final String DESC = "sort_by";
//Build the url
Uri buildMovieUri = Uri.parse(TMDB_BASE_URL).buildUpon()
.appendQueryParameter(DESC, descriptionHolder)
.appendQueryParameter(APPID, BuildConfig.TMDP_API_KEY)
.build();
URL url = new URL(buildMovieUri.toString());
//Create the request to TMDB and open connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//Read the input stream into a string
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
//Nothing to do
return null;
}
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
//Make debugging easier by adding a new line to the bufffer stream
buffer.append(line + "\n");
int result = 1;
}
if (buffer.length() == 0) {
//stream was empty. No point in parsing.
return null;
}
movieJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG, "Error ", e);
//If code didnt get the movie data, no point in parsing
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (final IOException e) {
Log.e(LOG, "Error closing stream ", e);
}
}
}
try {
return getMovieJson(movieJsonStr);
} catch (JSONException e) {
Log.e(LOG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result){
if (result != null){
mMovieAdapter.clear();
for (String results : result ){
mMovieAdapter.setMovieData(results);
}
}
}
}
}
This is my Adapter
package com.xxcanizeusxx.erick.moviesnow;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* This class is the MovieAdapter that will take data from the model and
* display it on the View. Additionally, this adapter will load the picasso base_img_url
* to populate the griView according to Udacity.
*/
public class MovieAdapter extends ArrayAdapter<Movie> {
private final String BASE_IMAGE_URL = "http://image.tmdb.org/t/p/w185";
private Context mContext;
private int resource;
private ArrayList<Movie> mMovieData = new ArrayList<Movie>();
//Constructor matching super
public MovieAdapter(Context mContext, int resource, ArrayList<Movie> mMovieData) {
super(mContext, resource, mMovieData);
this.mContext = mContext;
this.resource = resource;
this.mMovieData = mMovieData;
}
//This method sets the movieData and refreshes the gridLayout items.
public void setMovieData(ArrayList<Movie> mMovieData){
this.mMovieData = mMovieData;
//Notifies if data state has changed
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
//Declare the variables to hold the convertView and viewHolder static class
View cv = convertView;
ViewHolder viewHolder;
//If the convertView is null, we don't have a view so, create one.
if(cv == null){
//Create the View
cv = LayoutInflater.from(getContext()).inflate(resource, parent, false);
//Call the static viewHolder class
viewHolder = new ViewHolder();
//Initialize the textView and imageView to load inside the view
viewHolder.movieTextView = (TextView) cv.findViewById(R.id.movie_title);
viewHolder.moviePoster = (ImageView) cv.findViewById(R.id.movie_poster);
cv.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) cv.getTag();
}
Movie movieItem = mMovieData.get(position);
//Set the textView holder
viewHolder.movieTextView.setText(movieItem.getTitle());
//use picasso to load images to the holder
Picasso.with(mContext).load(BASE_IMAGE_URL + movieItem.getPoster_path()).fit().into(viewHolder.moviePoster);
return cv;
}
static class ViewHolder{
TextView movieTextView;
ImageView moviePoster;
}
}
This is my Main Activity
package com.xxcanizeusxx.erick.moviesnow;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new MovieFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
//Inflate the menu, this adds items to actionbar if present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if (id == R.id.action_settings){
return true;
}
return super.onOptionsItemSelected(item);
}
}
My girdLayout xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/grid_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/gridView"
android:numColumns="2"
android:gravity="center"
android:drawSelectorOnTop="true"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp">
</GridView>
</FrameLayout>
My movieItem xml (To populate the gridLayout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/movie_detail_item"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/movie_poster"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="fitXY"/>
<TextView
android:id="#+id/movie_title"
android:maxLines="2"
android:gravity="center"
android:textSize="14sp"
android:textAllCaps="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Change the parameter of your Asynctask first
public class FetchMovieTask extends AsyncTask<Void, String[], String[]> {}
Then change the return type of your doInBackground() to get the results
#Override
protected String[] doInBackground(Void... params) {}
Understand the flow of parameters and return types.
UPDATE:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.gird_layout, container, false);
//Initialize our array adapter
mMovieData = new ArrayList<>();
updateView(mMovieData);
return rootView;
}
void updateView(ArrayList<>() movieData){
mMovieAdapter = new MovieAdapter(getActivity(), R.layout.grid_movie_item, movieData);
//Get a reference to the gridView and attach the adapter to it
GridView mGridView = (GridView) rootView.findViewById(R.id.gridView);
mGridView.setAdapter(mMovieAdapter);
}
Return ArrayList from your GetMovie & DoInBackground
#Override
protected ArrayList<Movies> doInBackground(Object... params) {}
and
private ArrayList<Movies> getMovieJson(String movieJsonStr) throws JSONException {
....
mMovieData.add(movieItem);
return mMovieData;
}
call this updateView to update rather setAdapater(..) and postExecute parameters to
#Override
protected void onPostExecute(ArrayList<Movies> movieData){
updateView(movieData);
}
First things is you code compiling ? From what I can See your AsyncTask has the following signature -
public class FetchMovieTask extends AsyncTask<String[], Void, Void> {
But You are returning String[] from doInBackground which ideally would give you an error.
Anyways, you don't have to return anything from the AsyncTask in your case. Just add this call on onPostExecute - mMovieAdapter.setMovieData(Arrays.asList(result))
Btw, the type result should be String[] and not String as I can see.

Custom List View with thumbnail using Android Volley Library will not load any results

I am trying to load a custom listview using Volley Networking library but there are no results while running the app and no errors on the code. The data come from a JSON file
JSON OUTPUT HERE
Below are my classes :
MainActivity.java
package info.androidhive.customlistviewvolley;
import info.androidhive.customlistviewvolley.adater.CustomListAdapter;
import info.androidhive.customlistviewvolley.app.AppController;
import info.androidhive.customlistviewvolley.model.CaseStudy;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
public class MainActivity extends Activity {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://178.62.67.237/api/v1/residential/?format=json";
private ProgressDialog pDialog;
private List<CaseStudy> caseList = new ArrayList<CaseStudy>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, caseList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
CaseStudy reference = new CaseStudy();
reference.setTitle(obj.getString("title"));
reference.setThumbnailUrl(obj.getString("image"));
reference.setPostcode(obj.getString("postcode"));
// adding movie to movies array
caseList.add(reference);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
CaseStudy.java:
package info.androidhive.customlistviewvolley.model;
public class CaseStudy {
private String title;
private String thumbnailUrl;
private String postcode;
public CaseStudy() {
}
public CaseStudy(String name, String thumbnailUrl, String postcode) {
this.title = name;
this.thumbnailUrl = thumbnailUrl;
this.postcode = postcode;
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = name;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getPostcode() {
return postcode;
}
}
CustomListAdapter.java:
package info.androidhive.customlistviewvolley.adater;
import info.androidhive.customlistviewvolley.R;
import info.androidhive.customlistviewvolley.app.AppController;
import info.androidhive.customlistviewvolley.model.CaseStudy;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<CaseStudy> caseItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<CaseStudy> caseItems) {
this.activity = activity;
this.caseItems = caseItems;
}
#Override
public int getCount() {
return caseItems.size();
}
#Override
public Object getItem(int location) {
return caseItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row_custom, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView postcode = (TextView) convertView.findViewById(R.id.postcode);
//TextView genre = (TextView) convertView.findViewById(R.id.genre);
//TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
// getting movie data for the row
CaseStudy c = caseItems.get(position);
// thumbnail image
thumbNail.setImageUrl(c.getThumbnailUrl(), imageLoader);
// title
title.setText(c.getTitle());
postcode.setText(c.getPostcode());
// rating
//rating.setText("Rating: " + String.valueOf(m.getRating()));
// genre
//String genreStr = "";
//for (String str : m.getGenre()) {
// genreStr += str + ", ";
//}
//genreStr = genreStr.length() > 0 ? genreStr.substring(0,
// genreStr.length() - 2) : genreStr;
//genre.setText(genreStr);
// release year
//year.setText(String.valueOf(m.getYear()));
return convertView;
}
}
ist_row_custom.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_row_selector"
android:padding="8dp" >
<!-- Thumbnail Image -->
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/thumbnail"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentLeft="true"
android:layout_marginRight="8dp" />
<!-- Title -->
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:textSize="#dimen/title"
android:textStyle="bold" />
<!-- Postcode-->
<TextView
android:id="#+id/postcode"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_marginTop="1dip"
android:layout_toRightOf="#+id/thumbnail"
android:textSize="#dimen/rating" />
<!-- Genre -->
<!-- Release Year -->
</RelativeLayout>
Any ideas what I have done wrong?
You are referring to wrong xml in you MainActivity. Kindly create a new xml for ex activity_main.xml and initiate your list view there.
Also in your code you are Calling JSONArray however your Json output shows it Json Object. Kindly change your code to JSONObject as shown below
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
hidePDialog();
System.out.println("JsonObject++===---"+jsonObject);
try {
JSONArray response = jsonObject.getJSONArray("objects");
for(int i=0; i <response.length(); i++){
JSONObject obj = response.getJSONObject(i);
CaseStudy reference = new CaseStudy();
reference.setTitle(obj.getString("title"));
reference.setThumbnailUrl(obj.getString("image_path"));
reference.setPostcode(obj.getString("postcode"));
// adding movie to movies array
caseList.add(reference);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
System.out.println("error");
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest, TAG);
According to your Json you should get 'image_path' not 'image' .
reference.setThumbnailUrl(obj.getString("image"));
use
reference.setThumbnailUrl(obj.getString("image_path"));

android setAdapter doesn't trigger getView or doesn't build ListView

Too many times asked but I can't find the issue in my own code.
As others, I have a one ArrayList and i need to display it.
The problem is that ListView isn't visible when activity get launched, I don't know why.
Here is my code:
layout: activity_dashboard_screen.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/ly_dashboard"
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.ciroreed.war_horizon.ui.Dashboard_screen" >
<TextView
android:id="#+id/tv_dashboard_display_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="username"
tools:ignore="HardcodedText" />
<TableRow
android:id="#+id/row_dashboard_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="end" >
</TableRow>
<TableRow
android:id="#+id/row_dashboard_2"
android:layout_width="fill_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/lv_dashboard_matchlist"
android:layout_width="fill_parent"
android:layout_height="match_parent" />
</TableRow>
Custom class that extends BaseAdapter: MatchAdapter.java
package com.ciroreed.war_horizon;
import java.util.ArrayList;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.TwoLineListItem;
import com.ciroreed.war_horizon.data.Match;
public class MatchAdapter extends BaseAdapter {
private Context con;
private ArrayList<Match> MATCHLIST;
public MatchAdapter(Context appcontext, ArrayList<Match> matchlist){
con = appcontext;
MATCHLIST = matchlist;
}
..............
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TwoLineListItem tll;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) con
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
tll = (TwoLineListItem) inflater.inflate(
android.R.layout.simple_list_item_2, parent);
} else {
tll = (TwoLineListItem) convertView;
}
TextView text1 = tll.getText1();
TextView text2 = tll.getText2();
text1.setText("VS "+MATCHLIST.get(position).getEnemy_name());
text2.setText("turno: "+MATCHLIST.get(position).isPlayerTurn());
return tll;
}
}
And here is the activity when may run it:
package com.ciroreed.war_horizon.ui;
import java.util.concurrent.ExecutionException;
import org.json.JSONException;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.ciroreed.war_horizon.Controller;
import com.ciroreed.war_horizon.MatchAdapter;
import com.ciroreed.war_horizon.R;
public class Dashboard_screen extends Activity implements OnClickListener{
private TextView tv_dashboard_username;
private ListView lv_dashboard_matchlist;
private MatchAdapter MATCHLIST_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard_screen);
init();
}
private void init() {
// TODO Auto-generated method stub
tv_dashboard_username = (TextView)findViewById(R.id.tv_dashboard_display_username);
lv_dashboard_matchlist = (ListView)findViewById(R.id.lv_dashboard_matchlist);
try {
if(Controller.getCurrentMatches()){
MATCHLIST_adapter = new MatchAdapter(getApplicationContext(), Controller.MATCHLIST);
Toast.makeText(getApplicationContext(), "Partidas cargadas correctamente", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Error al cargar las partidas", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MATCHLIST_adapter.notifyDataSetChanged();
lv_dashboard_matchlist.setAdapter(MATCHLIST_adapter);
}
When I execute, .. well, this is NOT the main activity. It runs as expected but and the ArrayList<Match> contains one element (at least)..
Please don't ask about how the previous code works like "Controller.getCurrentMatches()" IE that method gets a json with data from a remote server, excepts the code relative to the ListAdapter everything else was tested before and works fine.
What did you do in getCount() of your adapter?
You should return a value > 0 in getCount()
From http://www.vogella.com/tutorials/AndroidListView/article.html
Chapter: 13. Tutorial: How to display two items in a ListView
package de.vogella.android.listactivity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.SimpleAdapter;
public class MyTwoListItemsActivity extends ListActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<Map<String, String>> list = buildData();
String[] from = { "name", "purpose" };
int[] to = { android.R.id.text1, android.R.id.text2 };
SimpleAdapter adapter = new SimpleAdapter(this, list,
android.R.layout.simple_list_item_2, from, to);
setListAdapter(adapter);
}
private ArrayList<Map<String, String>> buildData() {
ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
list.add(putData("Android", "Mobile"));
list.add(putData("Windows7", "Windows7"));
list.add(putData("iPhone", "iPhone"));
return list;
}
private HashMap<String, String> putData(String name, String purpose) {
HashMap<String, String> item = new HashMap<String, String>();
item.put("name", name);
item.put("purpose", purpose);
return item;
}
}
This isn't the accurate response to this issue, but it solved my problem.

Categories

Resources