RecycleView not calling methods - android

I'm trying to fetch data from a JSON, but it doesn't seem to work. OnBindViewHolder is never called...
ADAPTER CODE:
public class AdapterRallye extends RecyclerView.Adapter<AdapterRallye.MyViewHolder> implements View.OnClickListener {
private Context context;
private View.OnClickListener listener;
private List<DataRallye> data;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView Rallye_Nom;
public ImageView Rallye_Foto;
public TextView Rallye_Provincia;
public TextView Rallye_DataI;
public TextView Rallye_Tipus;
// create constructor to get widget reference
public MyViewHolder(final View itemView) {
super(itemView);
Rallye_Nom = (TextView) itemView.findViewById(R.id.tv_nom);
Rallye_Foto = (ImageView) itemView.findViewById(R.id.iv_foto);
Rallye_Provincia = (TextView) itemView.findViewById(R.id.tv_provincia);
Rallye_DataI = (TextView) itemView.findViewById(R.id.tv_datai);
Rallye_Tipus = (TextView) itemView.findViewById(R.id.tv_tipus);
}
}
// create constructor to innitilize context and data sent from MainActivity
public AdapterRallye(List<DataRallye> dadesrally) {
this.data = dadesrally;
}
// Inflate the layout when viewholder created
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.container_rallye, parent, false);
view.setOnClickListener(this);
return new MyViewHolder(view);
}
// Bind data
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
// Get current position of item in recyclerview to bind data and assign values from list
DataRallye current = data.get(position);
holder.Rallye_Nom.setText(current.getRallyeNom());
holder.Rallye_Tipus.setText(current.getRallyeTipus());
holder.Rallye_DataI.setText(current.getRallyeDataI());
holder.Rallye_Provincia.setText(current.getRallyeProvincia());
holder.Rallye_Provincia.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
// load image into imageview using glide
Glide.with(context).load("http://rallyecat.esy.es/fotos/" + current.getRallyeFoto())
.placeholder(R.drawable.rallyecatlogo)
.error(R.drawable.rallyecatlogo)
.into(holder.Rallye_Foto);
}
public void setOnClickListener(View.OnClickListener listener) {
this.listener = listener;
}
#Override
public void onClick(View view) {
if (listener != null)
listener.onClick(view);
}
// return total item from List
#Override
public int getItemCount() {
return data.size();
}
}
FRAGMENT CODE:
public class FragmentRally extends Fragment {
public FragmentRally() {
// Required empty public constructor
}
private List<DataRallye> llistarallyes = new ArrayList<>();
private RecyclerView recyclerView;
private AdapterRallye mAdapter;
private Intent intent;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fragment_rally, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.llistarallyes);
mAdapter = new AdapterRallye(llistarallyes);
recyclerView.setAdapter(mAdapter);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
new AsyncFetch().execute();
mAdapter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(getActivity(), ActivitatDetalls.class);
intent.putExtra("nombarra", llistarallyes.get(recyclerView.getChildAdapterPosition(view)).getRallyeNom());
startActivity(intent);
}
});
return rootView;
}
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(getActivity());
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tCarregant...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json llistarallyes
url = new URL("http://www.rallyecat.esy.es/Obtenir_events.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive llistarallyes from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve llistarallyes from json file
//conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read llistarallyes sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line + "\n");
}
// Pass llistarallyes to onPostExecute method
return (result.toString());
} else {
Toast.makeText(getActivity(), "No hi ha connexió a internet.",
Toast.LENGTH_LONG).show();
return ("No hi ha connexió a internet.");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract llistarallyes from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataRallye dadesrallye = new DataRallye();
dadesrallye.setRallyeNom(json_data.getString("nom"));
dadesrallye.setRallyeTipus(json_data.getString("tipus"));
dadesrallye.setRallyeDataI(json_data.getString("datai"));
dadesrallye.setRallyeProvincia(json_data.getString("provincia"));
dadesrallye.setRallyeFoto(json_data.getString("foto"));
llistarallyes.add(dadesrallye);
}
} catch (JSONException e) {
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.fragment_fragment_rally, parent, false));
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(v.getContext(), ActivitatDetalls.class);
context.startActivity(intent);
}
});
}
}
}
I've seen other StackOverflow posts where the problem is already solved, but I've been trying alot of the solutions the user said, but none is working...
Thanks!

