ListView repeating same JSON items on every Button click - android

I have a ListView on my main Activity and a button to fetch the JSON.
If I repeat the Button click, the same JSON elements is added to the ListView.
How can I clear the ListView if I click the Button again ?
CustomListAdapter
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Vehicle> vehicleItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Vehicle> vehicleItems) {
this.activity = activity;
this.vehicleItems = vehicleItems;
}
#Override
public int getCount() {
return vehicleItems.size();
}
#Override
public Object getItem(int location) {
return vehicleItems.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, 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 rating = (TextView) convertView.findViewById(R.id.rating);
TextView genre = (TextView) convertView.findViewById(R.id.genre);
TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
// getting movie data for the row
Vehicle m = vehicleItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
// 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;
}
}
SearchActivity
public class SearchActivity extends Activity implements View.OnClickListener {
// Log tag
private static final String TAG = SearchActivity.class.getSimpleName();
// Vehicles json url
private static final String url = "https://api.myjson.com/bins/3u7ty";
private SweetAlertDialog pDialog;
private List<Vehicle> vehicleList = new ArrayList<Vehicle>();
private ListView listView;
private CustomListAdapter adapter;
private Button buttonGet2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
buttonGet2 = (Button) findViewById(R.id.buttonGet2);
buttonGet2.setOnClickListener(this);
}
private void getData() {
listView=(ListView) findViewById(R.id.list2);
adapter=new CustomListAdapter(this,vehicleList);
listView.setAdapter(adapter);
final SweetAlertDialog pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
pDialog.setTitleText("Loading");
pDialog.setCancelable(true);
// Showing progress dialog before making http request
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest vehicleReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
pDialog.dismissWithAnimation();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Vehicle vehicle = new Vehicle();
vehicle.setTitle(obj.getString("title"));
vehicle.setThumbnailUrl(obj.getString("image"));
vehicle.setRating(((Number) obj.get("rating"))
.doubleValue());
vehicle.setYear(obj.getInt("releaseYear"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
vehicle.setGenre(genre);
// adding vehicle to vehicles array
vehicleList.add(vehicle);
} 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());
pDialog.dismissWithAnimation();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(vehicleReq);
}
#Override
public void onClick(View v) {
getData();
}
}

You are adding the content of Json object to your vehicleList again and again. The vehicleList still holds the old values. Then you catch the values from the Json object again and add it again to the vehicleList. To get rid of this, clear the list:
private void getData() {
vehicleList.clear();
listView=(ListView) findViewById(R.id.list2);
adapter=new CustomListAdapter(this,vehicleList);
//rest of your code
}

