How to implement a custom ArrayList in AsyncTask? - java

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.

Related

SearchView filter in ListView [duplicate]

here is my main activity
package com.javacodegeeks.android.lbs;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import lbs.promotion.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
public class Curve extends Activity {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> DaftarPromotion = new ArrayList<HashMap<String, String>>();
private static String url_daftar_promotion = "http://10.0.2.2/webserver_maaug/promotion/daftar_promotion.php";
String lon = "101.5178";
String lat = "3.0724";
public static final String TAG_SUCCESS = "success";
public static final String TAG_DAFTAR_PROMOTION = "daftar_promotion";
public static final String TAG_ID_PROMO = "PromoID";
public static final String TAG_NAMA_PROMO = "PromoName";
public static final String TAG_LINK_IMAGE_PROMO = "PromoImage";
public static final String TAG_DESC_PROMO= "PromoDesc";
public static final String TAG_CATE_PROMO = "PromoCate";
public static final String TAG_CONT_PROMO = "PromoContact";
public static final String TAG_DATES_PROMO = "PromoDateStart";
public static final String TAG_DATEE_PROMO = "PromoDateEnd";
JSONArray daftar_promotion = null;
ListView list;
PromotionListAdapter adapter;
EditText inputSearch;
private Curve activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_curve);
DaftarPromotion = new ArrayList<HashMap<String, String>>();
new Activity().execute();
activity = this;
list = (ListView) findViewById(R.id.list);
inputSearch = (EditText) findViewById(R.id.search_box);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
Curve.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = DaftarPromotion.get(position);
String pna = map.get(TAG_NAMA_PROMO);
String pde = map.get(TAG_DESC_PROMO);
String pca = map.get(TAG_CATE_PROMO);
String pcon = map.get(TAG_CONT_PROMO);
String pds = map.get(TAG_DATES_PROMO);
String pdae = map.get(TAG_DATEE_PROMO);
Toast.makeText(Curve.this, pna +"\n" + pde +"\n" + pca +"\n" + pds +" to " + pdae +"\n" + pcon,Toast.LENGTH_LONG).show();
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.smenu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
Toast.makeText(Curve.this,"Mobile Advertising Application Using GPS V1.0",Toast.LENGTH_LONG).show();
return true;
case R.id.search:{
Intent intent = new Intent(Curve.this, Search.class);
intent.putExtra("lon",lon);
intent.putExtra("lat",lat);
startActivity(intent);
//startActivity(new Intent(this, Search.class));
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void SetListViewAdapter(ArrayList<HashMap<String, String>> daftar) {
adapter = new PromotionListAdapter(activity, daftar);
list.setAdapter(adapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class Activity extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Curve.this);
pDialog.setMessage("Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_daftar_promotion, "GET",params);
Log.d("All Products: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
daftar_promotion = json.getJSONArray(TAG_DAFTAR_PROMOTION);
for (int i = 0; i < daftar_promotion.length();i++){
JSONObject c = daftar_promotion.getJSONObject(i);
String PromoID = c.getString(TAG_ID_PROMO);
String PromoName = c.getString(TAG_NAMA_PROMO);
String pat = "http://10.0.2.2/webserver_maaug/";
String PromoImage = pat + c.getString(TAG_LINK_IMAGE_PROMO);
String PromoDesc = c.getString(TAG_DESC_PROMO);
String PromoCate = c.getString(TAG_CATE_PROMO);
String PromoDateStart = c.getString(TAG_DATES_PROMO);
String PromoDateEnd = c.getString(TAG_DATEE_PROMO);
String PromoContact = c.getString(TAG_CONT_PROMO);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID_PROMO, PromoID);
map.put(TAG_NAMA_PROMO, PromoName);
map.put(TAG_LINK_IMAGE_PROMO, PromoImage);
map.put(TAG_DESC_PROMO, PromoDesc);
map.put(TAG_CATE_PROMO, PromoCate);
map.put(TAG_DATES_PROMO, PromoDateStart);
map.put(TAG_DATEE_PROMO, PromoDateEnd);
map.put(TAG_CONT_PROMO, PromoContact);
DaftarPromotion.add(map);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
SetListViewAdapter(DaftarPromotion);
}
});
}
}
}
and this is my custom adapter, it is a very simple one, without an object class of it's own
package lbs.promotion;
import java.util.ArrayList;
import java.util.HashMap;
import com.javacodegeeks.android.lbs.Curve;
import com.javacodegeeks.android.lbs.R;
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.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
public class PromotionListAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public PromotionListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)vi = inflater.inflate(R.layout.item_list_promotion, null);
TextView PromoID = (TextView) vi.findViewById(R.id.PromoID);
TextView PromoName = (TextView) vi.findViewById(R.id.PromoName);
TextView PromoImage = (TextView) vi.findViewById(R.id.PromoImage);
TextView PromoDesc = (TextView) vi.findViewById(R.id.PromoDesc);
TextView PromoCate = (TextView) vi.findViewById(R.id.PromoCate);
TextView PromoContact = (TextView) vi.findViewById(R.id.PromoContact);
TextView PromoDateStart = (TextView) vi.findViewById(R.id.PromoDateStart);
TextView PromoDateEnd = (TextView) vi.findViewById(R.id.PromoDateEnd);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.image_promo);
HashMap<String, String> daftar_promotion = new HashMap<String, String>();
daftar_promotion = data.get(position);
PromoID.setText(daftar_promotion.get(Curve.TAG_ID_PROMO));
PromoName.setText(daftar_promotion.get(Curve.TAG_NAMA_PROMO));
PromoImage.setText(daftar_promotion.get(Curve.TAG_LINK_IMAGE_PROMO));
PromoDesc.setText(daftar_promotion.get(Curve.TAG_DESC_PROMO));
PromoCate.setText(daftar_promotion.get(Curve.TAG_CATE_PROMO));
PromoContact.setText(daftar_promotion.get(Curve.TAG_CONT_PROMO));
PromoDateStart.setText(daftar_promotion.get(Curve.TAG_DATES_PROMO));
PromoDateEnd.setText(daftar_promotion.get(Curve.TAG_DATEE_PROMO));
imageLoader.DisplayImage(daftar_promotion.get(Curve.TAG_LINK_IMAGE_PROMO),thumb_image);
return vi;
}
}
here is my layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<!-- Editext for Search -->
<EditText android:id="#+id/search_box"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="type to search"
android:inputType="text"
android:maxLines="1"/>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#040404"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" />
</LinearLayout>
how do i get the getfilter() function working? or is there any simpler way to implement filtering in my listview? i want to filter based on my PromoName
A Filter has two major components, the performFiltering(CharSequence) method and the publishResults(CharSequence, FilterResults) method. In your PromotionListAdapter, you'll need to implement the Filterable interface then Override the getFilter() method to return a new Filter that has these methods implemented.
The performFiltering(CharSequence) method is where you'll do the bulk of your work. The CharSequence argument is the data which you're filtering on. Here, you'll first want to determine if the list should even be filtered as the base case. Once you've decided to perform the filtering, create a new ArrayList for your filtered dataset (in your case, a new ArrayList>), and loop through your complete set of list items, adding the values that match the filter to your new ArrayList.
The return type for the performFiltering method is FilterResults. FilterResults is a simple object with two variables, int count and Object results. Once performFiltering has created the new ArrayList with the filtered data, create a new FilterResults, setting your new ArrayList as results and the size of that ArrayList as count.
The publishResults(CharSequence, FilterResults) method is called after performFiltering() returns. The CharSequence parameter is the same String you were filtering on. The FilterResults parameter is the return from performFiltering(). In this method, you'll want to set your new ArrayList as the data source for your List and then call notifyDataSetChanged() to update the UI.
In order to implement this, I've had success when my Adapter keeps track of both the original ArrayList of data and a filtered ArrayList of what is currently being shown. Here's some boilerplate code based on your adapter that can help get you started. I've commented above important lines.
public class PromotionListAdapter extends BaseAdapter implements Filterable
{
private Activity activity;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
//Two data sources, the original data and filtered data
private ArrayList<HashMap<String, String>> originalData;
private ArrayList<HashMap<String, String>> filteredData;
public PromotionListAdapter(Activity a, ArrayList<HashMap<String, String>> d)
{
activity = a;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
//To start, set both data sources to the incoming data
originalData = d;
filteredData = d;
}
//For this helper method, return based on filteredData
public int getCount()
{
return filteredData.size();
}
//This should return a data object, not an int
public Object getItem(int position)
{
return filteredData.get(position);
}
public long getItemId(int position)
{
return position;
}
//The only change here is that we'll use filteredData.get(position)
//Even better would be to use getItem(position), which uses the helper method (see the getItem() method above)
public View getView(int position, View convertView, ViewGroup parent)
{
View vi = convertView;
if (convertView == null)vi = inflater.inflate(R.layout.item_list_promotion, null);
TextView PromoID = (TextView) vi.findViewById(R.id.PromoID);
TextView PromoName = (TextView) vi.findViewById(R.id.PromoName);
TextView PromoImage = (TextView) vi.findViewById(R.id.PromoImage);
TextView PromoDesc = (TextView) vi.findViewById(R.id.PromoDesc);
TextView PromoCate = (TextView) vi.findViewById(R.id.PromoCate);
TextView PromoContact = (TextView) vi.findViewById(R.id.PromoContact);
TextView PromoDateStart = (TextView) vi.findViewById(R.id.PromoDateStart);
TextView PromoDateEnd = (TextView) vi.findViewById(R.id.PromoDateEnd);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.image_promo);
HashMap<String, String> daftar_promotion = new HashMap<String, String>();
//Get data from filtered Data
//This line can be replaced with:
// daftar_promotion = getItem(position);
daftar_promotion = filteredData.get(position);
PromoID.setText(daftar_promotion.get(Curve.TAG_ID_PROMO));
PromoName.setText(daftar_promotion.get(Curve.TAG_NAMA_PROMO));
PromoImage.setText(daftar_promotion.get(Curve.TAG_LINK_IMAGE_PROMO));
PromoDesc.setText(daftar_promotion.get(Curve.TAG_DESC_PROMO));
PromoCate.setText(daftar_promotion.get(Curve.TAG_CATE_PROMO));
PromoContact.setText(daftar_promotion.get(Curve.TAG_CONT_PROMO));
PromoDateStart.setText(daftar_promotion.get(Curve.TAG_DATES_PROMO));
PromoDateEnd.setText(daftar_promotion.get(Curve.TAG_DATEE_PROMO));
imageLoader.DisplayImage(daftar_promotion.get(Curve.TAG_LINK_IMAGE_PROMO),thumb_image);
return vi;
}
#Override
public Filter getFilter()
{
return new Filter()
{
#Override
protected FilterResults performFiltering(CharSequence charSequence)
{
FilterResults results = new FilterResults();
//If there's nothing to filter on, return the original data for your list
if(charSequence == null || charSequence.length() == 0)
{
results.values = originalData;
results.count = originalData.size();
}
else
{
ArrayList<HashMap<String,String>> filterResultsData = new ArrayList<HashMap<String,String>>();
for(HashMap<String,String> data : originalData)
{
//In this loop, you'll filter through originalData and compare each item to charSequence.
//If you find a match, add it to your new ArrayList
//I'm not sure how you're going to do comparison, so you'll need to fill out this conditional
if(data matches your filter criteria)
{
filterResultsData.add(data);
}
}
results.values = filterResultsData;
results.count = filteredResultsData.size();
}
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults)
{
filteredData = (ArrayList<HashMap<String,String>>)filterResults.values;
notifyDataSetChanged();
}
};
}
}
And there you have it! As far as I can tell, you've already implemented the TextWatcher for your inputText EditText set up properly, so adding the getFilter() method and making a few other minor changes to your Adapter should lead you to a solution. I believe you can also create a member variable on your Adapter for your Filter, so you're not creating a new instance of the class each time getFilter() is called, but I copy/pasted this from a previous project of mine and am sure it works this way. Play with it and see what works for you! Hope this helps! And please do comment if you need anything clarified.
you adapter needs to implement Filterable .
for more info about this (and about listView) , watch the video "the world of listView"
here's a sample code:
http://codetheory.in/android-filters/

