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.
Related
I have code to show listview from my server, but when I update the data from server and refresh it in my app, the listview still getting the old data, and after several minutes when I open the app again, it updated the new data that I updated before.
My Main Fragment
public class DosenFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
ListView list;
SwipeRefreshLayout swipe;
List<Dosen> itemList = new ArrayList<>();
AdapterDosen adapter;
private static final String TAG = DosenFragment.class.getSimpleName();
private static String url_select = Server.URL + "select.php";
public static final String TAG_ID_DOSEN = "id_dosen";
public static final String TAG_NAME = "name";
public static final String TAG_STATUS = "status";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.matkul_list, container, false);
swipe = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh_layout);
list = (ListView) v.findViewById(R.id.list);
adapter = new AdapterDosen(getActivity(), itemList);
list.setAdapter(adapter);
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
});
return v;
}
#Override
public void onRefresh() {
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
private void callVolley() {
swipe.setRefreshing(true);
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Dosen item = new Dosen();
item.setId_dosen(obj.getString(TAG_ID_DOSEN));
item.setName(obj.getString(TAG_NAME));
item.setAlamat(obj.getString(TAG_STATUS));
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
AppController.getInstance().addToRequestQueue(jArr);
}
}
I have tried to do something with itemList.clear(); and adapter.notifyDataSetChanged(); but nothing change.
My Main Adapter
public class AdapterDosen extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Dosen> items;
public AdapterDosen(Activity activity, List<Dosen> items) {
this.activity = activity;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int location) {
return items.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);
Dosen data = items.get(position);
TextView id = (TextView) convertView.findViewById(R.id.id);
TextView name = (TextView) convertView.findViewById(R.id.nama);
TextView alamat = (TextView) convertView.findViewById(R.id.alamat);
id.setText(data.getId_dosen());
name.setText(data.getName());
alamat.setText(data.getAlamat());
return convertView;
}
}
I'm sorry for my bad english.
Please help.
try this , add this method in your adatper
public void updateList(List<Dosen> newlist) {
items.clear();
items.addAll(newlist);
this.notifyDataSetChanged();
}
and in callVolley() method , replace this
adapter.notifyDataSetChanged();
with
adapter.updateList();
Hope this helps
Use the below Code...
/* Within the RecyclerView.Adapter class */
// Clean all elements of the recycler
public void clear() {
items.clear();
notifyDataSetChanged();
}
// Add a list of items -- change to type used
public void addAll(List<Dosen> newlist) {
items.addAll(newlist);
notifyDataSetChanged();
}
callvolly() method inside.
adapter.clear();
adapter.addAll(item);
public void onRefresh() {
callVolley();
}
please try this code i have changed something it will work fine
public class AdapterDosen extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Dosen> items;
public AdapterDosen(Activity activity, List<Dosen> items) {
this.activity = activity;
this.items = items;
}
public void setData(List<Dosen> items){
this.items = items
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int location) {
return items.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);
Dosen data = items.get(position);
TextView id = (TextView) convertView.findViewById(R.id.id);
TextView name = (TextView) convertView.findViewById(R.id.nama);
TextView alamat = (TextView) convertView.findViewById(R.id.alamat);
id.setText(data.getId_dosen());
name.setText(data.getName());
alamat.setText(data.getAlamat());
return convertView;
}
}
public class DosenFragment extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
ListView list;
SwipeRefreshLayout swipe;
List<Dosen> itemList = new ArrayList<>();
AdapterDosen adapter;
private static final String TAG = DosenFragment.class.getSimpleName();
private static String url_select = Server.URL + "select.php";
public static final String TAG_ID_DOSEN = "id_dosen";
public static final String TAG_NAME = "name";
public static final String TAG_STATUS = "status";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.matkul_list, container, false);
swipe = (SwipeRefreshLayout)
v.findViewById(R.id.swipe_refresh_layout);
list = (ListView) v.findViewById(R.id.list);
adapter = new AdapterDosen(getActivity(), itemList);
list.setAdapter(adapter);
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
});
return v;
}
#Override
public void onRefresh() {
//itemList.clear();
//adapter.notifyDataSetChanged();
callVolley();
}
private void callVolley() {
swipe.setRefreshing(true);
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new
Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
itemList .clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj =
response.getJSONObject(i);
Dosen item = new Dosen();
item.setId_dosen(obj.getString(TAG_ID_DOSEN));
item.setName(obj.getString(TAG_NAME));
item.setAlamat(obj.getString(TAG_STATUS));
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.setData(itemList );
adapter.notifyDataSetChanged();
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
AppController.getInstance().addToRequestQueue(jArr);
}
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();
}
}
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()
So I made an sliding tabs app that loads json into a listview. My question is how would I implement something that would only load 5 listview items in the beginning and would load another 5 when you scroll down? (Instead of loading all of the listview items in the beginning)
I have search the web and I can't really understand how to do this. Any suggestions or ideas will be appreciated.
This is some of my code. These classes is where I think the code would go: I used SlidingTabLayout & strip from the android developer site.
CustomListAdapter code:
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Tanga> tangasItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Tanga> movieItems) {
this.activity = activity;
this.tangasItems = movieItems;
}
#Override
public int getCount() {
return tangasItems.size();
}
#Override
public Object getItem(int location) {
return tangasItems.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 name = (TextView) convertView.findViewById(R.id.name);
// getting movie data for the row
Tanga m = tangasItems.get(position);
// title
name.setText(m.getName());
return convertView;
}
}
Fragment:
public class Tab1 extends Fragment {
private static final String url = "website.json";
private List<Tanga> tangaList = new ArrayList<Tanga>();
private ListView listView;
private CustomListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onActivityCreated (Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
listView = (ListView) getView().findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), tangaList);
listView.setAdapter(adapter);
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Tanga movie = new Tanga();
//name
String name = obj.getString("name");
movie.setName(name);
// adding movie to movies array
tangaList.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("Error: ");
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tabs, container, false);
return v;
}
}
Tanga Code: (model)
public class Tanga {
private String name;
public Tanga() {
}
public Tanga(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
There are multiple ways you could handle this, the simplest way would be to create another ArrayList of type Tanga, let's suppose it's name is tangaList2. What you have to do is in your for loop write this code.
public void onResponse(JSONArray response) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Tanga movie = new Tanga();
//name
String name = obj.getString("name");
movie.setName(name);
// adding movie to movies array
if(i < 5) {
tangaList.add(movie);
}
else {
tangaList2.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();
}
Now after this you should also implement the onScrollListener in your Fragment:
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if ((++firstVisibleItem) + visibleItemCount > totalItemCount) {
for(int i = 0; i < 5 && tangaList2.size() > 0; i++){
tangaList.add(tangaList2.get(0));
tangaList2.remove(0);
}
}
}
});
I am using this LIB. It's working fine but I can not loading my data in adapter class. like.
If i add some static data that will be added but whenever i tries to load from server that will not be added. finally i am trying with this approach.
But when i calls the Brandinfo and try to add data that will be error saying colon missing etc. please tell me how i can i add data to adapter to complete this recyclerview.
Thanks.
My Fragment class is
List<BrandInfo> mContentItems = new ArrayList<BrandInfo>();
pbDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pbDialog.setMessage("Loading...");
pbDialog.show();
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("BrandViewActivity", response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
brandInfo = new BrandInfo();
mContentItems.add(new BrandInfo().setBrandname(obj.getString("title")));
String title = obj.getString("title");
String location = obj.getString("location");
String image = obj.getString("image_path");
String category = obj.getString("category");
Log.d("fffffffffff", mContentItems.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error aa gai bhaya", "Error: " + error.getMessage());
hidePDialog();
}
});
This is my Brandinfo class:
public class BrandInfo {
private String brandname;
private String brandinfo;
private String address;
private String detail;
public String getBrandname() {
return brandname;
}
public void setBrandname(String brandname) {
this.brandname = brandname;
}
public String getBrandInfo() {
return brandinfo;
}
public void setBrandinfo(String brandinfo) {
this.brandname = brandinfo;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDetail() {
return detail;
}
public void setSex(String detail) {
this.detail = detail;
}
}
finally this is my adapter class:
public class TOAdapter extends RecyclerView.Adapter<TOAdapter.ViewHolder> {
private List<BrandInfo> brandLists = new ArrayList<BrandInfo>();
private ImageLoader imageLoader;
public TOAdapter(List<BrandInfo> brandLists) {
this.brandLists = brandLists;
}
// Create new views (invoked by the layout manager)
#Override
public TOAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_card_big, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
// - get data from your itemsData at this position
// - replace the contents of the view with that itemsData
BrandInfo brandList = new BrandInfo();
imageLoader = AppController.getInstance().getImageLoader();
viewHolder.txtViewTitle.setText(brandList.getBrandname());
//viewHolder.thumbNail.setImageResource(itemsData[position].getImageUrl());
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
viewHolder.thumbNail.setImageUrl(brandList.getBrandname(), imageLoader);
}
#Override
public int getItemCount() {
String s = String.valueOf(brandLists.size());
Toast.makeText(AppController.getInstance(),s,Toast.LENGTH_LONG).show();
return brandLists.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public TextView txtViewTitle;
final NetworkImageView thumbNail;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.brandtitle);
thumbNail = (NetworkImageView) itemLayoutView
.findViewById(R.id.thumbnail);
}
}
}
So what I would recommend is the following (which I use in my own project):
Create the following method in you TOAdapter:
public void refreshRecyclerViewBrands(List<BrandInfo> brandLists) {
this.brandLists = brandLists;
notifyDataSetChanged();
}
Then call the following method from where you initialized the recyclerviewadapter and your list:
mAdapter.refreshRecyclerViewBrands(mContentItems);
This basically takes the list you just got from volley and tells the recyclerview to use this new list and refresh the recyclerview. This worked for me so hopefully will work for you.
Another thing I noticed is in your onBindViewHolder your are setting the following:
BrandInfo brandList = new BrandInfo();
Then you use:
viewHolder.txtViewTitle.setText(brandList.getBrandname());
But brandlist.getBrandname is null.
Never are you actually giving the brandlist object any values, rather use the following :
final BrandInfo brandList = brandLists.get(position);
Hope this helps.
you should do like this
JSONObject obj = response.getJSONObject(i);
brandInfo = new BrandInfo();
mContentItems.add(new
BrandInfo(obj.getString("title"),
obj.getString("title");
obj.getString("location");
obj.getString("image_path");
obj.getString("category");
then i add my adapter like this
CustomSourcingAdapter adapter=new
CustomSourcingAdapter(Sourcing_modes.this, publishPlacementList);
lists.setAdapter(adapter);
this is my custom Adapter class
public class CustomSourcingAdapter extends ArrayAdapter<SourcingModel> {
private final Activity context;
private final List<SourcingModel> publishPlacementList;
public CustomSourcingAdapter(Activity context,List<SourcingModel>
publishPlacementList) {
// TODO Auto-generated constructor stub
super(context, R.layout.sorsinglist,publishPlacementList);
// TODO Auto-generated constructor stub
this.context=context;
this.publishPlacementList=publishPlacementList;
}
static class ViewHolder {
protected TextView placementtitle;
protected TextView Noofposition;
protected ImageButton next;
protected TextView Department;
}
public View getView(int position,View converview,ViewGroup parent) {
ViewHolder viewHolder = null;
if (converview ==null ){
LayoutInflater inflater=context.getLayoutInflater();
converview=inflater.inflate(R.layout.sorsinglist, null);
viewHolder = new ViewHolder();
converview.setTag(viewHolder);
converview.setTag(R.id.idplacetitle,viewHolder.placementtitle);
converview.setTag(R.id.idnoofpos,viewHolder.Noofposition);
converview.setTag(R.id.imreqserch,viewHolder.next);
converview.setTag(R.id.iddepartment,viewHolder.Department);
}else{
viewHolder= (ViewHolder)converview.getTag();
}
viewHolder.placementtitle.setText(publishPlacementList.get(position).getPositionName());
viewHolder.Noofposition.setText(publishPlacementList.get(position).getNoOfPosition());
viewHolder.Department.setText(publishPlacementList.get(position).getName());
viewHolder.next.setTag(position);
viewHolder.next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int pos = (Integer) v.getTag();
long id = publishPlacementList.get(pos).getId();
Intent it = new Intent(context, SourcingSecond.class);
it.putExtra("id", id);
context.startActivity(it);
}
});
return converview;
};