Along with clearing the data, just make that method only responsible for getting the data, not repeating initializing the adapter and list.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
buttonGet2 = (Button) findViewById(R.id.buttonGet2);
buttonGet2.setOnClickListener(this);
// Moved these lines
listView = (ListView) findViewById(R.id.list2);
adapter = new CustomListAdapter(this,vehicleList);
listView.setAdapter(adapter);
}
private void getData() {
vehicleList.clear(); // Added this
final SweetAlertDialog pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
pDialog.setTitleText("Loading");
pDialog.setCancelable(true);

Related

in listview notifyDataSetChanged() methode has error

this is my main class where i am setting the adapter and calling the notifydatasetchanged() method the aim is to show the history of user in listview and refresh as the data is changed,but having error as stated earlier
public class HistoryActivity extends AppCompatActivity {
// Log tag
private static final String TAG = HistoryActivity.class.getSimpleName();
private static final String url ="http://192.168.0.102/android_login_api/historyfetch.php";
private ProgressDialog pDialog;
private List<HistoryItems> historyList = new ArrayList<HistoryItems>();
private ListView listView;
private CustomListAdapter adapter;
private SQLiteHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, historyList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
db = new SQLiteHandler(getApplicationContext());
HashMap<String, String> user = db.getUserDetails();
String user_email = user.get("email");
gethistory(user_email);
}
private void gethistory(final String email)
{
StringRequest stringRequest= new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG,response.toString());
hideDialog();
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0;i<response.length();i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
HistoryItems historyItems = new HistoryItems();
historyItems.setName(obj.getString("user_email"));
historyItems.setLat_from(obj.getDouble("latitude_from"));
historyItems.setLon_from(obj.getDouble("longitude_from"));
historyItems.setLat_to(obj.getDouble("latitude_to"));
historyItems.setLon_to(obj.getDouble("longitude"));
historyItems.setDate(obj.getString("created_at"));
historyList.add(historyItems);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter;
})
{
protected Map<String,String>getParams(){
Map<String, String> params=new HashMap<>();
params.put("user_email",email);
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
this is my custom adapter:-
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<HistoryItems> historyItems;
public CustomListAdapter(Activity activity, List<HistoryItems> historyItems) {
this.activity = activity;
this.historyItems = historyItems;
}
#Override
public int getCount() {
return historyItems.size();
}
#Override
public Object getItem(int location) {
return historyItems.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, null);
TextView user_email = (TextView) convertView.findViewById(R.id.tv_user_email);
TextView lat_from = (TextView) convertView.findViewById(R.id.tv_lat_from);
TextView lon_from = (TextView) convertView.findViewById(R.id.tv_lon_from);
TextView lat_to = (TextView) convertView.findViewById(R.id.tv_lat_to);
TextView lon_to = (TextView) convertView.findViewById(R.id.tv_lon_to);
TextView date = (TextView) convertView.findViewById(R.id.tv_date);
// getting billionaires data for the row
HistoryItems m = historyItems.get(position);
// name
user_email.setText(m.getUser_email());
//
lat_from.setText(String.valueOf(m.getLat_from()));
lon_from.setText(String.valueOf(m.getLon_from()));
lat_to.setText(String.valueOf(m.getLat_to()));
lon_to.setText(String.valueOf(m.getLon_to()));
date.setText(String.valueOf(m.getDate()));
return convertView;
}
}
i am not getting where i made mistake
any help will be helpful....
hey man i didn't see any notifydatasetchanged() in your code i just see adapter;
Solution ==> adapter.notifydatasetchanged(); should be put after catch not outside the method
you have to give notifyDataSetChanged() for your adapter...
like this
for(int i=0;i<response.length();i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
HistoryItems historyItems = new HistoryItems();
.
.
.
.
historyList.add(historyItems);
}
adapter.notifyDataSetChanged();
Hope, It will help you :)
every time u add new item adapter will add new item in the listview.
for(int i=0;i<response.length();i++)
{
JSONObject obj = jsonArray.getJSONObject(i);
HistoryItems historyItems = new HistoryItems();
historyItems.setName(obj.getString("user_email"));
historyItems.setLat_from(obj.getDouble("latitude_from"));
historyItems.setLon_from(obj.getDouble("longitude_from"));
historyItems.setLat_to(obj.getDouble("latitude_to"));
historyItems.setLon_to(obj.getDouble("longitude"));
historyItems.setDate(obj.getString("created_at"));
historyList.add(historyItems);
adapter.notifyDataSetChanged();
}

adapter.CustomListAdapter.getCount Exception