Pass fragment activity context to custom listview adapter

I have a custom listview adapter setup up that I need to call in my fragment, but I can't seem the pass my activity to it. I have a very similar set up, but called from within an activity, and it works very well. So, I think the issue is with passing the activity context to the adapter, but I'm not sure how to achieve it.
Below is the code for my fragment, where I make the call to my custom adapter:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
public class SiblingUnitFragment extends Fragment {
Context siblingContext = this.getActivity();
Activity context = this.getActivity();
ProgressDialog progressDialog;
ListView siblingLVAdapter;
String ReadOnly;
String LexaUser;
String Password;
String SearchValue;
String finalResultSiblings;
String HttpURLSiblings = "https://[myDataSpot]/getSiblings.php";
HashMap<String, String> hashMapSiblings = new HashMap<>();
HttpParse httpParse = new HttpParse();
String[] Uuid;
String[] Usize;
String[] Ustatus;
String SV;
String[] svSeparated;
ListView siblingListView;
public SiblingUnitFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_siblings, container, false);
siblingListView = (ListView) view.findViewById(R.id.SiblingsList);
return view;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getArguments() != null) {
SV = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
}
if (SV.contains("-")) {
svSeparated = SV.split("-");
SearchValue = svSeparated[0];
getSiblings(SearchValue, LexaUser);
} else {
SearchValue = SV;
getSiblings(SearchValue, LexaUser);
}
}
public void getSiblings(String searchInput, String lexaUser) {
class SiblingsClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(siblingContext, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
if (httpResponseMsg != null) {
try {
JSONArray json = new JSONArray(httpResponseMsg);
Uuid = new String[json.length()];
Usize = new String[json.length()];
Ustatus = new String[json.length()];
for (int i = 0; i < json.length(); i++) {
JSONObject object = json.getJSONObject(i);
Uuid[i] = object.getString("id");
Usize[i] = object.getString("size");
Ustatus[i] = object.getString("status");
}
siblingLVAdapter = new SiblingsListViewAdapter(context, Uuid, Usize, Ustatus);
siblingListView.setAdapter(siblingLVAdapter);
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
Toast.makeText(siblingContext, "Error: " + e.toString(), Toast.LENGTH_LONG).show();
} // catch (JSONException e)
progressDialog.dismiss();
} else {
progressDialog.dismiss();
Toast.makeText(siblingContext, "HttpResponseMsg is null.", Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
hashMapSiblings.put("searchinput", params[0]);
hashMapSiblings.put("lexauser", params[1]);
finalResultSiblings = httpParse.postRequest(hashMapSiblings, HttpURLSiblings);
return finalResultSiblings;
}
}
SiblingsClass siblingsClass = new SiblingsClass();
siblingsClass.execute(searchInput, lexaUser);
}
}
And this is my code for the adapter:
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class SiblingsListViewAdapter extends BaseAdapter {
Activity context;
String Uuid[];
String Usize[];
String Ustatus[];
public SiblingsListViewAdapter(Activity context, String[] Uuid, String[] Usize, String[] Ustatus) {
super();
this.context = context;
this.Uuid = Uuid;
this.Usize = Usize;
this.Ustatus = Ustatus;
}
public int getCount() {
// TODO Auto-generated method stub
return Uuid.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewUid;
TextView txtViewSize;
TextView txtViewStatus;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.siblings_list, null);
holder = new ViewHolder();
holder.txtViewUid = (TextView) convertView.findViewById(R.id.SiblingsUid);
holder.txtViewSize = (TextView) convertView.findViewById(R.id.SiblingsSize);
holder.txtViewStatus = (TextView) convertView.findViewById(R.id.SiblingsStatus);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtViewUid.setText(Uuid[position]);
holder.txtViewSize.setText(Usize[position]);
holder.txtViewStatus.setText(Ustatus[position]);
return convertView;
}
}
And here is the logcat error:
error: incompatible types: SiblingsListViewAdapter cannot be converted to ListView
All help is appreciated. Thank you!
A per the Fragment Lifecycle, You need to call getContext only after onAttach method of your fragment lifecycle is called otherwise there is no associated activity hence there is no context
so use it like
// declare context
Context siblingContext ;
then initialise it
.. onCreateView(...){
siblingContext = getContext();
context = getActvity();
}
you mistake in instantiate your adapter in line 24.change ListView siblingLVAdapter; to
SiblingsListViewAdapter siblingLVAdapter;
and use Context context =getActivity(); or Activity activity=getActivity(); in onAtach methode

