I have a database with table image, i have atribut id_image(int), image_name(string)
This is the web services that will be used to get the image_name URL=http://lomapod.azurewebsites.net/readBarang.php?id_penjual=1
This is how will i call the ImageURL
ImageUrl= http://lomapod.esy.es/assets/(image_name).jpg
gridItem.java
public class gridItem {
String imageUrl;
String barang;
public gridItem(String barang, String imageUrl) {
super();
this.imageUrl = imageUrl;
this.barang = barang;
}
public String getImageUrl() {
return imageUrl;
}
public String getBarang() {
return barang;
}
}
CustomGridViewAdapter.Java
public class CustomGridViewAdapter extends ArrayAdapter<gridItem> {
Context context;
int layoutResourceId;
ArrayList<gridItem> data = new ArrayList<>();
public CustomGridViewAdapter(Context context, int layoutResourceId,
ArrayList<gridItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RecordHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RecordHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.tvItem);
holder.imageItem = (ImageView) row.findViewById(R.id.imageView);
row.setTag(holder);
} else {
holder = (RecordHolder) row.getTag();
}
gridItem item = data.get(position);
holder.txtTitle.setText(item.getBarang());
Picasso.with(context).
load(item.getImageUrl()).
into(holder.imageItem);
return row;
}
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
}
}
MainActivity.Java
public class MainActivity extends ActionBarActivity {
JSONParser jParser= new JSONParser();
ArrayList<HashMap<String, String>> nameList;
JSONArray names=null;
GridView data;
private static final String URL_TEST_BARANG= "http://lomapod.azurewebsites.net/readBarang.php?id_penjual=1";
private static final String TAG_PESAN = "message";
private static final String TAG_HASIL = "result";
private static final String TAG_BARANG = "nama_barang";
private static final String TAG_IMAGE= "image_name";
ImageView imageview;
CustomGridViewAdapter mGridAdapter;
ArrayList<gridItem> mGridData;
public MainActivity()
{}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data=(GridView) findViewById(R.id.lvSeller);
nameList= new ArrayList<HashMap<String, String>>();
imageview =(ImageView) findViewById(R.id.imageView);
mGridData=new ArrayList<>();
mGridAdapter=new CustomGridViewAdapter(this,R.layout.grid_item,mGridData);
data.setAdapter(mGridAdapter);
new AmbilDataJson().execute();
}
public class AmbilDataJson extends AsyncTask<String,String,String> {
int sukses=0;
public AmbilDataJson() {}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
try
{
JSONObject json = jParser.makeHttpRequest(URL_TEST_BARANG, "GET", params);
if(json != null)
{
sukses = json.getInt(TAG_PESAN);
if(sukses == 0)
{
nameList = new ArrayList<HashMap<String,String>>();
Log.d("Semua Nama: ", json.toString());
names = json.getJSONArray(TAG_HASIL);
for(int i = 0; i < names.length();i++)
{
JSONObject c = names.getJSONObject(i);
String barang = c.getString(TAG_BARANG);
String image = "lomapod.esy.es/assets/"+c.getString(TAG_IMAGE);
HashMap<String,String> map = new HashMap<String,String>();
map.put(TAG_BARANG,barang);
map.put(TAG_IMAGE,image);
nameList.add(map);
}
}
}
}catch(JSONException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
if(sukses == 0)
{
CustomGridViewAdapter adapter = new CustomGridViewAdapter(
MainActivity.this,R.layout.grid_item,mGridData);
mGridAdapter.setGridData(mGridData);
}
else
{
Toast.makeText(MainActivity.this,"Failed",Toast.LENGTH_LONG);
}
}
}
}
I want to display the image to gridview in android studio, but i don't what should i do in MainActivity.
Can anyone tell me how? Thanks in advanced
Firstly, you need to fill your List, and pass it to the adapter. After that, you need to set your adapter to GridView.
Related
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();
}
}
I want to use picasso lib in a "RecyclerViewAdapter". I want to display different images for each entry. It worked for my when I only use text...
I parse a JSON file with the data I use in getDataSet().
At the moment I have no idea how I can use the picasso function to add the images to the dataSet.
WRONG => int imageUrl = Picasso.
CardViewActivity.java
public class CardViewActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "CardViewActivity";
// url to make request - Hole fixe Coupons (max. 100)
private static String url = "http://json.file";
// JSON Node names
private static final String TAG_FIXES = "result";
private static final String TAG_TITEL = "titel";
private static final String TAG_BESCHREIBUNG = "beschreibung";
// contacts JSONArray
JSONArray fixes = null;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_view);
/*
image = (ImageView) findViewById(R.id.image_view);
Picasso.with(getApplicationContext())
.load("http://1UVZ8A9DRLH/bild.jpg")
.placeholder(R.drawable.logo)
.fit().centerCrop().into(image);
*/
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyRecyclerViewAdapter(getDataSet());
mRecyclerView.setAdapter(mAdapter);
// Code to Add an item with default animation
//((MyRecyclerViewAdapter) mAdapter).addItem(obj, index);
// Code to remove an item with default animation
//((MyRecyclerViewAdapter) mAdapter).deleteItem(index);
}
#Override
protected void onResume() {
super.onResume();
((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter
.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.i(LOG_TAG, " Clicked on Item " + position);
}
});
}
private ArrayList<DataObject> getDataSet() {
ArrayList results = new ArrayList<DataObject>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of fixes
fixes = json.getJSONArray(TAG_FIXES);
// looping through All Contacts
for(int i = 0; i < fixes.length(); i++){
JSONObject f = fixes.getJSONObject(i);
// Storing each json item in variable
String titel = f.getString(TAG_TITEL);
String description = f.getString(TAG_BESCHREIBUNG);
int imageUrl = Picasso.with(getApplicationContext())
.load("http://1UVZ8A9DRLH/bild.jpg")
.placeholder(R.drawable.logo)
.fit().centerCrop().into(image);
DataObject obj = new DataObject(
titel,
description,
imageUrl
);
results.add(i, obj);
}
} catch (JSONException e) {
e.printStackTrace();
}
return results;
}
}
DataObject.java
public class DataObject {
private String mText1;
private String mText2;
private int imageUrl;
DataObject(String text1, String text2, int imageUrl){
mText1 = text1;
mText2 = text2;
imageUrl = imageUrl;
}
public String getmText1() { return mText1; }
public void setmText1(String mText1) {
this.mText1 = mText1;
}
public String getmText2() {
return mText2;
}
public void setmText2(String mText2) { this.mText2 = mText2; }
public int getImageUrl() { return imageUrl; }
public void getImageUrl(int imageUrl) {
this.imageUrl = imageUrl;
}
}
MyRecyclerViewAdapter
public class MyRecyclerViewAdapter extends RecyclerView
.Adapter<MyRecyclerViewAdapter
.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<DataObject> mDataset;
private static MyClickListener myClickListener;
public static class DataObjectHolder extends RecyclerView.ViewHolder
implements View
.OnClickListener {
TextView label;
ImageView imgViewIcon;
TextView description;
public DataObjectHolder(View itemView) {
super(itemView);
label = (TextView) itemView.findViewById(R.id.textView);
imgViewIcon = (ImageView) itemView.findViewById(R.id.image_view);
description = (TextView) itemView.findViewById(R.id.textView2);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
mDataset = myDataset;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view_row, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.label.setText(mDataset.get(position).getmText1());
holder.imgViewIcon.setImageResource(mDataset.get(position).getImageUrl());
holder.description.setText(mDataset.get(position).getmText2());
}
public void addItem(DataObject dataObj, int index) {
mDataset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
Firts set the imageUrl as a DataObject attribute:
...
String titel = f.getString(TAG_TITEL);
String description = f.getString(TAG_BESCHREIBUNG);
int imageUrl = f.getString(TAG_IMAGE); //Assuming TAG_IMAGE is the name of the Json attribute with the image url
DataObject obj = new DataObject(
titel,
description,
imageUrl);
...
Then on your adapter do the following:
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.label.setText(mDataset.get(position).getmText1());
Picasso.with(context).load(mDataset.get(position).getImageUrl()).into(holder.imgViewIcon);
holder.description.setText(mDataset.get(position).getmText2());
}
In your onBindViewHolder call Picasso to load an image to your ImageView. Like this:
Picasso.with(context).load("url").into(imageView);
[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;
}
I am using recyclerview adapter for my fragment, but my list is not getting shown as the onCreateViewHolder() and onBindViewHolder() are not getting called. Please let me know what is the issue with my code?
MyFragment code :
public class MyFragment extends Fragment {
private Integer mCurrentPage = 1;
private Integer mChosenOrder=0;
ArrayList<MyParcelableObject> mMyList;
private RecyclerView mRecyclerView;
MyAdapter mMyAdapter;
public MyFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mRecyclerView= (RecyclerView) rootView.findViewById(R.id.gridview_movies);
mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
Log.e(LOG_TAG, "In oncreateview");
if (savedInstanceState != null && savedInstanceState.getParcelableArrayList(ConstantUtil.My_LIST_KEY) != null) {
mMyList = savedInstanceState.getParcelableArrayList(ConstantUtil.My_LIST_KEY);
} else {
mMyList = new ArrayList<>();
}
new MyTask(getActivity(), mMyList,mMyAdapter).execute(mChosenOrder);
mMyAdapter = new MyAdapter(getActivity(),mMyList);
Log.e(LOG_TAG,"Adapter size oncreateview"+mMyAdapter.getItemCount());
mRecyclerView.setAdapter(mMyAdapter);
Log.e(LOG_TAG, "In oncreateview after attaching adapter");
return rootView;
}
#Override
public void onStart() {
super.onStart();
populate();
}
private void populate() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (prefs != null) {
String order = prefs.getString(getString(R.string.sorting_order), getString(R.string.pref_defaultValue));
int order_value = Integer.parseInt(order);
if (order_value >= 0) {
Resources resources = getResources();
mChosenOrder = Integer.parseInt(resources.getStringArray(R.array.pref_sorting_values)[order_value]);
} else {
mChosenOrder = order_value;
}
} else {
mChosenOrder = Integer.parseInt(getString(R.string.pref_defaultValue));
}
new MyTask(getActivity(),mMyList,mMyAdapter).execute(mChosenOrder);
Log.e(LOG_TAG,"populate Adapter size "+mMyAdapter.getItemCount());
mRecyclerView.setAdapter(mMyAdapter);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(ConstantUtil.My_LIST_KEY, mMyList);
}
}
Async Task code
public class MyTask extends AsyncTask<Integer, Void, MyParcelableObject[]> {
private Context context;
private List<MyParcelableObject> mMyParcelableObjects;
private RecyclerView recyclerView;
MyAdapter myAdapter;
public MyTask(Context context, List<MyParcelableObject> myParcelableObjects,MyAdapter myAdapter) {
this.context = context;
mMyParcelableObjects = myParcelableObjects;
this.myAdapter = myAdapter;
//this.imageAdapter = imageAdapter;
this.recyclerView = recyclerView;
}
#Override
protected MyParcelableObject[] doInBackground(Integer... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String myStr[] = null;
// Will contain the raw JSON response as a string.
String myStrJsonStr = null;
Uri buildUri = null;
MyParcelableObject[] myParcelableObjects = null;
//try {
// Context context = getApplicationContext();
ArrayList<MyParcelableObject> myParcelableObjectArrayList = null;
String[] sortOrder = context.getResources().getStringArray(R.array.pref_sorting_values);
int sort = Integer.parseInt(sortOrder[0]);
myParcelableObjectArrayList = getJsonFromUri(params[0]); //correctly gets the json array
if (myParcelableObjectArrayList != null) {
myParcelableObjects = myParcelableObjectArrayList.toArray(new MyParcelableObject[myParcelableObjectArrayList.size()]);
return myParcelableObjects;
return null;
}
/**
* #param results
*/
#Override
protected void onPostExecute(MyParcelableObject[] results) {
Log.e(LOG_TAG, "In onPostExecute");
if (results != null) {
mMyParcelableObjects = Arrays.asList(results);
myAdapter = new MyAdapter(context,mMyParcelableObjects);
Log.e(LOG_TAG,"adapter size"+myAdapter.getItemCount());
myAdapter.notifyDataSetChanged();
}
}
Adapter code
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
List<MyParcelableObject> mParcelableObjects;
ViewHolder mViewHolder;
Context mContext;
public MyAdapter(Context context, List<MyParcelableObject> parcelableObjects) {
mParcelableObjects = parcelableObjects;
mContext=context;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public ViewHolder(View view) {
super(view);
mImageView = (ImageView) view.findViewById(R.id.movie_content_imageview);
}
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.e("LOG_TAG","in on onCreateViewHolder");
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.content_main, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
Log.e("LOG_TAG","in on onBindViewHolder");
String myPoster = null;
MyParcelableObject myParcelableObject = mParcelableObjects.get(position);
if (myParcelableObject.poster_path != null) {
myPoster = myParcelableObject.poster_path.replaceAll("/", "");
}
Uri uri = Uri.parse(ConstantUtil.POSTER_URL).buildUpon().
appendPath(ConstantUtil.W342_SIZE).
appendPath(myPoster).build();
Picasso.with(mContext).load(uri).placeholder(R.drawable.resource_notfound).error(R.drawable.resource_notfound).into(mViewHolder.mImageView);
}
#Override
public int getItemCount() {
return mParcelableObjects.size();
}
}
You are not getting value because your list is empty.
replace this
new MyTask(getActivity(), mMyList,mMyAdapter).execute(mChosenOrder);
to this
mMyList = new MyTask(getActivity(), mMyList,mMyAdapter).execute(mChosenOrder).get();
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);