Try to call mAdapter.notifyDataSetChanged(); in onPostExecute() method.
You need to notify your adapter after you made changes.

Related

RecyclerView displaying wrong data in other positions

I am creating a RecyclerView with Card view
my json data contains movie name,year,rating
my card view contains three text fields moviename,rating,year
when i click on rating field it should get the data from the json and display rating beside the rating text field, but the problem here is when i click on text field the data of my card view is displayed on other positions of the card view also.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = findViewById(R.id.recylcerview);
movieList = new ArrayList<>();
builder = new AlertDialog.Builder(this);
adapter = new MovieAdapter(this, movieList);
linearLayoutManager = new LinearLayoutManager(this);
dividerItemDecoration = new DividerItemDecoration(mList.getContext(), linearLayoutManager.getOrientation());
mList.setHasFixedSize(true);
mList.setLayoutManager(linearLayoutManager);
mList.addItemDecoration(dividerItemDecoration);
mList.setAdapter(adapter);
if ((isNetworkConnected() == true)) {
getData();
} else {
builder.setTitle("turn on internet");
builder.setCancelable(false);
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.create();
builder.show();
}
}
#Override
protected void onResume() {
super.onResume();
if ((isNetworkConnected() == true)) {
getData();
adapter.notifyDataSetChanged();
} else {
builder.setTitle("turn on internet");
builder.setCancelable(false);
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.create();
builder.show();
}
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = this.getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private void getData() {
builder = new AlertDialog.Builder(this);
try {
JSONObject reader = new JSONObject(loadJSONFromAsset());
JSONArray jArray = reader.getJSONArray("rootnode");
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject jsonObject = jArray.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(jsonObject.getString("title"));
movie.setRating(jsonObject.getDouble("rating"));
movie.setYear(jsonObject.getInt("releaseYear"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
There should not be any duplicate data in my recycler view
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> {
private Context context;
Movie movie;
public MovieAdapter(Context context, ArrayList<Movie> list) {
this.context = context;
this.list = list;
}
private ArrayList<Movie> list;
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.single_item, parent, false);
final ViewHolder viewHolder = new ViewHolder(v);
viewHolder.view_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Intent i=new Intent(context,Main2Activity.class);
// String a=list.get(viewHolder.getAdapterPosition()).getTitle();
// Double b=list.get(viewHolder.getAdapterPosition()).getRating();
// int c=list.get(viewHolder.getAdapterPosition()).getYear();
// String g =String.valueOf(c);
// viewHolder.textYear.setText(g);
// i.putExtra("movie",a);
// i.putExtra("rating",b);
// i.putExtra("year",c);
// context.startActivity(i);
}
});
viewHolder.something.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Double w = list.get(viewHolder.getAdapterPosition()).getRating();
String k = Double.toString(w);
viewHolder.textRating.setText(k);
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
movie = list.get(position);
holder.textTitle.setText(movie.getTitle());
holder.view_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int c = list.get(holder.getAdapterPosition()).getYear();
String g = String.valueOf(c);
holder.textYear.setText(g);
}
});
// holder.textRating.setText(String.valueOf(movie.getRating()));
// holder.textYear.setText(String.valueOf(movie.getYear()));
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView view_container;
TextView something;
public TextView textTitle, textRating, textYear;
public ViewHolder(#NonNull View itemView) {
super(itemView);
view_container = itemView.findViewById(R.id.textView5);
something = itemView.findViewById(R.id.Rating);
textTitle = itemView.findViewById(R.id.title);
textRating = itemView.findViewById(R.id.textView2);
textYear = itemView.findViewById(R.id.main_year);
}
}
}
Never bind data with view inside onCreateViewHolder method as you have done this on click of something' ,holder.textYear.setText(g);`
So instead of managing it like this, I suggest you to manage your rating textview with visibility.
Just move your click action inside onBindViewHolder(), and do below changes with it.
Double w = list.get(viewHolder.getAdapterPosition()).getRating();
String k = Double.toString(w);
viewHolder.textRating.setText(k);
viewHolder.textRating.setVisibility(View.INVISIBLE);
viewHolder.something.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewHolder.textRating.setVisibility(View.VISIBLE);
}
});
To maintain the review state:
First create one booelan variable inside your model class and generate getter-setter for that.
i.e.
private boolean isReviewedVisible = false;
public boolean isReviewedVisible() {
return isReviewedVisible;
}
public void setIsReviewedVisible(boolean isVisible) {
this.isReviewedVisible = isVisible;
}
Than add below checks in onBindViewHolder() method.
if(movie.isReviewedVisible()){
viewHolder.textRating.setVisibility(View.VISIBLE);
} else {
viewHolder.textRating.setVisibility(View.INVISIBLE);
}
viewHolder.something.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
movie.setReviewedVisible(true);
viewHolder.textRating.setVisibility(View.VISIBLE);
}
});

