list doubles when back pressed in fragment - android

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()

Related

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

ListView repeating same JSON items on every Button click

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

How to implement onStop() method on a ListView?

I have a ListView on my android app. When click a ListView item and go to a new activity and when i press back button i land on a empty ListView. I dont get any data. Even if i restart the app i dont get any data on the ListView. It works only the first time i run the app. Do i have to override the onStop method and reset my ListView adapter? how do i fix this?
ListView activity
public class ViewGuidesActivity extends AppCompatActivity {
private static final String TAG = ViewGuidesActivity.class.getSimpleName();
private ProgressDialog pDialog;
private List<Guide> guideList = new ArrayList<Guide>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_guides);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, guideList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(AppConfig.URL_GET_GUIDE_LIST,
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);
Guide guide = new Guide();
guide.setNgno(obj.getString("ngno"));
guide.setEmail(obj.getString("email"));
guide.setName(obj.getString("name"));
// adding movie to movies array
guideList.add(guide);
} 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) {
Log.d(TAG, error.toString());
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Guide newGuide = guideList.get(position);
String email = newGuide.getEmail();
String ngno = newGuide.getNgno();
Intent i = new Intent(getApplicationContext(), GuideDetails.class);
i.putExtra("email", email);
i.putExtra("ngno", ngno);
startActivity(i);
}
});
}
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.menu_main, menu);
menu.getItem(1).setVisible(false);
menu.getItem(2).setVisible(false);
return true;
}
}
ListAdapter
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Guide> guideItems;
public CustomListAdapter(Activity activity, List<Guide> guideItems) {
this.activity = activity;
this.guideItems = guideItems;
}
#Override
public int getCount() {
return guideItems.size();
}
#Override
public Object getItem(int location) {
return guideItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.customrow, parent, false);
TextView ngno = (TextView) convertView.findViewById(R.id.txt_ListNgno);
TextView name = (TextView) convertView.findViewById(R.id.txt_ListName);
TextView email = (TextView) convertView.findViewById(R.id.txt_ListEmail);
// getting guide data for the row
Guide g = guideItems.get(position);
//thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
ngno.setText(g.getNgno());
name.setText(g.getName());
email.setText(g.getEmail());
return convertView;
}
}
how do i fix this issue?

Unable to view the content in listview

I am using a list view in fragment which loads data using json in that i cannot able to view the list view.In the sched it shows the constructor is never used i don't know where i have done wrong in the code.The server part works fine.
Fragment:
public class SchedulessFragment extends Fragment{
private static final String TAG = MatAct.class.getSimpleName();
private static final String url = "http://nammakovai2015-001-site1.1tempurl.com/iplspin/schedules.php";
ProgressDialog pDialog;
List<Sched> movieList = new ArrayList<Sched>();
ListView listview;
CustomListAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.schedule_frag, container, false);
adapter = new CustomListAdapter(getActivity(), movieList);
listview = (ListView) v.findViewById(R.id.listView1);
listview.setAdapter(adapter);
// TextView tv = (TextView) v.findViewById(R.id.tvfrag);
// tv.setText(getArguments().getString("msg"));
// tv.setText("Hello");
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
// 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);
Sched m = new Sched();
m.setTeama(obj.getString("teama"));
m.setTeamb(obj.getString("teamb"));
m.setTdate(obj.getString("tdate"));
m.setTtime(obj.getString("ttime"));
m.setThumbnailUrl(obj.getString("thumbnailUrl"));
m.setTeambthumbnailUrl(obj.getString("teambthumbnailUrl"));
m.setVenue(obj.getString("venue"));
// adding movie to movies array
movieList.add(m);
} 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);
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public static SchedulessFragment newInstance(String text) {
SchedulessFragment f = new SchedulessFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}}
ListAdapter:
public class CustomListAdapter extends BaseAdapter{
private Activity activity;
private LayoutInflater inflater;
List<Sched> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Sched> 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.listitem_ros, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.pict);
NetworkImageView teambthumbnail=(NetworkImageView) convertView.findViewById(R.id.pict1);
TextView teama = (TextView) convertView.findViewById(R.id.scheduleteama_name);
TextView teamb = (TextView) convertView.findViewById(R.id.schduleteamb_name);
TextView tdate = (TextView) convertView.findViewById(R.id.datess);
TextView ttime = (TextView) convertView.findViewById(R.id.timess);
TextView venue=(TextView)convertView.findViewById(R.id.schedulevenue);
// getting movie data for the row
Sched m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
teambthumbnail.setImageUrl(m.getTeambthumbnailUrl(),imageLoader);
// title
teama.setText(m.getTeama());
teamb.setText(m.getTeamb());
tdate.setText(m.getTdate());
ttime.setText(m.getTtime());
venue.setText(m.getVenue());
return convertView;
}}
Sched:
public class Sched {
private String teama,teamb,tdate,ttime,thumbnailUrl,teambthumbnailUrl,venue;
public Sched(){}
public Sched(String teama, String teamb, String tdate, String ttime, String thumbnailUrl, String teambthumbnailurl, String venue)
{
this.teama=teama;
this.teamb=teamb;
this.tdate=tdate;
this.ttime=ttime;
this.thumbnailUrl=thumbnailUrl;
this.teambthumbnailUrl=teambthumbnailurl;
this.venue=venue;
}
public String getTeama(){
return teama;
}
public void setTeama(String teama){
this.teama=teama;
}
public String getTeamb(){
return teamb;
}
public void setTeamb(String teamb){
this.teamb=teamb;
}
public String getTdate(){
return tdate;
}
public void setTdate(String tdate){
this.tdate=tdate;
}
public String getTtime(){
return ttime;
}
public void setTtime(String ttime){
this.ttime=ttime;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public String getTeambthumbnailUrl() {
return teambthumbnailUrl;
}
public void setTeambthumbnailUrl(String teambthumbnailUrl){
this.teambthumbnailUrl=teambthumbnailUrl;
}
public String getVenue(){
return venue;
}
public void setVenue(String venue){
this.venue=venue;
}}
xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp"
>
</ListView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/tvfrag"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="219dp" />
Your problem is that you are creating the adapter before the movieList has been populated. Move these two lines:
adapter = new CustomListAdapter(getActivity(), movieList);
listview.setAdapter(adapter);
after the for loop in which you're adding the Movies to the list:
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Sched m = new Sched();
m.setTeama(obj.getString("teama"));
m.setTeamb(obj.getString("teamb"));
m.setTdate(obj.getString("tdate"));
m.setTtime(obj.getString("ttime"));
m.setThumbnailUrl(obj.getString("thumbnailUrl"));
m.setTeambthumbnailUrl(obj.getString("teambthumbnailUrl"));
m.setVenue(obj.getString("venue"));
// adding movie to movies array
movieList.add(m);
} catch (JSONException e) {
e.printStackTrace();
}
//PUT THOSE TWO LINES HERE
Assuming your Request is good and it returns a non-empty JSONArray, this should work.

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