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();
}
}
Related
I have a recycler view to show an activity timeline and three floating buttons that click to add activity. How can I code three buttons to a different view? How can I pass the condition to the Adapter?
Now I can show only one viewType.
thx a lot.
Adapter.java
public class TripAdapter extends RecyclerView.Adapter<TripAdapter.TripHolder> {
private List<Trip> trips = new ArrayList<>();
private OnItemClickListener listener;
#NonNull
#Override
public TripHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.trip_item, parent, false);
return new TripHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull TripHolder holder, int position) {
Trip currentTrip = trips.get(position);
holder.textViewLodgingTitle.setText(currentTrip.getLodgingTitle());
holder.textTextViewLodgingCheckInDateTime.setText(currentTrip.getLodgingCheckInDateTime());
holder.textTextViewLodgingCheckOutDateTime.setText(currentTrip.getLodgingCheckOutDateTime());
holder.textViewLodgingAddress.setText(currentTrip.getLodgingAddress());
}
#Override
public int getItemCount() {
return trips.size();
}
public void setTrips(List<Trip> trips) {
this.trips = trips;
notifyDataSetChanged();
}
public Trip getTripAt(int position) {
return trips.get(position);
}
class TripHolder extends RecyclerView.ViewHolder {
//lodging
private TextView textViewLodgingTitle;
private TextView textTextViewLodgingCheckInDateTime;
private TextView textTextViewLodgingCheckOutDateTime;
private TextView textViewLodgingAddress;
private TextView textViewLodgingPhone;
private TextView textViewLodgingWebsite;
private TextView textViewLodgingEmail;
public TripHolder(#NonNull View itemView) {
super(itemView);
context = itemView.getContext();
textViewLodgingTitle = itemView.findViewById(R.id.text_view_title);
textTextViewLodgingCheckInDateTime = itemView.findViewById(R.id.text_view_start_date_time);
textTextViewLodgingCheckOutDateTime = itemView.findViewById(R.id.text_view_end_date_time);
textViewLodgingAddress = itemView.findViewById(R.id.text_view_description);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (listener != null && position != RecyclerView.NO_POSITION) {
listener.onItemClick(trips.get(position));
}
}
});
}
}
public interface OnItemClickListener {
void onItemClick(Trip trip);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
}
MainActivity.java
//adapter
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
final TripAdapter adapter = new TripAdapter();
recyclerView.setAdapter(adapter );
tripViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(TripViewModel.class);
tripViewModel.getAllTrips().observe(this, new Observer<List<Trip>>() {
#Override
public void onChanged(#Nullable List<Trip> trips) {
adapter.setTrips(trips);
}
});
//this on onActivityResult()
else if (requestCode == ADD_LODGING && resultCode == Activity.RESULT_OK) {
//get data from lodging activity
String lodgingTitle = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_TITLE);
String lodgingCheckInDateTime = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_CHECK_IN_DATE_TIME);
String lodgingCheckOutDateTime = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_CHECK_OUT_DATE_TIME);
String lodgingDescription = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_DESCRIPTION);
String lodgingAddress = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_ADDRESS);
String lodgingPhone = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_PHONE);
String lodgingWebsite = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_WEBSITE);
String lodgingEmail = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_EMAIL);
String lodgingImagePath = "test";
Trip lodging = new Trip(lodgingTitle, lodgingCheckInDateTime, lodgingCheckOutDateTime,lodgingDescription, lodgingAddress, lodgingPhone, lodgingWebsite, lodgingEmail,lodgingImagePath);
tripViewModel.insert(lodging);
Toast.makeText(this, "lodging save", Toast.LENGTH_SHORT).show();
}
My application I adapt from codinginflow channel.
https://codinginflow.com/tutorials/android/room-viewmodel-livedata-recyclerview-mvvm/part-1-introduction
how to get ID position in call retrofit
GET https://api.themoviedb.org/3/movie/{movie_id}/credits?api_key=<>
i need to get position id send to server in loadCast function
and in MovieService that's retrofit call i need send postion id befor credits
i don't know how to do that if any one can help me thanks so much for that <3
//this my call retrofit server
public interface MovieService {
#GET("popular?" + Common.API_KEY + "&language=en-US")
Call<MoviesList> getPopular(#Query("api_key") String api_key);
#GET( ListMovieAdapter.SELECTED_MOVIE +"/credits?" + Common.API_KEY +
"&language=en-US")
Call<MovieCast> getCast(
#Query("api_key") String api_key);
----------------------------------------------------------------
package com.example.android.movie;
/**
* Created by yuyu on 12-Nov-18.
*/
public class MovieDetails extends YouTubeBaseActivity {
Result selectedMovie;
private ArrayList<Cast> cast;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerView mRecyclerView;
private CastMovieAdapter castMovieAdapter;
private TextView name;
private ImageView imageMovie;
private TextView date;
private TextView rating;
private ArrayList<Result> results;
MovieService mService;
private static final String YT_API_KEY = "###";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_details);
selectedMovie =
getIntent().getParcelableExtra(ListMovieAdapter.SELECTED_MOVIE);
mRecyclerView = (RecyclerView) findViewById(R.id.cast_recycler);
mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
cast = new ArrayList<>();
castMovieAdapter = new CastMovieAdapter(cast, MovieDetails.this);
mRecyclerView.setAdapter(castMovieAdapter);
results = new ArrayList<>();
mService = Common.getMovieService();
loadTriler();
loadMovies();
loadCast();
}
this function to load movie
private void loadMovies() {
mService.getPopular(Common.API_KEY).enqueue(new Callback<MoviesList>()
{
#Override
public void onResponse(Call<MoviesList> call, Response<MoviesList>
response) {
results.clear();
results.addAll(response.body().getResults());
name = (TextView) findViewById(R.id.name_movie);
rating = (TextView) findViewById(R.id.rating);
date = (TextView) findViewById(R.id.date_det);
imageMovie = (ImageView) findViewById(R.id.imageView);
date.setText(selectedMovie.getReleaseDate());
name.setText(selectedMovie.getTitle());
rating.setText(String.valueOf(selectedMovie.getVoteAverage()));
final String image = Common.IMAGE_LOAD +
selectedMovie.getPosterPath();
Picasso.with(MovieDetails.this)
.load(image)
.into(imageMovie);
}
#Override
public void onFailure(Call<MoviesList> call, Throwable t) {
Log.d("===LoadMovies", "onResponse: " + t);
}
});
}
//i have proplem here in send ID postion
private void loadCast() {
mService.getCast(
ListMovieAdapter.SELECTED_MOVIE+Common.API_KEY).enqueue(new
Callback<MovieCast>() {
#Override
public void onResponse(Call<MovieCast> call, final
Response<MovieCast> response) {
cast.clear();
cast.addAll(response.body().getCast());
mRecyclerView.getAdapter().notifyDataSetChanged();
}
#Override
public void onFailure(Call<MovieCast> call, Throwable t) {
}
});
}
}
package com.example.android.movie.Adapter;
/**
* Created by yuyu on 11-Nov-18.
*/
public class ListMovieAdapter extends
RecyclerView.Adapter<ListMovieAdapter.MyViewHolder> {
private ArrayList<Result> mMovies;
private Context context;
public static final String SELECTED_MOVIE = "selected_movie";
private int lastPosition = -1;
public ListMovieAdapter(ArrayList<Result> mMovies, Context context) {
this.mMovies = mMovies;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.list_views, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
//Animation Scroll
Animation animation = AnimationUtils.loadAnimation(context,
(position > lastPosition) ? R.anim.up_from_bottom
: R.anim.down_from_top);
holder.itemView.startAnimation(animation);
lastPosition = position;
holder.nameMovie.setText(mMovies.get(position).getTitle());
final String image = Common.IMAGE_LOAD +
mMovies.get(position).getPosterPath();
Picasso.with(context)
.load(image)
.into(holder.imageMovie);
holder.rating.setText(String.valueOf(
mMovies.get(position).getVoteAverage()));
holder.dateMovie.setText(mMovies.get(position).getReleaseDate());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(context, MovieDetails.class);
Result result = mMovies.get(position);
intent.putExtra(SELECTED_MOVIE, result);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mMovies.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
ImageView imageMovie;
TextView nameMovie;
TextView rating;
TextView dateMovie;
ItemClickListener itemClickListener;
public MyViewHolder(View itemView) {
super(itemView);
this.imageMovie = (ImageView)
itemView.findViewById(R.id.image_movie);
this.nameMovie = (TextView) itemView.findViewById(R.id.name_movie);
this.rating = (TextView) itemView.findViewById(R.id.rating);
this.dateMovie = (TextView) itemView.findViewById(R.id.date);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View v) {
itemClickListener.onClick(v, getAdapterPosition());
}
}
}
From the Retrofit documentation:
URL MANIPULATION A request URL can be updated dynamically using
replacement blocks and parameters on the method. A replacement block
is an alphanumeric string surrounded by { and }. A corresponding
parameter must be annotated with #Path using the same string.
#GET("group/{id}/users")
Call<List<User>> groupList(#Path("id") int groupId);
https://square.github.io/retrofit/
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.
[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 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);