Android Recycle View inside fragment show "No adapter attached; skipping layout "

if i write this code in a class extends AppCompatActivity it
works but in a fragment class i don't know why it doesn't work .
in the activity that has this fragment i use another adapter
to show products with the same code and it works
public class Categroy extends Fragment{
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
public RecyclerView mRVcategoryList;
public AdapterCategory mAdapter;
private String myurl="http://10.0.3.2/mobilaApp/category.php";
// private String categoryurl="http://10.0.3.2/mobilaApp/category.php";
public LinearLayoutManager layoutManager;
List<DataCategory> data=new ArrayList<>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// execute asyncLogin
new AsyncLogin().execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_categroy, container, false);
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.rvcat);
// 2. set layoutManger
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// 3. create an adapter
AdapterCategory mAdapter = new AdapterCategory(getActivity().getApplicationContext(), data);
// 4. set adapter
recyclerView.setAdapter(mAdapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
return rootView;
}
private class AsyncLogin extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(getActivity());
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL(myurl);
// urlcat = new URL(categoryurl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
// dississ dialog pdLoading.dismiss();
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
DataCategory categorydata = new DataCategory();
categorydata.name_cat= json_data.getString("name_cat");
data.add(categorydata);
}
mRVcategoryList = (RecyclerView)getActivity(). findViewById(R.id.rvcat);
mAdapter = new AdapterCategory(getActivity().getApplicationContext(), data);
mRVcategoryList.setAdapter(mAdapter);
mRVcategoryList.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
/* if i write this code in a class extends AppCompatActivity it
works but in a fragment class i don't know why it doesn't work .
in the activity that has this fragment i use another adapter
to show products with the same code and it works
*/
Adapter is here
public AdapterCategory(Context context, List<DataCategory> data){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
}
// Inflate the layout when viewholder created
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.categoryrow, parent,false);
MyHolder holder=new MyHolder(view);
return holder;
}
// Bind data
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// Get current position of item in recyclerview to bind data and assign values from list
MyHolder myHolder= (MyHolder) holder;
DataCategory current=data.get(position);
myHolder.namecat.setText(current.name_cat);
}
// return total item from List
#Override
public int getItemCount() {
return data.size();
}
class MyHolder extends RecyclerView.ViewHolder{
TextView namecat;
// TextView textPrice;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
namecat= (TextView) itemView.findViewById(R.id.category_name);
}
}
}
Set layoutManager to your recyclerView using getContext() instead of getActivity() and it will work.
mListLayoutManager=new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(mListLayoutManager);
Thank you all
the problem was to replace getActivity() by getView() onpostexecute
mRVFishPrice = (RecyclerView)getView().findViewById(R.id.fishPriceList);
mAdapter = new AdapterFish(getActivity(), data);
mRVFishPrice.setAdapter(mAdapter);
mRVFishPrice.setLayoutManager(new LinearLayoutManager(getActivity()));