private List<Product> movieList = new ArrayList<Product>();
In my "Favorite" Fragment, If I get my favorite list:
movieList = sharedPreference.getFavorites(activity); // movieList is some data that I get with JSON
Before initializing my custom adapter:
adapter = new CustomListAdapter(activity, movieList);
I'll get this exception:
java.lang.NullPointerException
at com.company.myapp.adater.CustomListAdapter.getCount(CustomListAdapter.java:63)
at android.widget.ListView.setAdapter(ListView.java:463)
And if I get favorite list after initializing adapter my favorite list will not show anything.
"This exception will come up only if my favorite list is empty"
Fragment
public class ZZZFavorites extends Fragment{
View view ;
Activity activity;
SharedPreference sharedPreference;
private static final String url = "http://symphonyrecords.ir/apps/ringtone/movies2.json";
private ProgressDialog pDialog;
private List<Product> movieList = new ArrayList<Product>();
private ListView listView;
private CustomListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
sharedPreference = new SharedPreference();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.android_hive_main_activity, container, false);
listView = (ListView) view.findViewById(R.id.list);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
movieList = sharedPreference.getFavorites(activity);
adapter = new CustomListAdapter(activity, movieList);
listView.setAdapter(adapter);
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);
Product movie = new Product();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating")).doubleValue());
movie.setYear(obj.getInt("id"));
// Genre is array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
}
catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
return view;
}
}
Adapter
public class CustomListAdapter extends ArrayAdapter<Product> {
private Activity activity;
private LayoutInflater inflater;
private List<Product> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
SharedPreference sharedPreference;
public CustomListAdapter(Activity activity, List<Product> movieItems) {
super(activity, R.layout.android_hive_list_row, movieItems);
this.activity = activity;
this.movieItems = movieItems;
sharedPreference = new SharedPreference();
}
static class ViewHolder {
private TextView title ;
private TextView rating ;
private TextView genre ;
private TextView year ;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Product getItem(int position) {
return movieItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.android_hive_list_row, null);
convertView.setTag(holder);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.rating = (TextView) convertView.findViewById(R.id.rating);
holder.genre = (TextView) convertView.findViewById(R.id.genre);
holder.year = (TextView) convertView.findViewById(R.id.releaseYear);
}else{
holder = (ViewHolder) convertView.getTag();
}
Product m = movieItems.get(position);
holder.title.setText(m.getTitle());
holder.rating.setText("Rating: " + String.valueOf(m.getRating()));
String genreStr = "";
for (String str : m.getGenre()) {
genreStr += str + ", ";
}
genreStr = genreStr.length() > 0 ? genreStr.substring(0,genreStr.length() - 2) : genreStr;
holder.genre.setText(genreStr);
holder.year.setText(String.valueOf(m.getYear()));
return convertView;
}
}
Change your getCount() method to this:
#Override
public int getCount() {
if(movieItens == null{
return 0;
} else {
return movieItens.isEmpty()? 0 : movieItems.size();
}
}

list doubles when back pressed in fragment

This is my Fragment in navigation view, it is opened as default when I clicked an item in navigation view and return back to this fragment the items in lists are doubled for example in list it has apple when i press back it shows two apples
public class AllProductsActivity extends Fragment {
private static final String TAG = MainActivity.class.getSimpleName();
private String category_id;
// Movies json url
private String url ;
private ProgressDialog pDialog;
private List<Movie> movieList=new ArrayList<Movie>() ;
private ListView listView;
private CustomListAdapter adapter;
public AllProductsActivity() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle bundle=getArguments();
category_id = bundle.getString("IDS");
View rootView = inflater.inflate(R.layout.category_layout, container, false);
listView = (ListView) rootView.findViewById(R.id.categories_list);
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
category_id = bundle.getString("IDS");
VerifyURL();
return rootView;
}
private void VerifyURL() {
if (category_id.equals("no_product")) {
url = "http://192.168.43.149/Newfolder/gap.php";
DownloadJSON();
}else{
url = "http://192.168.43.149/Newfolder/gap.php?category_id=" + category_id;
DownloadJSON();
}
}
private void DownloadJSON(){
pDialog=new
ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// 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);
Movie movie = new Movie();
movie.setTitle(obj.getString("name"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(obj.getString("price"));
movie.setYear(obj.getString("description"));
// adding movie to movies array
movieList.add(movie);
} 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;
} }}
This is my Adapter class where it opens a Activity i want to open a Fragment I already changed get Fragment manager to the get child Fragment manager but it does not work
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
HashMap<String, String> m = new HashMap<String, String>();
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount()
{
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final 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.all_products, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.PI1);
ImageButton AddcarT=(ImageButton) convertView.findViewById(R.id.product_add_cart);
TextView title = (TextView) convertView.findViewById(R.id.PN1);
TextView rating = (TextView) convertView.findViewById(R.id.PD1);
TextView genre = (TextView) convertView.findViewById(R.id.PD2);
// getting movie data for the row
final Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
// rating
rating.setText("Rating: " + String.valueOf(m.getRating()));
// genre
genre.setText(m.getYear());
// release year
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
Movie m = movieItems.get(position);
Intent intent = new Intent(activity, ProductsViewActivity.class);
// Pass all data rank
intent.putExtra("rank", m.getTitle());
intent.putExtra("flag", m.getThumbnailUrl());
activity.startActivity(intent);
}
});
AddcarT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
Movie m = movieItems.get(position);
Toast.makeText(activity, m.getTitle(), Toast.LENGTH_LONG).show();
// Pass all data rank
}
});
return convertView;}
}
If you're not calling your api multiple times to use pagination, call movieList.clear() or movieList = new ArrayList<>(); before adding data into it.
So your code will be:-
// Checking of movieList is not null
if(movieList != null) {
movieList.clear();
} else {
movieList = new ArrayList<>();
}
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("name"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(obj.getString("price"));
movie.setYear(obj.getString("description"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
In onCreateView() method, clear your list.
movieList.clear();
use this:
if (adapter==null) {
prod = new ArrayList<>();
adapter = new ProductsAdapter(prod, getActivity());
if (Constants.isNetworkAvailable(getActivity())){
recyclerView.setLayoutManager(GlayoutManager);
recyclerView.setAdapter(adapter);
}else {
Constants.showToast(getActivity(),"No Internet!!");
recyclerView.setLayoutManager(GlayoutManager);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}else{
recyclerView.setLayoutManager(GlayoutManager);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
Simply clear the list before adding data into ArrayList. It means when you click on the back press it will clear first and then insert data into the list. So you always get an updated list.
list.clear()

Having trouble implementing onClickListener for a custom ListAdapter Listview

I am having trouble implementing onItemClick for my ListView . I need to open a new activity on clicking the item in my ListView and pass the title/genre/rating/release year data to this new activity. I would also like to know how can I pass the thumbnail image of the clicked Item in ListView and display it in a new activity.
CustomListAdapter.java
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.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, 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 rating = (TextView) convertView.findViewById(R.id.rating);
TextView genre = (TextView) convertView.findViewById(R.id.genre);
TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
// getting movie data for the row
Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
// 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;
}
}
Main2Activity.java
public class Main2Activity extends AppCompatActivity {
// Log tag
private static final String TAG = Main2Activity.class.getSimpleName();
// Movies json url
private static final String url = "http://api.androidhive.info/json/movies.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
listView = (ListView) findViewById(service_list);
adapter = new CustomListAdapter(this, movieList);
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);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} 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;
}
}
}
You can send whole object movieItem and position of item click then In next activity you can extract them like this.
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
{
intent=new Intent(getBaseContext(),NextActivity.class);
intent.putParcelableArrayListExtra("key", movielist);
intent.putExtra("IntKey",p3);
}
});
You can add the individual items of the model calls as Extras to an intent, or you can make the model class implement the Serializable interface and just add the whole object to the intent manually :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Movie movie = (Movie) adapterView.getItemAtPosition(i);
Intent intent = new Intent(view.getContext(), DetailActivity.class);
intent.putExtra("mName", movie.getTitle());
intent.putExtra("mRating", movie.getRating());
intent.putExtra("mGenre", movie.getGenre());
intent.putExtra("mYear". movie.getYear());
//Get the Bitmap object from the NetworkImageView
Bitmap bm = ((BitmapDrawable)((NetworkImageView)view.findViewById(R.id.image)).getDrawable()).getBitmap();
//Can be added directly as an Extra, as Bitmap implements Parcelable
intent.putExtra("mImage", bm);
//OR make Moview implement Serializable and do this :
//intent.putExtra("clickedObject", movie);
startActivity(intent);
}
});
In the receiving activity, you can use getExtras() to get the values :
Bitmap bm = getIntent().getExtras().getParcelable("mImage");
imageView.setImageBitmap(bm);
Everything works fine, after i changed the code with the help of people who answered to this question.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Movie movie = (Movie) adapterView.getItemAtPosition(i);
Intent intent = new Intent(view.getContext(), Main3Activity.class);
intent.putExtra("mName", movie.getTitle());
intent.putExtra("mRating", movie.getRating());
intent.putExtra("mGenre", movie.getGenre());
intent.putExtra("mYear", movie.getYear());
intent.putExtra("mServiceImage",movie.getThumbnailUrl());
//OR make Moview implement Serializable and do this :
//intent.putExtra("clickedObject", movie);
startActivity(intent);
}
});
In the final activity i use Android-Universal-Image-Loader to load the image from the url i passed from first activity.
String mName = getIntent().getExtras().getString("mServiceImage");
imageLoader.displayImage(mName, imageView);

