How to create Recyclerview adapter in android? - android

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

Related

Adapter for objects from JSON

I get data in JSON from API, and there are id and url. Now, i need to create a button "Add to favorites" for each image that i display. When i try to set adapter.setListener(this);, i get an error, because i can't use string format.
How can i resolve this problem? I spend 5 hours on this, and can't resolve it :(
MainActivity:
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listItem);
favorites = findViewById(R.id.buttonFav);
catDetailsArrayList = new ArrayList<>();
myAdapter = new MyAdapter(MainActivity.this ,catDetailsArrayList);
searchbtn = findViewById(R.id.buttonSearch);
searchbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
catDetailsArrayList.clear();
myAdapter.notifyDataSetChanged();
displayCats();
}
});
});
}
private void displayCats() {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String jsonCatUrl2 = jsonObject1.getString("url");
String jsonCatId2 = jsonObject1.getString("id");
CatDetails catDetails = new CatDetails();
catDetails.setUrl(jsonCatUrl2);
catDetails.setId(jsonCatId2);
catDetailsArrayList.add(catDetails);
}
listView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
} catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
});
requestQueue.add(stringRequest);
}
MyAdapter:
public class MyAdapter extends BaseAdapter {
public Activity activity;
public ArrayList<CatDetails> catDetailsArrayList;
public LayoutInflater inflater;
Button btn;
TextView idnr;
public MyAdapter(Activity activity, ArrayList<CatDetails> catDetailsArrayList) {
this.activity = activity;
this.catDetailsArrayList = catDetailsArrayList;
}
#Override
public Object getItem(int position) {
return catDetailsArrayList.get(position);
}
#Override
public long getItemId(int position) {
return (long)position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
if (inflater == null) {
inflater = this.activity.getLayoutInflater();
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item, null);
}
ImageView imageView = convertView.findViewById(R.id.ImageView);
final CatDetails catDetails = this.catDetailsArrayList.get(position);
Picasso.get().load(catDetails.getUrl()).into(imageView);
idnr =convertView.findViewById(R.id.textView);
btn = convertView.findViewById(R.id.buttonFav);
final String id = catDetails.getId();
idnr.setText(catDetails.getId());
return convertView;
}
#Override
public int getCount() {
return this.catDetailsArrayList.size();
}
I display the id that i receive from server for each item, it's ok, but i don't know how to set the button "add to favorites" to works fine. It must receive item id (that i received from server) as a param, but id is in string format.
final String id = catDetails.getId();
change it to
final String id = Integer.toString(catDetails.getId());

Json volley listview error incompatible types Adapter

I have been following some tutorials to retrieve json data and add it to a listview using volley. I have been stuck in this error trying to solve it for some time, so i had to seek out some help. I tried many examples, this one seems the most intuitive to learn, but i just cant get passed this error, thank you
i cant solve this error
this is my model class
public class Trilhos {
private int id;
private String titulo;
private int id_user;
private String dificuldade;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public int getId_user() {
return id_user;
}
public void setId_user(int id_user) {
this.id_user = id_user;
}
public String getDificuldade() {
return dificuldade;
}
public void setDificuldade(String dificuldade) {
this.dificuldade = dificuldade;
}
}
my adapter
public class AdapterTrilhos extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Trilhos> triList;
public AdapterTrilhos(List<Trilhos> triList, Activity activity) {
this.activity = activity;
this.triList = triList;
}
#Override
public int getCount() {
return this.triList.size();
}
#Override
public Object getItem(int position) {
return this.triList.get(position);
}
#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.dadoslista, null);
TextView idtxt = (TextView)
convertView.findViewById(R.id.txtid);
TextView tittxt = (TextView)
convertView.findViewById(R.id.txttit);
TextView usertxt = convertView.findViewById(R.id.txtuser);
TextView diftxt = (TextView)
convertView.findViewById(R.id.txtdif);
Trilhos t = triList.get(position);
idtxt.setText(t.getId());
tittxt.setText(t.getTitulo());
usertxt.setText(t.getId_user());
diftxt.setText(t.getDificuldade());
return convertView;
}
}
my main_activity (listarTrilhos)
public class ListarTrilhos extends Activity {
private static final String
urlget="http://192.168.1.68/loginsignup/getTrilhos.php";
private ListView listView;
private AdapterTrilhos adapter;
private List<Trilhos> TrilhosList = new ArrayList<Trilhos>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listatrilhos);
listView=findViewById(R.id.listv);
adapter=new AdapterTrilhos(this,TrilhosList);
listView.setAdapter(adapter);
criarLista();
}
public void criarLista(){
RequestQueue mRequestQueue =
Volley.newRequestQueue(getApplicationContext());
JsonArrayRequest request = new JsonArrayRequest(
urlget,
new Response.Listener<JSONArray>(){
#Override
public void onResponse(JSONArray response) {
int count = response.length();
for(int i = 0; i < count; i++){
try {
JSONObject jo = response.getJSONObject(i);
Trilhos tri=new Trilhos();
tri.setId(jo.getInt("id"));
tri.setTitulo(jo.getString("titulo"));
tri.setId_user(jo.getInt("id_user"));
tri.setDificuldade(jo.getString("dificuldade"));
TrilhosList.add(tri);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(), response.toString(),
Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "onErrorResponse",
Toast.LENGTH_LONG).show();
}
}
);
Object TAG_REQUEST_QUEUE = new Object();
request.setTag(TAG_REQUEST_QUEUE);
mRequestQueue.add(request);
mRequestQueue.start();
}
}
I didn't read all of your code but noticed that you have constructor
public AdapterTrilhos(List<Trilhos> triList, Activity activity) {
this.activity = activity;
this.triList = triList;}
change adapter=new AdapterTrilhos(this, TrilhosList); to
adapter=new AdapterTrilhos(TrilhosList, this);