Handling image button click inside a RecycleView item

I have a button inside CardView which represents item of RecycleView. I've managed to handle the click event inside the ViewHolder class but I need to call function on MainActivity, How can I implement that with below code?
My code as below
ShopItemRecyclerViewAdapter.java
public class ShopItemRecyclerViewAdapter extends RecyclerView.Adapter<ShopItemRecyclerViewAdapter.ListItemViewHolder> {
static ArrayList<ShopListItemModel> list;
LayoutInflater inflater;
public ShopItemRecyclerViewAdapter(ArrayList<ShopListItemModel> list, Context context){
inflater = LayoutInflater.from(context);
this.list = list;
}
public ListItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_item, parent , false);
ListItemViewHolder vh = new ListItemViewHolder(view);
return vh;
}
public void onBindViewHolder(ListItemViewHolder holder, int position) {
ShopListItemModel current = list.get(position);
holder.name.setText(current.getName());
holder.price.setText(String.valueOf(current.getPrice()));
}
public int getItemCount() {
return list.size();
}
public static class ListItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView cv;
TextView name;
TextView price;
ImageButton btnDelete;
ListItemViewHolder(final View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cvShopListItem);
name = (TextView)itemView.findViewById(R.id.name);
price = (TextView)itemView.findViewById(R.id.price);
btnDelete = (ImageButton)itemView.findViewById(R.id.btnDeleteItem);
itemView.setOnClickListener(this);
btnDelete.setOnClickListener(this);
}
#Override
public void onClick(View v) {
//here i can handle the click but i think i need to use it in the main activity
}
}
}
MainActivity.java (skipped irrelevent code)
public class ShopCartScreen extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
RecyclerView cartItems; //recycler to hold the cart list
ArrayList<ShopListItemModel> list = new ArrayList<ShopListItemModel>();
ShopItemRecyclerViewAdapter adapter;
GetShopingCartList getShopingCartList; ////instance of network operation class to retrieve shop cart items list from server data base
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shop_carts_list);
cartItems = (RecyclerView) findViewById(R.id.newListItem);
cartItems.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
cartItems.setLayoutManager(llm)
}
public void bindData(int listNumber) {
getShopingCartList = new GetShopingCartList(this, list, adapter, cartItems, listNumber, totalPrice);
getShopingCartList.execute("link to query which returns json object");
}
}
GetShopingCartList.java for network operation
public class GetShopingCartList extends AsyncTask<String, String, ArrayList<ShopListItemModel>> {
private ArrayList<ShopListItemModel> shopCartItemList;
Context context;
RecyclerView items;
ShopItemRecyclerViewAdapter adapter;
int listNumber;
public GetShopingCartList(Context context, ArrayList<ShopListItemModel> shopCartItemList, ShopItemRecyclerViewAdapter adapter,
RecyclerView items ,int listNumber) {
this.context = context;
this.shopCartItemList = shopCartItemList;
this.adapter = adapter;
this.items = items;
this.listNumber = listNumber;
}
protected ArrayList<ShopListItemModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
shopCartItemList = new ArrayList<ShopListItemModel>();
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("result");
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);//get the cuttent json object which is representaion of shop cart model object
String name = finalObject.getString("name");
String price = finalObject.getString("price");
Double d = Double.parseDouble(price);
ShopListItemModel item = new ShopListItemModel(name, d);
shopCartItemList.add(item);//adds the shopcart to the list of shop carts model
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return shopCartItemList;
}
protected void onPostExecute(ArrayList<ShopListItemModel> s) {
super.onPostExecute(s);
adapter = new ShopItemRecyclerViewAdapter(shopCartItemList, context);
items.setAdapter(adapter);
}
public ArrayList<ShopListItemModel> getList() {
return shopCartItemList;
}
}
Implement a method inside ShopCartScreen.java, then you can use the context object inside the adapter.
((ShopCartScreen)context).methodImplemented(ShopListItemModel model)
//add this code inside onClick event of the button
ok this is my solution if anyone needs it (i combined 2 methods/ 1 in the main activity and 1 in the recycler adapter):
in my recycler adapter i added this delete method:
//delete the item from the recycler Immediately for user interaction
public void delete(int position){
list.remove(position);
notifyItemRemoved(position);
}
in my ViewHolder class:
ListItemViewHolder(final View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cvShopListItem);
name = (TextView)itemView.findViewById(R.id.name);
price = (TextView)itemView.findViewById(R.id.price);
btnDelete = (ImageButton)itemView.findViewById(R.id.btnDeleteItem);
itemView.setOnClickListener(this);
btnDelete.setOnClickListener(this);
}
#Override
public void onClick(View v) {
((ShopCartScreen)context).deleteItem(getPosition());//calls method in main activity
delete(getPosition());
}
and in the main activity:
public void deleteItem(int postion){
list = getShopingCartList.getList();
ShopListItemModel tmp = list.get(postion);
tmp.getName(); //gets the item name to remove
shopCartModel.getNumber(); //gets the cart number for deleting the item for the correct cart
new DeleteCartItem(this , shopCartModel , tmp).execute(); //remove the item from the data base
}