Android JSON Parsing images into imageview with cached thumbnails

I'm trying to develop an app which works by parsing json and adding parsed json into Imageview. I set a GridView and Imageview into it as a row. When I run app, pictures get parsed as well but when I scroll down, the thumbnails get lost.
The video at this URL Json thumbs shows what I mean.
Here my MainActivity.java:
package berkantkz.wallstation;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.baoyz.widget.PullRefreshLayout;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<Actors> actorsList;
ActorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar tool_bar = (Toolbar) findViewById(R.id.tool_bar);
tool_bar.setTitle(R.string.app_name);
tool_bar.setLogo(R.mipmap.ic_launcher);
ProgressBar spinner = (ProgressBar) findViewById(R.id.spinner);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("https://raw.githubusercontent.com/berkantkz/misc/master/sample.json");
PullRefreshLayout layout = (PullRefreshLayout) findViewById(R.id.swipeRefreshLayout);
// listen refresh event
layout.setRefreshStyle(PullRefreshLayout.STYLE_MATERIAL);
layout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// start refresh
Intent i = new Intent(MainActivity.this, MainActivity.class); //your class
startActivity(i);
finish();
}
});
// refresh complete
layout.setRefreshing(false);
final GridView listview = (GridView) findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, final int position, long id) {
//
final ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar);
pb.setVisibility(View.VISIBLE);
final Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
toolbar.setVisibility(View.GONE);
LinearLayout linearlayout = (LinearLayout) findViewById(R.id.LinearLayout1);
linearlayout.setBackgroundColor(getResources().getColor(R.color.black));
//TextView tv = (TextView) findViewById(R.id.tvName);
//tv.setVisibility(View.VISIBLE);
final ImageView iv = (ImageView) findViewById(R.id.expanded_image);
Picasso.with(MainActivity.this)
.load(actorsList.get(position).getImage())
.into(iv, new Callback() {
#Override
public void onSuccess() {
pb.setVisibility(View.GONE);
}
#Override
public void onError() {
}
});
iv.setVisibility(View.VISIBLE);
listview.setVisibility(View.GONE);
//
}
});
}
#Override
public void onBackPressed() {
final Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
toolbar.setVisibility(View.VISIBLE);
ImageView iv = (ImageView) findViewById(R.id.expanded_image);
iv.setVisibility(View.GONE);
GridView listview = (GridView) findViewById(R.id.list);
listview.setVisibility(View.VISIBLE);
LinearLayout ln = (LinearLayout) findViewById(R.id.LinearLayout1);
ln.setBackgroundColor(getResources().getColor(R.color.default_bg));
ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar);
pb.setVisibility(View.GONE);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setImage(object.getString("image"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if (result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.refresh) {
// TODO Auto-generated method stub
}
return super.onOptionsItemSelected(item);
}
}
Actors.java
package berkantkz.wallstation;
/**
* Created by berka on 1.12.2016.
*/
public class Actors {
private String name;
private String description;
private String image;
public Actors() {
}
//Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
ActorAdapter.java
package berkantkz.wallstation;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Created by berka on 25.11.2016.
*/
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
Log.d("Deneme", "birinci");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("Deneme", "iki");
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
//holder.tvName = (TextView) v.findViewById(R.id.tvName);
//holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.transparent);
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
//holder.tvName.setText(actorList.get(position).getName());
//holder.tvDescription.setText(actorList.get(position).getDescription());
return v;
}
static class ViewHolder {
public ImageView imageview;
//public TextView tvName;
//public TextView tvDescription;
}
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 mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}

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