CustomListview Volley with Image doesn't works in real device

Someone, help me with this problem. i have stuck in 3 days because this problem -_-!
i can make listview with image and text using volley library, its works in emulator (i use genymotion emulator) the image and text show. but when i run it in my device (android Jelly 4.3.0) the listview is empty. the layer is blank (empty). i don't know why.
heres my piece code
public class DaftarBarang_Layout extends Activity{
private List<Produk> produkList = new ArrayList<Produk>();
private ListView listView;
private CustomListAdapter adapter;
private ProgressDialog pDialog;
private ServerRequest serverRequest;
JSONArray member = null;
private static final String url = "http://192.168.117.1:808/Koen_CI/index.php/daftar_barang_control";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.daftarbarang_layout);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, produkList);
listView.setAdapter(adapter);
btnBack = (Button)findViewById(R.id.btnBackDaftarBarang);
setBehavior();
// Creating volley request obj
JsonArrayRequest produkReq = 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);
Produk produk = new Produk();
produk.setNamaProduk(obj.getString("nama_produk"));
produk.setHargaProduk(obj.getString("harga_produk"));
produk.setFotoProduk(obj.getString("foto_produk"));
Log.d("TAG", "TAG : " + produk.getNamaProduk());
// adding movie to movies array
produkList.add(produk);
} 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(produkReq);
}
im sure the url is fine, and image return is http://192.168.117.1:808/Koen_CI/gambarbaju/batik.jpg.
the problem is, why in real device the listview is not show, but in emulator the listview is show..
sorry for my bad english, but thanks anyway.. :)
heres my CustomListAdapter:
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Produk> produkItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Produk> produkItems) {
this.activity = activity;
this.produkItems = produkItems;
}
#Override
public int getCount() {
return produkItems.size();
}
#Override
public Object getItem(int location) {
return produkItems.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, 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 rating = (TextView) convertView.findViewById(R.id.rating);
// getting movie data for the row
Produk p = produkItems.get(position);
// thumbnail image
thumbNail.setImageUrl(p.getFotoProduk(), imageLoader);
// title
title.setText(p.getNamaProduk());
// rating
rating.setText("Harga: " + p.getHargaProduk());
return convertView;
}
Add this code to your onCreate or init method.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
If this doesn't work please post logcat showing warning or error.

Categories

Resources