ListView not displaying data in fragment

I am using listview to populate data coming from the server. This listview will show that data in a fragmentTab. Now the data is parsing fine and logcat is also showing the data. But the data is not being populated by listview. I tried to see the error through debugging but there is no problem. Even the Holder in adapter catches the data but it's not displayed. I don't know what the problem is. I tried the following questions but didn't got the answer.
Android - ListView in Fragment does not showing up
Android - ListView in Fragment does not show
ListView in Fragment Not Displayed
Below is my fragment and the adapter.
Tastemaker Fragment:
public class TasteMakersFragment extends Fragment
{
CommonClass commonTasteMakers;
String tasteMaker_url = CommonClass.url+ URLConstants.Host.URL_ALL_SUGGESTED_TASTEMAKERS;
String user_token = "8aa0dcd5aaf54c8a5aaef1aa242f342f";
ListView suggested_list;
List<SuggestedUserModel> suggestedUsers_list = new ArrayList<>();
SuggestedUsersAdapter mAdapter;
int selectedPosition = 0;
public TasteMakersFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.from(getActivity()).inflate(R.layout.suggested_users_tastemakers, null);
commonTasteMakers = new CommonClass(getActivity().getApplicationContext());
suggested_list = (ListView)v.findViewById(R.id.lst_suggestedUsers);
new GetSuggestedUsers().execute(tasteMaker_url);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
private class GetSuggestedUsers extends AsyncTask< String, Void, Void>
{
private ProgressDialog Dialog = new ProgressDialog(getActivity());
protected void onPreExecute() {
if (suggestedUsers_list.isEmpty())
{
Dialog = ProgressDialog.show(getActivity(),"Please be patient!","Fetching for first time...");
}
}
#Override
protected Void doInBackground(String... params)
{
if (suggestedUsers_list.isEmpty())
{
getSuggestedUsers();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
else{
Log.d("---- Already Fetched --", "---- Already Fetched ----");
return null;
}
}
protected void onPostExecute(Void unused)
{
Dialog.dismiss();
mAdapter = new SuggestedUsersAdapter(getActivity(), suggestedUsers_list);
suggested_list.setAdapter(mAdapter);
suggested_list.setSelection(selectedPosition);
mAdapter.notifyDataSetChanged();
//startMainActivity();
}
}
private List<SuggestedUserModel> getSuggestedUsers()
{
StringRequest postRequest = new StringRequest(Request.Method.POST, tasteMaker_url, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try {
//JSONObject jsonResponse = new JSONObject(response).getJSONObject("form");
JSONObject jsonResponse = new JSONObject(response);
if (jsonResponse.has("data"))
{
JSONObject data = jsonResponse.getJSONObject("data");
String code = jsonResponse.getString("code");
if(code.equals("200"))
{
if(data.has("tasteMakers"))
{
JSONArray tastemakers = data.getJSONArray("tasteMakers");
for (int i =0; i<tastemakers.length(); i++)
{
JSONObject jsnObj = tastemakers.getJSONObject(i);
String id = jsnObj.getString("userId");
String name = jsnObj.getString("name");
String profilePic = jsnObj.getString("imgUrl");
Boolean isFollowed = jsnObj.getBoolean("isFollowed");
suggestedUsers_list.add(new SuggestedUserModel(id,
name,
profilePic,
isFollowed));
Log.d("Names are ----", "size is=" + name +" and their id are: "+id);
}
// Log.d("Adapter list ----", "size is=" + suggestedUsers_list.size());
}
}
else {
Log.d("Error0 Error Error", "response------:" + jsonResponse);
}
}
// Log.d("response222---------","response22222------:"+jsonResponse);
} catch (JSONException e) {
Log.d("-----Stop------", "!!!");
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("sessionToken", user_token);
return params;
} };
postRequest.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(getActivity().getApplicationContext()).add(postRequest);
return suggestedUsers_list;
}
}
Adapter Class:
public class SuggestedUsersAdapter extends BaseAdapter {
Context context;
int count = 1;
private List<SuggestedUserModel> allUsers;
public SuggestedUsersAdapter(FragmentActivity activity, List<SuggestedUserModel> suggestUserModel)
{
Log.d("Custom Adapter called", "" + suggestUserModel.size());
context = activity;
allUsers = suggestUserModel;
//FragmentActivity mActivity = activity;
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return allUsers.size();
// return imageId.length;
}
#Override
public Object getItem(int position) {
return allUsers.get(position);
// return position;
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint({"ViewHolder", "InflateParams", "CutPasteId"})
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final mHolder holder;
// int type = getItemViewType(position);
LayoutInflater layoutInflater;
getItemViewType(position);
if (convertView == null)
{
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.suggested_users_tastemaker_cell, null);
holder = new mHolder();
// convertView.setTag(mFeedsListItemViewHolder);
holder.txt_suggestUserName = (TextView) convertView.findViewById(R.id.tv_tasteMakerName);
holder.imgV_userProfile = (ImageView) convertView.findViewById(R.id.imgBtn_tasteMaker_pic);
holder.btnFollow = (Button) convertView.findViewById(R.id.btnFollow_tasteMaker);
holder.btnFollowing = (Button) convertView.findViewById(R.id.btnFollowing);
convertView.setTag(holder);
} else {
holder = (mHolder) convertView.getTag();
}
final SuggestedUserModel suggestUser = allUsers.get(position);
holder.txt_suggestUserName.setText(allUsers.get(position).getSuggested_UserName());
/*if(suggestUser.getSuggested_UserImage().equals(""))
{
Picasso
.with(context)
.load(R.mipmap.ic_launcher)
.transform(new CropSquareTransformationHomePage())
.into(holder.imgV_userProfile);
}
else {
Picasso
.with(context)
.load(suggestUser.getSuggested_UserImage())
.transform(new CropSquareTransformationHomePage())
.into(holder.imgV_userProfile);
}*/
holder.pos = position;
//mFeedsListItemViewHolder.setData(allPersons.get(position));
return convertView;
}
private class mHolder {
TextView txt_suggestUserName;
ImageView imgV_userProfile;
Button btnFollow;
Button btnFollowing;
int pos;
}
}
Note: I already tried declaring listview and assigning adapter in onActivityCreated() method of fragment but no effect.
Any Help will be appreciated.

