I am creating an list view inside fragment but it is not displaying i have stuck.I am passing data from mainActivity.java to OrderDetailsAdapter.java but getview() function is not getting called and getcount returning nonzero
Here is my code
OrderDetailsAdapter.java
public class OrderDetailsAdapter extends ArrayAdapter<OrderDetails> {
Context context;
int resource;
private List<OrderDetails> orderList = new ArrayList<OrderDetails>();
public OrderDetailsAdapter(Context context, int resource) {
super(context, resource);
this.context = context;
this.resource = resource;
}
#Override
public void add(OrderDetails object) {
orderList.add(object);
Log.v("getcount", "addItems " + getCount());
super.add(object);
}
#Override
public int getCount() {
int size = orderList.size();
Log.v("getcount","getcount "+ size);
return orderList.size();
}
#Override
public OrderDetails getItem(int index) {
return orderList.get(index);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Log.v("getcount","I am getting called");
View row = convertView;
OrderDetailsHolder holder = null;
if(row == null)
{
LayoutInflater layoutInflater = LayoutInflater.from(context);
row = layoutInflater.inflate(resource,parent,false);
holder = new OrderDetailsHolder();
holder.patientName = (TextView)row.findViewById(R.id.order_list_view_patient_name);
holder.price = (TextView)row.findViewById(R.id.order_list_view_price);
holder.medicineList = (TextView)row.findViewById(R.id.order_list_view_medicine_list);
holder.expirationTime = (TextView)row.findViewById(R.id.order_list_view_expiration_time);
holder.expirationText = (TextView)row.findViewById(R.id.order_list_view_order_expire_text);
holder.cancelOrder = (TextView)row.findViewById(R.id.order_list_view_cancel_order);
holder.openOrder = (TextView)row.findViewById(R.id.order_list_view_open_order);
//Assigning custom fonts
Typeface typeface = Typeface.createFromAsset(context.getAssets(),"fonts/gothic.ttf");
holder.patientName.setTypeface(typeface);
holder.price.setTypeface(typeface);
holder.expirationTime.setTypeface(typeface);
holder.medicineList.setTypeface(typeface);
holder.expirationText.setTypeface(typeface);
holder.cancelOrder.setTypeface(typeface);
holder.openOrder.setTypeface(typeface);
row.setTag(holder);
}
else {
holder = (OrderDetailsHolder)row.getTag();
}
final OrderDetails details = getItem(position);
Log.v("AAAA",details.toString());
// OrderDetails orderDetails1 = orderList[position];
holder.patientName.setText(details.getPatientName());
holder.price.setText(String.valueOf(details.getPrice()) +" /-");
holder.medicineList.setText(Arrays.toString(details.getMedicineList()));
holder.expirationTime.setText(String.valueOf(details.expirationTime)+" mins");
return row;
}
static class OrderDetailsHolder {
TextView patientName;
TextView price;
TextView medicineList;
TextView expirationTime;
TextView expirationText;
TextView openOrder;
TextView cancelOrder;
}}
OrderDetails.java
public class OrderDetails {
public String patientName;
public float price;
public String medicineList[];
public int expirationTime;
public OrderDetails()
{
super();
}
public OrderDetails(String patientName,float price,String[] medicineList,int expirationTime)
{
this.patientName = patientName;
this.price = price;
this.medicineList = medicineList;
this.expirationTime = expirationTime;
}
public String getPatientName(){
return patientName;
}
public float getPrice() { return price; }
public String[] getMedicineList() { return medicineList; }
public int getExpirationTime() { return expirationTime; }}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.mipmap.ic_icon_home);
TextView userAddress = (TextView) findViewById(R.id.navigationDrawerHeaderTextView2);
userAddress.setText("52N 12, Pratap Nagar");
replaceFragment(R.layout.fragment_order_list, null);
//Set adapter for Order List
String medicineList[] = {"Paracetamol","Crocin","Azithomycin","Strepsils"};
orderDetails = new OrderDetails("Ravi Gupta",220,medicineList,20);
OrderDetailsAdapter orderDetailsAdapter = new OrderDetailsAdapter(this,R.layout.order_list_view_items);
orderDetailsAdapter.add(orderDetails);
orderDetailsAdapter.add(orderDetails);
orderDetailsAdapter.add(orderDetails);
orderDetailsAdapter.add(orderDetails); }
HELP PLZ
do this public OrderDetailsAdapter(Context context, int resource,List<OrderDetails> orderList) {
super(context, resource);
this.context = context;
this.resource = resource;
this.orderList = orderList;
} and this OrderDetailsAdapter orderDetailsAdapter = new OrderDetailsAdapter(this,R.layout.order_list_view_items,orderList);
Related
I have a code, witch shows all the pictures from a sql database in a gridview and now i try to introduce a OnItemClick method to show this pictures in a new Activity over the full screen. I am coding in Java. Pls help me. Thanks
This is the code from thr list activity (the sqldatabase is called aood)
(there are some other things in this activity so do not wonder)
public class AoodList extends AppCompatActivity {
GridView gridView;
ArrayList<Aood> list;
AoodAdapter adapter = null;
GridView grid;
public static Bitmap bmp = null;
private String[] FilePathStrings;
ImageView imageview;
private File[] listFile;
File file;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aood_list_activity);
gridView = (GridView) findViewById(R.id.gridview1);
list = new ArrayList<>();
adapter = new AoodAdapter(this, R.layout.aood_items, list);
gridView.setAdapter(adapter);
Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT * FROM AOOD");
list.clear();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String price = cursor.getString(2);
String date = cursor.getString(4);
byte[] image = cursor.getBlob(3);
list.add(new Aood(id, name, price, image, date));
}
adapter.notifyDataSetChanged();
public class Aood {
private int id;
private String name;
private String price;
private String date;
private byte[] image;
public Aood(int id, String name, String price, byte[] image, String date) {
this.id = id;
this.name = name;
this.price = price;
this.date = date;
this.image = image;
}
public int getId() { return id; }
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getDate() {return date;}
public void setDate(String date) {this.date = date;}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
}
public class AoodAdapter extends BaseAdapter {
private Context context;
private int layout;
private ArrayList<Aood> aoodList;
public AoodAdapter(Context context, int layout, ArrayList<Aood> aoodList) {
this.context = context;
this.layout = layout;
this.aoodList = aoodList;
}
#Override
public int getCount() {
return aoodList.size();
}
#Override
public Object getItem(int position) {
return aoodList.get (position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder{
ImageView imageView;
TextView txtName, txtPrice, txtDate;
}
#Override
public View getView(int position, View view, ViewGroup ViewGroup) {
View row = view;
ViewHolder holder = new ViewHolder();
if(row == null){
LayoutInflater inflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout, null);
holder.txtName = (TextView) row.findViewById(R.id.txtName);
holder.txtPrice = (TextView) row.findViewById(R.id.txtPrice);
holder.txtDate = (TextView) row.findViewById(R.id.txtDate);
holder.imageView = (ImageView) row.findViewById(R.id.imgAood);
row.setTag(holder);
}
else {
holder = (ViewHolder) row.getTag();
}
Aood aood = aoodList.get(position);
holder.txtName.setText(aood.getName());
holder.txtPrice.setText(aood.getPrice());
holder.txtDate.setText(aood.getDate());
byte[] aoodImage = aood.getImage();
Bitmap bitmap = BitmapFactory.decodeByteArray(aoodImage, 0, aoodImage.length);
holder.imageView.setImageBitmap(bitmap);
return row;
}
}
You need to create an interface that'll handle your onClick event:
public interface IClickListener {
<T> void onClick(T model);
}
Then change your adapter to the following, receive IClickListener in the constructor and setOnClickLister on your imageView and trigger onClick event:
public class AoodAdapter extends BaseAdapter {
private Context context;
private int layout;
private ArrayList<Aood> aoodList;
private IClickListener clickListener //register clickListener to trigger onClick event
public AoodAdapter(Context context, int layout, ArrayList<Aood> aoodList, IClickListener clickListener) {
this.context = context;
this.layout = layout;
this.aoodList = aoodList;
this.clickListener = clickListener;
}
#Override
public int getCount() {
return aoodList.size();
}
#Override
public Object getItem(int position) {
return aoodList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
ImageView imageView;
TextView txtName, txtPrice, txtDate;
}
#Override
public View getView(int position, View view, ViewGroup ViewGroup) {
View row = view;
ViewHolder holder = new ViewHolder();
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout, null);
holder.txtName = (TextView) row.findViewById(R.id.txtName);
holder.txtPrice = (TextView) row.findViewById(R.id.txtPrice);
holder.txtDate = (TextView) row.findViewById(R.id.txtDate);
holder.imageView = (ImageView) row.findViewById(R.id.imgAood);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
Aood aood = aoodList.get(position);
holder.txtName.setText(aood.getName());
holder.txtPrice.setText(aood.getPrice());
holder.txtDate.setText(aood.getDate());
//setOnClickListener on imageView to trigger your interface and pass clicked object
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickListener.onClick(aood);
}
});
byte[] aoodImage = aood.getImage();
Bitmap bitmap = BitmapFactory.decodeByteArray(aoodImage, 0, aoodImage.length);
holder.imageView.setImageBitmap(bitmap);
return row;
}
}
Then implement your interface in your Activity and override onClick as shown below:
public class AoodList extends AppCompatActivity implements IClickListener {
GridView gridView;
ArrayList<Aood> list;
AoodAdapter adapter = null;
GridView grid;
public static Bitmap bmp = null;
private String[] FilePathStrings;
ImageView imageview;
private File[] listFile;
File file;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aood_list_activity);
gridView = (GridView) findViewById(R.id.gridview1);
list = new ArrayList<>();
adapter = new AoodAdapter(this, R.layout.aood_items, list, this); //pass IClickListener
gridView.setAdapter(adapter);
Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT * FROM AOOD");
list.clear();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String price = cursor.getString(2);
String date = cursor.getString(4);
byte[] image = cursor.getBlob(3);
list.add(new Aood(id, name, price, image, date));
}
adapter.notifyDataSetChanged();
}
#Override
public <T> void onClick(T data) {
//then cast data onto your obj
Aood aood = (Aood) data;
}
}
I developed a vocabulary app that has a Recycler View in main activity and shows two column of database: unit number and Unit name.When I click on each item it goes to another activity called inner page that has 6 text views and it must show other items of that row like word definition unit number spell meaning and part of speech. But unfortunately text views are empty and it shows only one value which is unit number.Please take a look at my codes and tell me what I missed.
Here's my codes:
Main page:
public class TabWord extends Fragment {
private RecyclerView recyclerView;
private ArrayList<WordItem> items = new ArrayList<>();
private WordTab adapter;
private DatabaseHelper databaseHelper;
private Cursor cursor ;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.tab_word, container, false);
recyclerView = viewGroup.findViewById(R.id.recyclerview_word);
adapter = new WordTab(items, getContext());
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
loadDatabase();
return viewGroup;
}
public void loadDatabase() {
databaseHelper = new DatabaseHelper(getActivity());
try {
databaseHelper.checkAndCopyDatabase();
databaseHelper.openDatabase();
} catch (SQLException e) {
e.printStackTrace();
}
try {
cursor = databaseHelper.QueryData("select * from ielts");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
WordItem item = new WordItem();
item.setUnitName(cursor.getString(2));
item.setUnitNumber(cursor.getString(1));
items.add(item);
} while (cursor.moveToNext());
}
}
} catch (SQLException e) {
e.printStackTrace();
}
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
adapter = new WordTab(items, getActivity());
adapter.setOnTapListener(new OnTapListener() {
#Override
public void OnTapView(int position) {
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
}
}
Adapter:
public class WordTab extends RecyclerView.Adapter<WordTab.ViewHolder> {
public static List<WordItem> wordItems;
private Context context;
private OnTapListener onTapListener;
public WordTab(List<WordItem> wordItems, Context context) {
this.wordItems = wordItems;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.sample_word, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
WordItem wordItem = wordItems.get(position);
holder.unitNumber.setText(wordItem.getUnitNumber());
holder.unitName.setText(wordItem.getUnitName());
holder.cardView.setId(position);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onTapListener != null) {
onTapListener.OnTapView(position);
int position = v.getId();
Intent intent = new Intent(context, InnerPage.class);
intent.putExtra("name", "words");
intent.putExtra("id", position + "");
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return wordItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView unitName, unitNumber;
CardView cardView;
public ViewHolder(View itemView) {
super(itemView);
unitName = itemView.findViewById(R.id.unit_name);
unitNumber = itemView.findViewById(R.id.unit_number);
cardView= itemView.findViewById(R.id.card_view_word);
}
}
public void setOnTapListener(OnTapListener onTapListener) {
this.onTapListener = onTapListener;
}
}
Model:
public class WordItem {
private int id;
private String unitNumber;
private String unitName;
private String word;
private String phonetic,pos,persian,definition;
public WordItem() {
this.unitName = unitName;
this.unitNumber = unitNumber;
this.word = word;
this.phonetic = phonetic;
this.pos = pos;
this.persian = persian;
this.definition = definition;
this.id = id;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getPhonetic() {
return phonetic;
}
public void setPhonetic(String phonetic) {
this.phonetic = phonetic;
}
public String getPos() {
return pos;
}
public void setPos(String pos) {
this.pos = pos;
}
public String getPersian() {
return persian;
}
public void setPersian(String persian) {
this.persian = persian;
}
public String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUnitNumber() {
return unitNumber;
}
public void setUnitNumber(String unitNumber) {
this.unitNumber = unitNumber;
}
public String getUnitName() {
return unitName;
}
public void setUnitName(String unitName) {
this.unitName = unitName;
}
}
Inner Page:
public class InnerPage extends AppCompatActivity {
private int id;
private String unitNumber,word,phonetic,pos,persian,definition;
private TextView unitTxt,wordTxt,phoneticTxt,posTxt,persianTxt,definitionTxt;
private int layoutId;
private String pageName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inner_page);
Bundle extras = getIntent().getExtras();
if (extras != null) {
layoutId = Integer.parseInt(extras.getString("id"));
pageName = extras.getString("name");
if (pageName.equals("words")){
id = WordTab.wordItems.get(layoutId).getId();
unitNumber = WordTab.wordItems.get(layoutId).getUnitNumber();
word = WordTab.wordItems.get(layoutId).getWord();
phonetic = WordTab.wordItems.get(layoutId).getPhonetic();
pos = WordTab.wordItems.get(layoutId).getPos();
persian = WordTab.wordItems.get(layoutId).getPersian();
definition = WordTab.wordItems.get(layoutId).getDefinition();
}
}
unitTxt = findViewById(R.id.unit);
wordTxt = findViewById(R.id.word);
phoneticTxt = findViewById(R.id.phonetic);
posTxt = findViewById(R.id.txtSpell);
persianTxt = findViewById(R.id.farMean);
definitionTxt = findViewById(R.id.definition);
unitTxt.setText(unitNumber);
wordTxt.setText(word);
phoneticTxt.setText(phonetic);
posTxt.setText(pos);
persianTxt.setText(persian);
definitionTxt.setText(definition);
}
}
When I just display string data it seems to show up fine, but when I try to display an int or double the RecyclerView won't populate. I am pulling from the Google places API JSON. I think maybe it is the way I'm using my onBindViewHolder()? Thanks
// MainActivity
private void getJson() {
String URL = https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.7085,-74.003124&opennow&radius=5000&type=restaurant&key=
JsonObjectRequest root = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray results = response.getJSONArray("results");
Log.d("RESULTS", String.valueOf(results));
for(int i = 0; i<results.length(); i++) {
JSONObject resultsObj = results.getJSONObject(i);
mImageUrls.add(resultsObj.getString("icon"));
mTitle.add(resultsObj.getString("name"));
//mRating.add(resultsObj.getDouble("rating"));
mPriceLevel.add(resultsObj.getInt("price_level"));
}
getRecyclerView();
} catch (JSONException e) {
e.printStackTrace();
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(root);
}
private void getRecyclerView() {
// LinearLayoutManager
recyclerView = findViewById(R.id.recyclerView);
adapter = new RecyclerViewAdapter(mImageUrls, mTitle, mPriceLevel, this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
}
And the RecyclerViewAdapter Class is.
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private static final String TAG = "RecyclerViewAdapter";
private ArrayList<String> rNames = new ArrayList<>();
private ArrayList<String> rImageUrls = new ArrayList<>();
private ArrayList<Double> rRatings = new ArrayList<>();
private ArrayList<Integer> rPriceLevel = new ArrayList<>();
private Context mContext;
public RecyclerViewAdapter(ArrayList<String> image, ArrayList<String> name, ArrayList<Integer> priceLevel, Context context) {//, ArrayList<Double> rating
this.rImageUrls = image;
this.rNames = name;
//this.rRatings = rating;
this.rPriceLevel = priceLevel;
mContext = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
//return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Glide.with(mContext).asBitmap().load(rImageUrls.get(position)).into(holder.image);
holder.name.setText(rNames.get(position));
//holder.rating.setText(rRatings.get(position));
holder.priceLevel.setText(rPriceLevel.get(position));
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked on an image: " + rNames.get(position));
Toast.makeText(mContext, rNames.get(position), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return rNames.size(); //we can use rImageUrls/rRatings as well because they are all the same size
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView image;
TextView name;
TextView rating;
TextView priceLevel;
TextView address;
RelativeLayout parentLayout;
public ViewHolder(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.image);
name = (TextView) itemView.findViewById(R.id.title);
//rating = itemView.findViewById(R.id.rating);
priceLevel = (TextView) itemView.findViewById(R.id.priceLevel);
parentLayout = itemView.findViewById(R.id.parentLayout);
}
}
}
The reason for this is you are not converting Double to String
change this line holder.rating.setText(rRatings.get(position)); to holder.rating.setText(String.valueOf(rRatings.get(position)));
I would like to suggest you to create an object having all necessary parameters in it and then pass a single list of that object to the RecyclerViewAdapter.
public class MapElement {
public String name;
public String imageUrl;
public Double rating;
public Integer price;
}
Then create an ArrayList of this object when you get the response from your getJson function call. Now in your adapter just use a single list of MapElement object to show the data from there.
The modified adapter should look like this.
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private static final String TAG = "RecyclerViewAdapter";
private ArrayList<MapElement> elements = new ArrayList<>();
private Context mContext;
public RecyclerViewAdapter(ArrayList<MapElement> elements, Context context) {
this.elements = elements;
mContext = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Glide.with(mContext).asBitmap().load(rImageUrls.get(position)).into(holder.image);
holder.name.setText(elements.get(position).name);
holder.rating.setText(elements.get(position).rating);
holder.priceLevel.setText(elements.get(position).price);
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked on an image: " + rNames.get(position));
Toast.makeText(mContext, elements.get(position).name, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return elements.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView image;
TextView name;
TextView rating;
TextView priceLevel;
TextView address;
RelativeLayout parentLayout;
public ViewHolder(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.image);
name = (TextView) itemView.findViewById(R.id.title);
rating = itemView.findViewById(R.id.rating);
priceLevel = (TextView) itemView.findViewById(R.id.priceLevel);
parentLayout = itemView.findViewById(R.id.parentLayout);
}
}
}
First you should check that the rating you are getting is a double value.
It might be the case that an exception is thrown after this line
mRating.add(resultsObj.getDouble("rating"))
Also as #hooray_todd siggested textview only takes string value so you have to change your data into string.
Am looking to create a fragment conaining listview by retriveing data from firebase database.This listview gets cards having buttons and seekbar. All I want is to have a global variable listen to these buttons. I tried creating onClicklistener in the fragment itself but wasn't successful.Then I created onClicklistener for these buttons on the Adapter itself which was working. Now when I use the buttonclick to create a Toast, the Toast string is coming up as I expect. But the problem is that I want this Toasted string to store somewhere like global variable so that I could use it in another fragment as well. So I used:
String alpha = ((MyApplication) getContext()).getCartitem();
((MyApplication)getContext()).setCartitem("XYZ");
inside my adapter class's on Click Listener itself but the application crashes showing error log "First cannot be cast to com.fastfrooot.fastfrooot.MyApplication". First being my Activity containing Fragment and MyApplication is the class extending application.
MyApplication.java
package com.fastfrooot.fastfrooot;
import android.app.Application;
import android.widget.Button;
public class MyApplication extends Application {
private boolean[] cartsitem = {
false,
false,
false,
false,
false,
false
};
private String orderitem;
private String pkname;
private boolean oncomp = false;
private Button[] cartbuttons = new Button[20];
private String cartitem = "Alpha";
public boolean[] getcartsitem() {
return cartsitem;
}
public void setcartsitem(boolean[] cartsitem) {
this.cartsitem = cartsitem;
}
public String getorderitem() {
return orderitem;
}
public void setorderitem(String orderitem) {
this.orderitem = orderitem;
}
public String getpkname() {
return pkname;
}
public void setpkname(String pkname) {
this.pkname = pkname;
}
public boolean getoncomp() {
return oncomp;
}
public void setoncomp(boolean oncomp) {
this.oncomp = oncomp;
}
public Button[] getcartbuttons() {
return cartbuttons;
}
public void setCartbuttons(Button[] cartbuttons) {
this.cartbuttons = cartbuttons;
}
public String getCartitem() {
return cartitem;
}
public void setCartitem(String cartitem) {
this.cartitem = cartitem;
}
}
public class CustomListAdapterfir extends ArrayAdapter < Cardfir > {
private static final String TAG = "CustomListAdapter";
private Context mContext;
private int mResource;
private int lastPosition = -1;
private int procount;
String Cartkeitem;
private static class ViewHolder {
TextView title;
ImageView image;
TextView Status;
Button cartbutton;
SeekBar seekbar;
}
public CustomListAdapterfir(Context context, int resource, List < Cardfir > objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
//sets up the image loader library
setupImageLoader();
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//get the persons information
final String title = getItem(position).getTitle();
String imgUrl = getItem(position).getImgURL();
final String Status = getItem(position).getStatus();
Button cartbutton = getItem(position).getCartbutton();
final SeekBar seekBar = getItem(position).getSeekbar();
try {
//create the view result for showing the animation
final View result;
//ViewHolder object
final ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.cardTitle);
holder.Status = (TextView) convertView.findViewById(R.id.cardstat);
holder.image = (ImageView) convertView.findViewById(R.id.cardImage);
holder.seekbar = (SeekBar) convertView.findViewById(R.id.seekBarf);
holder.cartbutton = (Button) convertView.findViewById(R.id.Addbutton);
result = convertView;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
result = convertView;
}
lastPosition = position;
holder.title.setText(title);
holder.Status.setText(Status);
holder.cartbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int seekerpos = holder.seekbar.getProgress() + 1;
Cartkeitem = title + " " + String.valueOf(seekerpos);
Toast.makeText(mContext, Cartkeitem, Toast.LENGTH_SHORT).show();
String alpha = ((MyApplication) getContext()).getCartitem();
((MyApplication) getContext()).setCartitem("XYZ");
}
});
holder.seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
//create the imageloader object
ImageLoader imageLoader = ImageLoader.getInstance();
int defaultImage = mContext.getResources().getIdentifier("#drawable/logo", null, mContext.getPackageName());
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(defaultImage)
.showImageOnFail(defaultImage)
.showImageOnLoading(defaultImage).build();
imageLoader.displayImage(imgUrl, holder.image, options);
return convertView;
} catch (IllegalArgumentException e) {
Log.e(TAG, "getView: IllegalArgumentException: " + e.getMessage());
return convertView;
}
}
private void setupImageLoader() {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
mContext)
.defaultDisplayImageOptions(defaultOptions)
.memoryCache(new WeakMemoryCache())
.discCacheSize(100 * 1024 * 1024).build();
ImageLoader.getInstance().init(config);
}
}
public class Tab1fragment extends Fragment implements View.OnClickListener {
private static final String TAG = "TAG1 fragment";
private ListView mListView;
DatabaseReference Complete = FirebaseDatabase.getInstance().getReference();
DatabaseReference Products = Complete.child("Products");
ValueEventListener productlistener;
final ArrayList < Cardfir > list = new ArrayList < Cardfir > ();
String productname;
String producttype;
final ArrayList < Button > Cartbuttons = new ArrayList < Button > ();
final ArrayList < SeekBar > Seekbars = new ArrayList < SeekBar > ();
int productnumber = -1;
Button[] Cartsbut = new Button[20];
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1_fragment, container, false);
mListView = (ListView) view.findViewById(R.id.listview);
productlistener = Products.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (final DataSnapshot delphi: dataSnapshot.getChildren()) {
productnumber = productnumber + 1;
productname = delphi.child("Name").getValue().toString();
producttype = delphi.child("Type").getValue().toString();
list.add(new Cardfir("drawable://" + R.drawable.trans, productname, producttype));
}
CustomListAdapterfir adapter = new CustomListAdapterfir(getActivity(), R.layout.card_layout_liveorder, list);
mListView.setAdapter(adapter);
Products.removeEventListener(productlistener);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "HI", Toast.LENGTH_SHORT).show();
}
}
[EDIT] I'm new to android development, so please bear with me. I have two java classes named Join Game, extends to AppCompatActivity and HintList,extends to ArrayAdapter<>. This is connected to a database. So maybe its one of the factors?
For the layout of join game, I have a listview
and for the layout of hintlist I have three textview.
The code goes this way
JoinGame
public class JoinGame extends AppCompatActivity {
ListView list;
String[] itemdescription = {};
String[] itemhints = {};
String[] itemlocasyon = {};
ProgressDialog progress;
View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_joingame);
Button schan = (Button)findViewById(R.id.tarascan);
schan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(JoinGame.this,ScanActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
progress = new ProgressDialog(this);
progress.setMessage("Connecting...");
progress.setCancelable(false);
progress.show();
RequestFactory.joingameitems(JoinGame.this, RequestFactory.user_id, new RequestCallback<JSONArray>() {
#Override
public void onSuccess(final JSONArray response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
RequestFactory.response = response;
itemdescription = new String[response.length()];
itemhints = new String[response.length()];
itemlocasyon = new String[response.length()];
for (int hl = 0; hl < response.length(); hl++){
try{
itemdescription[hl] = ((String)(response.getJSONObject(hl)).get("description"));
itemhints[hl] = ((String)(response.getJSONObject(hl)).get("hint"));
itemlocasyon[hl] = ((String)(response.getJSONObject(hl)).get("location"));
} catch (JSONException e) {
e.printStackTrace();
}
} ////////// below this is the adapter
final HintList hladapt = new HintList(JoinGame.this,itemdescription,itemlocasyon,itemhints);
list = (ListView)findViewById(R.id.item_hints_and_location);
list.setAdapter(hladapt);
progress.dismiss();
}
});
}
#Override
public void onFailed(final String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(JoinGame.this, message, Toast.LENGTH_LONG).show();
progress.dismiss();
}
});
}
});
}
});
}
HintList
public class HintList extends ArrayAdapter<String> {
private final Activity context;
private String[] itemDesc = {};
private String[] itemHints = {};
private String[] itemLocation = {};
public HintList(Activity context,String[] itemDesc,String[] itemhints,String[] itemlocation) {
super(context,R.layout.hints_list);
this.context = context;
this.itemDesc = itemDesc;
itemHints = itemhints;
itemLocation = itemlocation;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.hints_list, null, true);
TextView itemDesc2 = (TextView)rowView.findViewById(R.id.itemdescription);
TextView itemHint = (TextView)rowView.findViewById(R.id.itemhint);
TextView itemLocation2 = (TextView)rowView.findViewById(R.id.itemlocation);
itemDesc2.setText(itemDesc[position]);
itemHint.setText(itemHints[position]);
itemLocation2.setText(itemLocation[position]);
return rowView;
}
}
I actually retrieved the data (here)
E/DB: [{"description":"chinese garter","location":"near Tricycle station","hint":"garter plus chinese"},{"description":"isang pinoy game","location":"near ....","hint":"may salitang baka"},{"description":"\"tinik\"","location":"below...","hint":"may salitang tinik"},{"description":"aka Tinubigan","location":"at the back...","hint":"katunog ng pintero"},{"description":"\"knock down the can\"","location":"near...","hint":"gumagamit ng lata"}]
but it doesnt display on my listview
I dont know anymore what I should do.
I actually tried making this (I added view)
final HintList hladapt = new HintList(JoinGame.this,itemdescription,itemlocasyon,itemhints);
list = (ListView)view.findViewById(R.id.item_hints_and_location);
list.setAdapter(hladapt);
progress.dismiss();
but it will only returns an error of java.lang.NullPointerException: Attempt to invoke virtual method
Change this:
View rowView = inflater.inflate(R.layout.hints_list, null, true);
to:
View rowView = inflater.inflate(R.layout.hints_list, parent, false);
Modify your getView() method to:
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.hints_list, parent, false);
TextView itemDesc2 = (TextView)rowView.findViewById(R.id.itemdescription);
TextView itemHint = (TextView)rowView.findViewById(R.id.itemhint);
TextView itemLocation2 = (TextView)rowView.findViewById(R.id.itemlocation);
itemDesc2.setText(itemDesc[position]);
itemHint.setText(itemHints[position]);
itemLocation2.setText(itemLocation[position]);
return rowView;
}
try adding getCount
#Override
public int getCount() {
return itemHints.length;
}
Try to change your code to this
public class HintList extends ArrayAdapter<String> {
private final Activity context;
private String[] itemDesc = {};
private String[] itemHints = {};
private String[] itemLocation = {};
private LayoutInflater inflater=null;
public HintList(Activity context,String[] itemDesc,String[] itemhints,String[] itemlocation) {
super(context,R.layout.hints_list);
this.context = context;
this.itemDesc = itemDesc;
itemHints = itemhints;
itemLocation = itemlocation;
inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return itemHints.length;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view==null){
view=inflater.inflate(R.layout.hints_list, null, true);
holder = new ViewHolder(view);
view.setTag(holder);
}else {
holder = (ViewHolder) view.getTag();
}
holder.itemDesc2.setText(itemDesc[position]);
holder.itemHint.setText(itemHints[position]);
holder.itemLocation2.setText(itemLocation[position]);
return view;
}
static class ViewHolder{
TextView itemDesc2,itemHint,itemLocation2;
ViewHolder(View view) {
itemDesc2 = (TextView)view.findViewById(R.id.itemdescription);
itemHint = (TextView)view.findViewById(R.id.itemhint);
itemLocation2 = (TextView)view.findViewById(R.id.itemlocation);
}
}
}
My suggestions is create a bean class (DetailsBean), used for setter and getter method, and also the ArrayList (details1).
List<DetailsBean> details1 = new ArrayList<>(); // declare this as global
Then add the bean to below code
public void run() {
RequestFactory.response = response;
itemdescription = new String[response.length()];
itemhints = new String[response.length()];
itemlocasyon = new String[response.length()];
for (int hl = 0; hl < response.length(); hl++){
try{
itemdescription[hl] = ((String)(response.getJSONObject(hl)).get("description"));
itemhints[hl] = ((String)(response.getJSONObject(hl)).get("hint"));
itemlocasyon[hl] = ((String)(response.getJSONObject(hl)).get("location"));
// here the bean
DetailsBean dbean = new DetailsBean(itemDescription, itemhints, itemlocasyon);
details1.add(dbean); // add all the data to details1 ArrayList
HintList hladapt = new HintList(getActivity(), details1);
(ListView)findViewById(R.id.item_hints_and_location);
list.setAdapter(hladapt);
} catch (JSONException e) {
e.printStackTrace();
}
}
Your DetailsBean should looked like this
public class DetailsBean {
private String itemDescription="";
private String itemhints="";
private String itemlocasyon ="";
public DetailsBean(String description, String hints, String itemlocasyon) {
this.itemDescription=description;
.....
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDesription;
}
public String getItemDescription() {
return itemDescription;
}
....
}
Then your HintList
public class HintList extends BaseAdapter{
Activity context;
List<DetailsBean> details;
private LayoutInflater mInflater;
public CustomBaseAdapter(Activity context,List<DetailsBean> details) {
this.context = context;
this.details = details;
}
........
}
Add these Override methods in your adapter
#Override
public int getCount() {
return itemHints.length;
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}