Tabbed fragment don't show listviews

i try to combine tabbed fragment with listview. I fetch data by JSON and put it in listview in fragment but when i start app fragment don't show list view.
Actors.java
`
public class Actors {
private String name;
private String description;
private String dob;
private String country;
private String height;
private String spouse;
private String children;
private String image;
public Actors() {
// TODO Auto-generated constructor stub
}
public Actors(String name, String description, String dob, String country,
String height, String spouse, String children, String image) {
super();
this.name = name;
this.description = description;
this.dob = dob;
this.country = country;
this.height = height;
this.spouse = spouse;
this.children = children;
//this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
}
`
ActorAdapter.java
`
import java.io.InputStream;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// this.vi = LayoutInflater.from(context);
this.Resource = resource;
this.actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
// holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
holder.tvName = (TextView) v.findViewById(R.id.tvName);
holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
//holder.imageview.setImageResource(R.drawable.ic_launcher);
//new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
holder.tvName.setText(actorList.get(position).getName());
holder.tvDescription.setText(actorList.get(position).getDescription());
holder.tvDOB.setText("Pubblicato il: " + actorList.get(position).getDob());
holder.tvCountry.setText(actorList.get(position).getCountry());
holder.tvHeight.setText("Categoria: " + actorList.get(position).getHeight());
return v;
}
static class ViewHolder {
//public ImageView imageview;
public TextView tvName;
public TextView tvDescription;
public TextView tvDOB;
public TextView tvCountry;
public TextView tvHeight;
}
/*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);
}
}*/
}
Main.java
import info.androidhive.tabsswipe.adapter.TabsPagerAdapter;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Top Rated", "Games", "Movies" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
TopRatedFragment.java
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
public class TopRatedFragment extends Fragment {
ArrayList<Actors> actorsList;
Context context=getActivity();
ActorAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://www.technologici.it/api/get_recent_posts/");
ListView listview = (ListView)rootView.findViewById(R.id.list);
context = getActivity();
listview.setAdapter(new ActorAdapter(getActivity(), R.layout.row, actorsList));
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
// Starting single contact activity
Intent in = new Intent(getActivity(),
SingleContactActivity.class);
in.putExtra("title", actorsList.get(position).getName());
in.putExtra("author", actorsList.get(position).getCountry());
in.putExtra("data", actorsList.get(position).getDob());
in.putExtra("content", actorsList.get(position).getDescription());
in.putExtra("category", actorsList.get(position).getHeight());
//in.putExtra("image", actorsList.get(position).getImage());
startActivity(in);
}
});
setRetainInstance(true);
return rootView;
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Caricamento...");
dialog.setTitle("Contattando il server...");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("posts");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("title"));
actor.setDescription(object.getString("content"));
actor.setDob(object.getString("date"));
JSONObject author = object.getJSONObject("author");
actor.setCountry(author.getString("name"));
JSONArray catarray = object.getJSONArray("categories");
JSONObject catobject = catarray.getJSONObject(0);
actor.setHeight(catobject.getString("title"));
// JSONArray imgarray = object.getJSONArray("attachments");
// JSONObject imgobject = imgarray.getJSONObject(0);
//actor.setImage(imgobject.getString("url"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
// adapter.notifyDataSetChanged();
if (result == false) {
Toast.makeText(getActivity(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
}
Layout:
fragment_top_rated.xml
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:listitem="#layout/row" >
</ListView>
</LinearLayout>
row.xml
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tom Cruise"
android:textColor="#166CED"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvDateOfBirth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#D64530"
android:text="Date of Birth: July 3, 1962" />
<TextView
android:id="#+id/tvHeight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Height: 1.80 m"
android:textColor="#D64530"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/tvCountry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#D64530"
android:text="United States" />
<TextView
android:id="#+id/tvDescriptionn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#009A57"
android:text="Description"
android:visibility="gone"/>
</LinearLayout>
`
Can someone help me?

Categories

Resources