Custom adapter never empty

I've custom adapter that populates custom listview with data fetched from server. What I want is check if adapter is empty and append data to listview if it is empty else fill the listview with data and notifyDataSetChanged. I'm implementing OnScrollListener to load more data from server. But adapter never is empty and always notifyDataSetChanged is called.
My List Activity
public class ListResultActivity extends Activity implements OnScrollListener{
private ArrayList<BusinessListData> businesses;
private ListView businessList;
private LayoutInflater layoutInflator;
private BusinessListIconTask imgFetcher;
BusinessListDataAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.businesslist);
this.businessList = (ListView) findViewById(R.id.lvBusinesslist);
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
getData();
businessList.setOnScrollListener(this);
}
#Override
public Object onRetainNonConfigurationInstance() {
Object[] myStuff = new Object[2];
myStuff[0] = this.businesses;
myStuff[1] = this.imgFetcher;
return myStuff;
}
/**
* Bundle to hold refs to row items views.
*
*/
public static class MyViewHolder {
public TextView businessName, businessAddress, phoneNo;
public Button btnProfile;
public ImageView icon;
public BusinessListData business;
}
public void setBusinesses(ArrayList<BusinessListData> businesses) {
this.imgFetcher = new BusinessListIconTask(this);
this.layoutInflator = LayoutInflater.from(this);
this.businesses = businesses;
if(adapter !=null){
this.adapter.notifyDataSetChanged();
}else{
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
businessList.setAdapter(adapter);
}
}
private void getData() {
// TODO Auto-generated method stub
Intent myIntent = getIntent();
// gets the arguments from previously created intent
String metroTxt = myIntent.getStringExtra("key");
String metroLoc = myIntent.getStringExtra("loc");
String metroId = myIntent.getStringExtra("qt");
BusinessListApiTask spTask = new BusinessListApiTask(
ListResultActivity.this);
try {
spTask.execute(metroTxt, metroLoc, metroId);
} catch (Exception e) {
spTask.cancel(true);
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if (businessList.getLastVisiblePosition() == totalItemCount - 1) {
getData();
adapter.notifyDataSetChanged();
Log.d("test count", "abc"+totalItemCount);
}
}
}
Class to fetch data from server and set to adapter
public class BusinessListApiTask extends AsyncTask<String, Integer, String> {
private ProgressDialog progDialog;
private Context context;
private ListResultActivity activity;
private static final String debugTag = "sodhpuch";
HashMap<String, String> queryValues;
/**
* Construct a task
*
* #param activity
*/
public BusinessListApiTask(ListResultActivity activity) {
// TODO Auto-generated constructor stub
super();
this.activity = activity;
this.context = this.activity.getApplicationContext();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progDialog = ProgressDialog.show(this.activity, "Search", this.context
.getResources().getString(R.string.looking_for_business), true,
false);
}
#Override
protected String doInBackground(String... params) {
try {
// Log.d(debugTag, "Background:" +
// Thread.currentThread().getName());
String result = BusinessListHelper.downloadFromServer(params);
// try {
//
// updateSQLite(result);
//
// } catch (Exception e) {
// return result;
// }
Log.d("result", result);
return result;
} catch (Exception e) {
return new String();
}
}
#Override
protected void onPostExecute(String result) {
ArrayList<BusinessListData> businessData = new ArrayList<BusinessListData>();
progDialog.dismiss();
try {
JSONObject respObj = new JSONObject(result);
int success = respObj.getInt("success");
Log.d("Success", "abc"+success);
if (success == 1) {
JSONArray tracks = respObj.getJSONArray("idioms");
for (int i = 0; i < tracks.length(); i++) {
JSONObject track = tracks.getJSONObject(i);
String businessName = track.getString("name");
String businessAddress = track.getString("address");
String phone = track.getString("phone");
String id = track.getString("id");
String deals_in = track.getString("deals_in");
businessData.add(new BusinessListData(businessName,
businessAddress, id, phone, deals_in));
}
} else {
Log.d("Success", "first"+success);
// Log.d(debugTag, "Background:" + result);
// DBController controller = new DBController(context);
// businessData = controller.getBusinessList();
return ;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
this.activity.setBusinesses(businessData);
}
My Adapter
public class BusinessListDataAdapter extends BaseAdapter implements
OnClickListener {
private static final String debugTag = "BusinessListDataAdapter";
private ListResultActivity activity;
private BusinessListIconTask imgFetcher;
private LayoutInflater layoutInflater;
private ArrayList<BusinessListData> businesses;
BusinessListData business;
public BusinessListDataAdapter(ListResultActivity a,
BusinessListIconTask i, LayoutInflater l,
ArrayList<BusinessListData> data) {
this.activity = a;
this.imgFetcher = i;
this.layoutInflater = l;
this.businesses = data;
}
#Override
public int getCount() {
return this.businesses.size();
}
public void clear()
{
businesses.clear();
notifyDataSetChanged();
}
#Override
public boolean areAllItemsEnabled() {
return true;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
MyViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.trackrow, parent,
false);
holder = new MyViewHolder();
holder.businessName = (TextView) convertView
.findViewById(R.id.tvBusinessName);
holder.businessAddress = (TextView) convertView
.findViewById(R.id.tvAddress);
holder.phoneNo = (TextView) convertView.findViewById(R.id.tvPhone);
holder.icon = (ImageView) convertView.findViewById(R.id.album_icon);
holder.btnProfile = (Button) convertView
.findViewById(R.id.btnProfile);
holder.btnProfile.setTag(holder);
convertView.setTag(holder);
} else {
holder = (MyViewHolder) convertView.getTag();
}
convertView.setOnClickListener(this);
business= businesses.get(pos);
holder.business = business;
holder.businessName.setText(business.getName());
holder.businessAddress.setText(business.getAddress());
holder.phoneNo.setText(business.getPhone());
holder.btnProfile.setOnClickListener(this);
// if(track.getImageUrl() != null) {
// holder.icon.setTag(track.getImageUrl());
// Drawable dr = imgFetcher.loadImage(this, holder.icon);
// if(dr != null) {
// holder.icon.setImageDrawable(dr);
// }
// } else {
holder.icon.setImageResource(R.drawable.filler_icon);
// }
return convertView;
}
#Override
public void onClick(View v) {
String deals_in = business.getDeals().toString();
Log.d("name", deals_in);
MyViewHolder holder = (MyViewHolder) v.getTag();
if (v instanceof Button) {
Intent profile = new Intent(activity,
ProfileActivity.class);
profile.putExtra("deals_in", deals_in);
profile.putExtra("phone", holder.business.getPhone());
profile.putExtra("address", holder.business.getAddress());
profile.putExtra("name", holder.business.getName());
this.activity.startActivity(profile);
} else if (v instanceof View) {
Log.d("test","call testing");
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" +holder.business.getPhone()));
this.activity.startActivity(intent);
}
Log.d(debugTag, "OnClick pressed.");
}
}
Try this way,hope this will help you to solve your problem.
public void setBusinesses(ArrayList<BusinessListData> businesses) {
imgFetcher = new BusinessListIconTask(this);
layoutInflator = LayoutInflater.from(this);
if(this.businesses == null || adapter==null){
this.businesses = new ArrayList<BusinessListData>();
adapter= new BusinessListDataAdapter(this,imgFetcher,layoutInflator,this.businesses);
businessList.setAdapter(adapter);
}
this.businesses.addAll(businesses);
adapter.notifyDataSetChanged();
}
You have the adapter object in your setBusinesses Method. You just need to check the size of the adapter too as follows which is solve your problem.
if(adapter !=null && adapter.getCount()>0)
{
this.adapter.notifyDataSetChanged();
}
else
{
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
businessList.setAdapter(adapter);
}
this will check the size of your BusinessListData object in the adapter and this will not initialize the adapter again and again.
Hope this Solves your problem.
Thank You!
Change use of OnScrollListener. Use Asynctask class and onPreExecute() set adapter as null. Load data in doInBackground() method and call custom adapter in onPostExecute(). I hope it 'll work fine.

Categories

Resources