How to prevent RecyclerView Items duplication onBack pressed and coming to Fragment where RecyclerView is set

I have Fragment where RecyclerView is set.After pressing Button on Fragment I go to next Fragment.After onBackPressed again I come to previous Fragment.This timee all items in Reycycler View are Doubled.
This is code for Setting Recyclerview in Fragment.
JsonArrayRequest req = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try
{
for( int i=0;i<response.length();i++)
{
JSONObject obj = response.getJSONObject(i);
final BookEntry tableEntry=new BookEntry();
String status=obj.getString("status");
if(status.equals("F"))
{
Entry.setName(obj.getString("name"));
Entry.setDescription(obj.getString("description"));
Entry.setCapacity(obj.getString("capacity"));
Entry.setId(obj.getString("id"));
current.add(tableEntry);
adapter=new BookingAdapter(current,getActivity().getApplicationContext());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
This is code for Adapter
public class TableBookingAdapter extends RecyclerView.Adapter<BookingAdapter.ViewHolder> {
private ArrayList<BookEntry> entry;
Context context;
String id;
public BookingAdapter(ArrayList<BookEntry> entry, Context context) {
this.entry = entry;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.booking_card, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final BookEntry currentEntry = entry.get(position);
holder.name.setText(currentEntry.getName());
holder.description.setText(currentEntry.getDescription());
holder.capacity.setText(currentEntry.getCapacity());
holder.tableId.setText(currentEntry.getId());
}
#Override
public int getItemCount() {
return entry.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name, description, capacity,tableId;
final CheckBox check;
public ViewHolder(final View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
description = (TextView) itemView.findViewById(R.id.description);
capacity = (TextView) itemView.findViewById(R.id.capacity);
tableId=(TextView)itemView.findViewById(R.id.tableId);
check=(CheckBox)itemView.findViewById(R.id.book);
}
}
}
How to prevent Items Duplication ?
Just clear you array list before json parsing. I am editing your code. Just add one line.
if(current!=null && current.size()>0){
current.clear();
}
JsonArrayRequest req = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try
{
for( int i=0;i<response.length();i++)
{
JSONObject obj = response.getJSONObject(i);
final BookEntry tableEntry=new BookEntry();
String status=obj.getString("status");
if(status.equals("F"))
{
Entry.setName(obj.getString("name"));
Entry.setDescription(obj.getString("description"));
Entry.setCapacity(obj.getString("capacity"));
Entry.setId(obj.getString("id"));
current.add(tableEntry);
adapter=new BookingAdapter(current,getActivity().getApplicationContext());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}

getCount() is being called before BaseAdapter constructor method finishes executing

I am new to android. I am trying to create a GridView
consisting of ImageView. The images are from flickr and I am using flickr API to search flickr and receive JSON response. I parse the JSON data to get image URL. The API call and parsing JSON data is done inside FlickrAdapter which extends BaseAdapter. But the problem is my getView() method is never called. I searched stackoverflow for this and I found that if there is no data to show then getView() will not be called. But I am setting the data in FlickrAdapter constructor. I've set some debug texts in the methods and I see that getCount() is called before the data is set which means getCount() is called before the FlickrAdapter constructor finishes executing. So getView() is never called.
I want getCount() method to be called after the constructor method of my FlickrAdapter finishes executing.
How can I solve this problem?
Here is my code for the BaseAdapter and other classes
FlickrAdapter.java
public class FlickrAdapter extends BaseAdapter {
public ArrayList<FlickrImage> flickrImagesList;
private Context context;
public static FlickrAdapter instance;
FlickrAdapter(final Context context, String searchText, Activity activity) {
this.flickrImagesList = new ArrayList<FlickrImage>();
this.context = context;
instance = this;
Flickr flickr = new Flickr(searchText, context, activity);
//row[0] = inflater.inflate(R.layout.template, null, false);
Log.d("URL", flickr.buildApiUrl());
DownloadManager.getJsonResponse(flickr.buildApiUrl(), context, new VolleyCallBack<JSONObject>() {
#Override
public void onSuccess(JSONObject success) {
//Log.d("JSON",success.toString());
try {
success = success.getJSONObject("photos");
JSONArray photo = success.getJSONArray("photo");
for (int i = 0; i < photo.length(); i++) {
JSONObject tempObject = photo.getJSONObject(i);
String result = new StringBuilder("https://farm" + tempObject.get("farm").toString() +
".staticflickr.com/" +
tempObject.get("server").toString() +
"/" +
tempObject.get("id").toString() +
"_" +
tempObject.get("secret").toString() +
"_n.jpg").toString();
FlickrImage image = new FlickrImage(i, result);
instance.flickrImagesList.add(image);
Log.d("SIZE", String.valueOf(instance.flickrImagesList.size()));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public int getCount() {
Log.d("COUNT",String.valueOf(flickrImagesList.size()));
return flickrImagesList.size();
}
#Override
public Object getItem(int position) {
return flickrImagesList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
class ViewHolder {
ImageView myImage;
ViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.individulaImage);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.individual_image, parent, false);
holder = new ViewHolder(row);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
FlickrImage tempImage = flickrImagesList.get(position);
Log.d("Address", tempImage.imageName);
//ImageView iv = (ImageView) convertView.findViewById(R.id.individulaImage);
//Picasso.with(context).load(tempImage.imageName).into(iv);
return row;
}}
Flickr.java
public class Flickr {
private StringBuilder urlBuilder = new StringBuilder("https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=e78808f6cf756218d6981fcdf8021f0c&tags=");
private String apiUrl = "";
private Context context = null;
private Activity activity;
private String[] individualImageUrl;
private String keyWord = "";
public Flickr(String keyWord, Context context, Activity activity) {
this.keyWord=keyWord;
this.apiUrl = buildApiUrl();
this.context = context;
this.activity = activity;
//Log.d("APIURL", this.apiUrl);
}
public String buildApiUrl() {
String[] temp;
StringBuilder sb = new StringBuilder();
temp = this.keyWord.split(" ");
for (int i = 0; i < temp.length; i++) {
sb.append(temp[i]);
if (i != (temp.length - 1)) {
sb.append("+");
}
}
urlBuilder.append(sb);
urlBuilder.append("&text=");
urlBuilder.append(sb);
urlBuilder.append("&format=json&nojsoncallback=1");
return urlBuilder.toString();
}}
FlickrImage.java
public class FlickrImage {
public int imageId;
public String imageName;
FlickrImage(int imageId, String imageURL) {
this.imageId = imageId;
this.imageName = imageURL;
}
}
VolleyCallBack.java
public interface VolleyCallBack<T> {
public void onSuccess(T success);
}
DownloadManager.java
public class DownloadManager {
public static void getJsonResponse(final String Url, Context context, final VolleyCallBack callBack) {
JsonObjectRequest flickrJsonRequest = new JsonObjectRequest(Request.Method.GET, Url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
callBack.onSuccess(response);
}
},
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Volley.newRequestQueue(context).add(flickrJsonRequest);
}
}
It is not being called before your constructor completes. YOur web code runs in a seperate thread so your constructor code completes and then getCount is called. Once your web code is complete onSuccess is called.
It is never advisable to run network code in adapter. Run it in your activity or fragment and once it completes call notifyDatasetChanged() on your adapter.

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.

Categories

Resources