Overriding Getview Of Arrayadapter To Fill 3 Textviews
From my Activity, I am calling my MovieTask that extendsAsyncTask. I get Json response from the server which I have successfully parsed inside the doInBackground method of MovieTas
Solution 1:
When you setAdapter()
on an AdapterView
for example ListView
, getView()
is called internally and the views returned from the same are populated in the AdapterView
.
You might want to read and learn about how AdapterView
s and Adapter
s work. Go ahead and read some docs here:
What you need to do is:
Create a model for your data like:
publicclassMovie { publiclong id; public String date; public String title; publicdouble vote; publicMovie(long id, String date, String title, double vote){ this.id = id; this.date = date; this.title = title; this.vote = vote; } }
Create a layout to show movie details like:
<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><TextViewandroid:id="@+id/lbl_date"android:layout_width="wrap_content"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/lbl_title"android:layout_width="wrap_content"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/lbl_vote"android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout>
Change your adapter to handle
Movie
s rather thanString
s like:publicclassMovieListAdapterextendsArrayAdapter<Movie > { publicMovieListAdapter(Context context, List<Movie> objects) { super(context, 0, objects); } @Overridepublic View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.movie_item, parent, false); } ((TextView) convertView.findViewById(R.id.lbl_date)) .setText(getItem(position).date); ((TextView) convertView.findViewById(R.id.lbl_title)) .setText(getItem(position).title); ((TextView) convertView.findViewById(R.id.lbl_vote)) .setText(String.valueOf(getItem(position).vote)); return convertView; } }
Finally set the adapter after your for loop like:
privatevoidgetMovieDataFromJson(String JsonString)throws JSONException { JSONObjectjsonObject=newJSONObject(JsonString); JSONArrayresults= jsonObject.getJSONArray("results"); ArrayList<Movie> movies = newArrayList<>(); for (int i=0; i<results.length(); i++){ Stringtitle= results.getJSONObject(i).getString("original_title"); Stringdate= results.getJSONObject(i).getString("release_date"); longid= results.getJSONObject(i).getLong("id"); doublevote= results.getJSONObject(i).getDouble("vote_average"); movies.add(newMovie(id, date, title, vote)); } myMoviesListView.setAdapter(newMovieListAdapter(MainActivity.this, movies)); }
Post a Comment for "Overriding Getview Of Arrayadapter To Fill 3 Textviews"