Hide RecyclerView until List is sorted - java

When my RecyclerView loads it shows the unsorted list for a few milliseconds and then switches to the sorted list.
Here is a video what it looks like: https://drive.google.com/file/d/14UnS54S9JNp9VPYxIOAHIiPnJjksdYOL/view
Does anyone know how i can fix this?
Thanks in advance!
This is my code:
package com.example.thecryptoapp11;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
public class Fragment_Track extends Fragment {
View view;
private EditText searchEDT;
private RecyclerView currenciesRV;
private ArrayList<TrackRVModal> currencyRVModalArrayList;
private TrackRVAdapter currencyRVAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_track, container, false);
searchEDT = (EditText) view.findViewById(R.id.idEdtSearch);
currenciesRV = (RecyclerView) view.findViewById(R.id.idRVCurrencies);
RecyclerView.LayoutManager recyce = new LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false);
currenciesRV.setLayoutManager(recyce);
currencyRVModalArrayList = new ArrayList<>();
currencyRVAdapter = new TrackRVAdapter(currencyRVModalArrayList, requireContext());
currenciesRV.setAdapter(currencyRVAdapter);
getCurrencyDataPage();
searchEDT.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
filterCurrencies(editable.toString());
}
});
return view;
}
private void filterCurrencies(String currency) {
ArrayList<TrackRVModal> filteredList = new ArrayList<>();
for (TrackRVModal item : currencyRVModalArrayList) {
if (item.getName().toLowerCase().contains(currency.toLowerCase())) {
filteredList.add(item);
}
}
if (filteredList.isEmpty()) {
//Toast.makeText(requireContext(), "No Currency found...", Toast.LENGTH_SHORT).show();
} else {
currencyRVAdapter.filterList(filteredList);
}
}
private void getCurrencyDataPage() {
for(int i=1; i<=3; i++) {
String url = "https://api.coingecko.com/api/v3/coins/markets?vs_currency=eur&order=market_cap_desc&per_page=250&page="+i+"&sparkline=false";
RequestQueue requestQueue = Volley.newRequestQueue(requireContext());
int finalI = i;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
// Get current json object
JSONObject currency = response.getJSONObject(i);
String name = currency.getString("name");
String symbol = currency.getString("symbol").toUpperCase();
String image_url = currency.getString("image");
int ID = currency.getInt("market_cap_rank");
double price = currency.getDouble("current_price");
currencyRVModalArrayList.add(new TrackRVModal(name, symbol, price, ID, image_url));
}
Collections.sort(currencyRVModalArrayList, TrackRVModal.TrackRVModalIDComparator);
currencyRVAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(requireContext(), "Error", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonArrayRequest);
}
}
}
The Comparator:
public static Comparator<TrackRVModal> TrackRVModalIDComparator = new Comparator<TrackRVModal>() {
#Override
public int compare(TrackRVModal currency1, TrackRVModal currency2) {
return currency1.getID() - currency2.getID();
}
};

Related

Calculation using JSON Data in RecyclerView and ToggleButton

I want to do calculation using JSON Data in RecyclerView with ToggleButton. When the toggle button is checked the value should change and when its not checked the value should change again for that particular RecyclerView row. The problem is when I click the ToggleButton, 2 other RecyclerView row's ToggleButton is also checked.
CODE:
Activity
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.gridlayout.widget.GridLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class GstPlanner extends AppCompatActivity implements GstPlanAdapter.GstPlanListener{
private static final String TAG = GstPlanner.class.getSimpleName();
List<String> dateNames = new ArrayList<String>();
private List<GstPlanList> GSTLisT;
private GstPlanAdapter mAdapter;
Context context;
Spinner ret_pending_drop, state_drop, nil_drop;
String URL, URL1;
ProgressBar progress_gst, Progress_Gst_Plan;
GridLayout grid_gst;
TextView txt_retry_gst, txt_state_gst, txt_ret_type, txt_final_gst;
Button btn_retry_gst, btn_submit_state, btn_submit;
String State_GET;
RecyclerView recyclerView1;
RelativeLayout Gst_Plan_Relative;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gst_planner);
Gst_Plan_Relative = findViewById(R.id.Gst_Plan_Relative);
recyclerView1 = findViewById(R.id.Recycler_Gst_Plan);
Progress_Gst_Plan = findViewById(R.id.Progress_Gst_Plan);
btn_submit_state = findViewById(R.id.btn_submit_state);
txt_state_gst = findViewById(R.id.txt_state_gst);
txt_ret_type = findViewById(R.id.txt_ret_type);
txt_retry_gst = findViewById(R.id.txt_retry_gst);
btn_retry_gst = findViewById(R.id.btn_retry_gst);
ret_pending_drop = findViewById(R.id.ret_pending_drop);
txt_final_gst = findViewById(R.id.txt_final_gst);
state_drop = findViewById(R.id.state_drop);
btn_submit = findViewById(R.id.btn_submit);
nil_drop = findViewById(R.id.nil_drop);
grid_gst = findViewById(R.id.grid_gst);
progress_gst = findViewById(R.id.progress_gst);
GSTLisT = new ArrayList<>();
mAdapter = new GstPlanAdapter(this, GSTLisT, this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView1.setLayoutManager(mLayoutManager);
recyclerView1.setItemAnimator(new DefaultItemAnimator());
recyclerView1.addItemDecoration(new MyDividerItemDecoration(this, DividerItemDecoration.VERTICAL, 36));
recyclerView1.setAdapter(mAdapter);
btn_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
URL1 = "http://url.com/something.php?state="+state_drop.getSelectedItem().toString()+"&RType="+txt_ret_type.getText().toString()+"&NIL="+nil_drop.getSelectedItem().toString()+"&Month="+ret_pending_drop.getSelectedItem().toString();
Log.e("URL1",URL1);
Progress_Gst_Plan.setVisibility(View.VISIBLE);
fetchData();
GlobalValue.getit = true;
}
});
btn_submit_state.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
URL = "http://url.com/something.php?state="+state_drop.getSelectedItem().toString();
State_GET = state_drop.getSelectedItem().toString();
btn_submit_state.setVisibility(View.INVISIBLE);
state_drop.setVisibility(View.INVISIBLE);
progress_gst.setVisibility(View.VISIBLE);
fetchMonths();
}
});
btn_retry_gst.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progress_gst.setVisibility(View.INVISIBLE);
txt_retry_gst.setVisibility(View.GONE);
btn_retry_gst.setVisibility(View.GONE);
btn_submit_state.setVisibility(View.VISIBLE);
state_drop.setVisibility(View.VISIBLE);
}
});
}
private void fetchData() {
JsonArrayRequest request = new JsonArrayRequest(URL1,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response == null) {
Toast.makeText(getApplicationContext(), "Couldn't fetch the Details! Please try again.", Toast.LENGTH_LONG).show();
return;
}
Gst_Plan_Relative.setVisibility(View.VISIBLE);
Progress_Gst_Plan.setVisibility(View.INVISIBLE);
List<GstPlanList> items = new Gson().fromJson(response.toString(), new TypeToken<List<GstPlanList>>() {
}.getType());
// adding contacts to contacts list
GSTLisT.clear();
GSTLisT.addAll(items);
// refreshing recycler view
mAdapter.notifyDataSetChanged();
Progress_Gst_Plan.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error in getting json
Log.e(TAG, "Error: " + error.getMessage() +error.getCause());
AlertDialog("Error...Please try after some time.");
progress_gst.setVisibility(View.INVISIBLE);
txt_retry_gst.setVisibility(View.VISIBLE);
btn_retry_gst.setVisibility(View.VISIBLE);
btn_submit.setVisibility(View.INVISIBLE);
Gst_Plan_Relative.setVisibility(View.INVISIBLE);
}
});
APP.getInstance().addToRequestQueue(request);
}
private void fetchMonths() {
StringRequest stringRequest = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject object = jsonArray.getJSONObject(0);
JSONArray arrayContacts = object.getJSONArray("Status");
for (int i = 0; i<arrayContacts.length(); i++) {
JSONObject contactObject = arrayContacts.getJSONObject(i);
dateNames.add(contactObject.getString("Month"));
}
spinnervalue(dateNames, ret_pending_drop);
txt_state_gst.setText(State_GET);
progress_gst.setVisibility(View.INVISIBLE);
grid_gst.setVisibility(View.VISIBLE);
txt_retry_gst.setVisibility(View.GONE);
btn_retry_gst.setVisibility(View.GONE);
btn_submit.setVisibility(View.VISIBLE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog("Error...Please try after some time.");
progress_gst.setVisibility(View.INVISIBLE);
txt_retry_gst.setVisibility(View.VISIBLE);
btn_retry_gst.setVisibility(View.VISIBLE);
btn_submit.setVisibility(View.INVISIBLE);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
public void spinnervalue(List<String> value, Spinner spinner1){
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, value);
dataAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
}
public void AlertDialog(String s) {
try{
AlertDialog.Builder builder1 = new AlertDialog.Builder(GstPlanner.this);
builder1.setMessage(s);
builder1.setCancelable(true);
builder1.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}catch (
WindowManager.BadTokenException ex){
ex.printStackTrace();
}
}
#Override
public void onSubTotalUpdate(int total){
txt_final_gst.setText(String.valueOf(total));
}
RecyclerView Adapter
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GstPlanAdapter extends RecyclerView.Adapter<GstPlanAdapter.MyViewHolder>
implements Filterable {
private Context context;
private List<GstPlanList> GstPlanList;
private List<GstPlanList> GstPlanListFiltered;
private GstPlanListener listener;
int totalPrice;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView ret_month, due_date, penalty_amt;
Spinner nil_ret;
ToggleButton toggleSwitch;
public MyViewHolder(View view) {
super(view);
ret_month = view.findViewById(R.id.ret_month);
due_date = view.findViewById(R.id.due_date);
penalty_amt = view.findViewById(R.id.penalty_amt);
toggleSwitch = view.findViewById(R.id.switch_gst);
}
}
public GstPlanAdapter(Context context, List<GstPlanList> BiLLList, GstPlanListener listener ) {
this.context = context;
this.listener = listener;
this.GstPlanList = BiLLList;
this.GstPlanListFiltered = BiLLList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent1, int viewType1) {
View itemView = LayoutInflater.from(parent1.getContext())
.inflate(R.layout.gst_plan_view_item_row, parent1, false);
return new MyViewHolder(itemView);
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, final int position) {
final GstPlanList bill = GstPlanListFiltered.get(position);
holder.nil_ret.setAdapter(categoriesAdapter);
holder.ret_month.setText(bill.getMonth());
holder.due_date.setText(bill.getDate());
holder.penalty_amt.setText(bill.getPenatly().toString());
totalPrice = 0;
for (int i = 0; i < GstPlanList.size(); i++) {
totalPrice += GstPlanList.get(i).getPenatly();
countTotal(totalPrice);
}
if (GlobalValue.getit == true) {
if (bill.getNIL().equals("YES")) {
holder.toggleSwitch.setChecked(true);
GlobalValue.getit = false;
} else {
holder.toggleSwitch.setChecked(false);
GlobalValue.getit = false;
}
}
holder.toggleSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.toggleSwitch.isChecked()) {
int AC = bill.getTODATE();
int BC = Integer.parseInt(bill.getNILNO().toString());
int ABC = AC * BC;
totalPrice = totalPrice - ABC;
int A = bill.getTODATE();
int B = Integer.parseInt(bill.getNILYES().toString());
int AB = A * B;
if (AB >= 10000) {
holder.penalty_amt.setText("10000");
totalPrice = totalPrice + 10000;
countTotal(totalPrice);
} else {
holder.penalty_amt.setText(String.valueOf(AB));
totalPrice = totalPrice + AB;
countTotal(totalPrice);
}
}
if (!holder.toggleSwitch.isChecked()) {
int AC = bill.getTODATE();
int BC = Integer.parseInt(bill.getNILYES().toString());
int ABC = AC * BC;
totalPrice = totalPrice - ABC;
int A = bill.getTODATE();
int B = Integer.parseInt(bill.getNILNO().toString());
int AB = A * B;
if (AB >= 10000) {
holder.penalty_amt.setText("10000");
totalPrice = totalPrice + 10000;
countTotal(totalPrice);
} else {
holder.penalty_amt.setText(String.valueOf(AB));
totalPrice = totalPrice + AB;
countTotal(totalPrice);
}
}
}
});
}
public void countTotal(int total){
listener.onSubTotalUpdate(total);
}
#Override
public int getItemCount() {
return GstPlanListFiltered.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
GstPlanListFiltered = GstPlanList;
} else {
List<GstPlanList> filteredList = new ArrayList<>();
for (GstPlanList row : GstPlanList) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getDate().toLowerCase().contains(charString.toLowerCase()) || row.getMonth().toLowerCase().contains(charString.toLowerCase()) || row.getRType().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(row);
}
}
GstPlanListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = GstPlanListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
GstPlanListFiltered = (ArrayList<GstPlanList>) filterResults.values;
notifyDataSetChanged();
}
};
}
public interface GstPlanListener {
// void onGstPlanSelected(GstPlanList bill);
void onSubTotalUpdate(int total);
}
}
GstPlanList
public class GstPlanList {
private String RType;
private String State;
private String NILNO;
private String NILYES;
private String Month;
private String Date;
private String NIL;
private int Penatly;
private int TODATE;
public GstPlanList() {
}
public Integer getPenatly() {
return Penatly;
}
public int getTODATE() {
return TODATE;
}
public String getNIL() {
return NIL;
}
public String getRType() {
return RType;
}
public String getState() {
return State;
}
public String getNILNO() {
return NILNO;
}
public String getNILYES() {
return NILYES;
}
public String getMonth() {
return Month;
}
public String getDate() {
return Date;
}
}

E/RecyclerView: No adapter attached; skipping layout (Help needed) [duplicate]

This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
Closed 2 years ago.
i'm building an application that connects to my Drupal API. Somehow i'm not getting any data display within my application. I don't see any errors in the code and the debugging online gives the follow error: E/RecyclerView: No adapter attached; skipping layout
Here is my MainActivity code:
package com.example.eindopdrachtcmsapi;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.LinkedList;
public class MainActivity extends AppCompatActivity implements ExampleAdapter.onItemClickListener {
public static final String EXTRA_TITLE = "title";
public static final String EXTRA_BODY = "body";
public static final String EXTRA_LINK = "link";
private RecyclerView mRecyclerView;
private ExampleAdapter mExampleAdapter;
private ArrayList<ExampleItem> mExampleList;
private RequestQueue mRequestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
String url = "http://vistudio.be/api/portfolio";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject portfolio = response.getJSONObject(i);
String title = portfolio.getString("title");
String body = portfolio.getString("body");
String link = portfolio.getString("field_website_url");
mExampleList.add(new ExampleItem(title, body, link));
}
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleAdapter.setOnClickListener(MainActivity.this, new ExampleAdapter.onItemClickListener() {
#Override
public void onItemClick(int position) {
ExampleItem clickedItem = mExampleList.get(position);
String title = clickedItem.getTitle();
String Link = clickedItem.getLink();
Intent mSharingIntent = new Intent(Intent.ACTION_SEND);
mSharingIntent.setType("text/plain");
mSharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Vistudio");
mSharingIntent.putExtra(Intent.EXTRA_TEXT, title + " - "+ Link);
startActivity(Intent.createChooser(mSharingIntent, "Share"));
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(this, DetailActivity.class);
ExampleItem clickedItem = mExampleList.get(position);
detailIntent.putExtra(EXTRA_TITLE, clickedItem.getTitle());
detailIntent.putExtra(EXTRA_BODY, clickedItem.getBody());
detailIntent.putExtra(EXTRA_LINK, clickedItem.getLink());
mExampleAdapter.setOnClickListener(MainActivity.this, new ExampleAdapter.onItemClickListener() {
#Override
public void onItemClick(int position) {
ExampleItem clickedItem = mExampleList.get(position);
String title = clickedItem.getTitle();
String Link = clickedItem.getLink();
Intent mSharingIntent = new Intent(Intent.ACTION_SEND);
mSharingIntent.setType("text/plain");
mSharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Vistudio");
mSharingIntent.putExtra(Intent.EXTRA_TEXT, title + " - "+ Link);
startActivity(Intent.createChooser(mSharingIntent, "Share"));
}
});
startActivity(detailIntent);
}
}
My Adapter code:
package com.example.eindopdrachtcmsapi;
import android.content.Context;
import android.graphics.PorterDuffColorFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.portfolioViewHolder>{
private Context mContext;
private ArrayList<ExampleItem> mExampleList;
private onItemClickListener mListener;
private onItemClickListener mListenerShare;
public interface onItemClickListener{
void onItemClick(int position);
}
public void setOnClickListener(onItemClickListener listener, onItemClickListener listenerShare){
mListener = listener;
mListenerShare = listenerShare;
}
public ExampleAdapter(Context context, ArrayList<ExampleItem> ExampleList) {
mContext = context;
mExampleList = ExampleList;
}
#Override
public portfolioViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.exampleitem, parent, false);
return new portfolioViewHolder(v);
}
#Override
public void onBindViewHolder(portfolioViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
String title = currentItem.getTitle();
String body = currentItem.getBody();
String link = currentItem.getLink();
holder.mTextViewTitle.setText(title);
holder.mTextViewBody.setText(body);
holder.mTextViewLink.setText(link);
}
#Override
public int getItemCount() {
return mExampleList.size();
}
public class portfolioViewHolder extends RecyclerView.ViewHolder{
public TextView mTextViewTitle;
public TextView mTextViewBody;
public TextView mTextViewLink;
public Button mButton;
public portfolioViewHolder(View itemView) {
super(itemView);
mTextViewTitle = itemView.findViewById(R.id.text_view_title);
mTextViewBody = itemView.findViewById(R.id.text_view_body);
mTextViewLink = itemView.findViewById(R.id.text_view_link);
mButton = itemView.findViewById(R.id.share);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListenerShare != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListenerShare.onItemClick(position);
}
}
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
});
}
}
}
first remove inside oncreate()
mRecyclerView.setAdapter(mExampleAdapter);
after this code
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
add this:-
mExampleAdapter.notifyDataSetChanged();

Unable to refresh the updated data after clicking on search button (Fetching data via API)

I am not able to update the values when i click on the search button, The data is fetched but the old fetched data is not getting discards, the fetched data is overlapping over each other
SearchFragment.java
package com.example.recipeappandroid.Fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.recipeappandroid.Adapter.RecipeAdapter;
import com.example.recipeappandroid.Model.Recipe;
import com.example.recipeappandroid.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class SearchFragment extends Fragment {
Button click;
//public static TextView fetchedText;
ImageView searching_logo;
TextView searching_text;
SearchView searchbar;
String query="";
RecyclerView recyclerView;
public static ArrayList<Recipe> recipeList;
public static RecipeAdapter recipeAdapter;
private RequestQueue mRequestQueue;
private String Api_id= "3f335994";
private String Api_key = "8e99e327d1f2130dc6ab3422e26a95e8";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
click = (Button) view.findViewById(R.id.button1);
//fetchedText = (TextView) view.findViewById(R.id.fetcheddata);
searchbar = (SearchView) view.findViewById(R.id.searchbar);
searching_logo = view.findViewById(R.id.searching_logo);
searching_text = view.findViewById(R.id.searching_text);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
//recipeAdapter = new RecipeAdapter();
recipeList = new ArrayList<>();
//getData();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
query = searchbar.getQuery().toString();
String url = "https://api.edamam.com/search?q=" + query + "&app_id=" + Api_id + "&app_key=" + Api_key;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray hits = response.getJSONArray("hits");
for (int i =0;i<hits.length();i++) {
JSONObject jsonObject = hits.getJSONObject(i);
JSONObject recipe = jsonObject.getJSONObject("recipe");
String recipe_img = recipe.getString("image");
String recipe_title = recipe.getString("label");
String recipe_data = recipe.getString("source");
recipeList.add(new Recipe(recipe_img,recipe_title,recipe_data));
}
recipeAdapter = new RecipeAdapter(getContext(),recipeList);
recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue = Volley.newRequestQueue(getContext());
mRequestQueue.add(jsonObjectRequest);
/*JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
JSONObject recipes = jsonObject.getJSONObject("recipe");
//Recipe recipe = new Recipe();
String recipe_img = recipes.getString("image");
String recipe_title = recipes.getString("label");
String recipe_data = recipes.getString("source");
recipeList.add(new Recipe(recipe_img,recipe_title,recipe_data));
Log.d("data",recipe_title);
}
//recipeAdapter = new RecipeAdapter(getContext(), recipeList);
//recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(SearchFragment.this,"Error Occured",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});*/
/*jsonArrayRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 3000;
}
#Override
public int getCurrentRetryCount() {
return 3000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});*/
/* Log.d("QUEEEERRRYYYY",query);
ApiCall process = new ApiCall(searching_logo,searching_text);
process.execute(query);*/
}
});
return view;
}
}
I want to get rid of the old data after the new data is fetched and don't want to display it after the new one is called
looks like you are only adding items to your ArrayList<Recipe> recipeList;, so they may duplicate
maybe try to recipeList.clear(); it in first line of onResponse method
also notifyDataSetChanged isn't needed, setAdapter does it itself (and a lot more in fact)

ItemClickListener not working in Fragment RecyclerView with onclick

I've been following this tutorial: Tutorial
To make a json recyclerviewer with onclick, but i wanted to use Fragments instead of activities.
I've figured everything out until the point of the onClick.
My problem is the setOnItemClickListener is not taking my getActivity()
I've tried so much, but i just cant see the bright light.
If anyone could help me out that would be totally awesome!
Me only real problem is that the getActivity is giving a red line in the:
fNieuwsAdapter.setOnItemClickListener(getActivity());
NieuwsFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import java.util.ArrayList;
public class NieuwsFragment extends Fragment implements NieuwsAdapter.OnItemClickListener {
public static final String EXTRA_URL = "nieuwsImageUrl";
public static final String EXTRA_HEADING = "nieuwsHeading";
public static final String EXTRA_CONTENT = "nieuwsContent";
private RecyclerView fNieuwsRecyclerView;
private NieuwsAdapter fNieuwsAdapter;
private ArrayList<NieuwsItem> fNieuwsList;
private RequestQueue fNieuwsQueue;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_nieuws, container, false);
fNieuwsRecyclerView = view.findViewById(R.id.recycler_view);
fNieuwsRecyclerView.setHasFixedSize(true);
fNieuwsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
fNieuwsList = new ArrayList<>();
fNieuwsQueue = Volley.newRequestQueue(getActivity());
parseJSON();
return view;
}
private void parseJSON() {
String url = "urlissecretsorry<3butthejsonparsingworks";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
public String nieuwsImageUrl;
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("posts");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
JSONArray attachArray = hit.getJSONArray("attachments");
for (int a = 0; a < attachArray.length(); a++) {
JSONObject attach = attachArray.getJSONObject(a);
nieuwsImageUrl = attach.getString("url");
}
String nieuwsHeading = hit.getString("title");
String nieuwsExcerpt = hit.getString("excerpt");
String nieuwsContent = hit.getString("content");
nieuwsExcerpt = html2text(nieuwsExcerpt);
fNieuwsList.add(new NieuwsItem(nieuwsImageUrl, nieuwsHeading, nieuwsExcerpt,nieuwsContent));
}
fNieuwsAdapter = new NieuwsAdapter(getActivity(), fNieuwsList);
fNieuwsAdapter.setOnItemClickListener(getActivity());
fNieuwsRecyclerView.setAdapter(fNieuwsAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
fNieuwsQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(getActivity(), DetailActivity.class);
NieuwsItem clickedItem = fNieuwsList.get(position);
detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
detailIntent.putExtra(EXTRA_HEADING, clickedItem.getHeading());
detailIntent.putExtra(EXTRA_CONTENT, clickedItem.getContent());
startActivity(detailIntent);
}
public String html2text(String html) {
try {
return Jsoup.parse(html).text();
} catch (Exception ignored) {
return "";
}
}
}
NieuwsItem.java
public class NieuwsItem {
private String nieuwsImageUrl;
private String nieuwsHeading;
private String nieuwsExcerpt;
private String nieuwsContent;
public NieuwsItem(String imageUrl, String heading, String excerpt, String content){
nieuwsImageUrl = imageUrl;
nieuwsHeading = heading;
nieuwsExcerpt = excerpt;
nieuwsContent = content;
}
public String getImageUrl(){
return nieuwsImageUrl;
}
public String getHeading(){
return nieuwsHeading;
}
public String getExcerpt(){
return nieuwsExcerpt;
}
public String getContent(){
return nieuwsContent;
}
}
NieuwsAdapter.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class NieuwsAdapter extends RecyclerView.Adapter<NieuwsAdapter.NieuwsViewHolder> {
private Context NieuwsContext;
private ArrayList<NieuwsItem> NieuwsList;
private OnItemClickListener NieuwsListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
NieuwsListener = listener;
}
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist) {
NieuwsContext = context;
NieuwsList = nieuwslist;
}
#NonNull
#Override
public NieuwsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(NieuwsContext).inflate(R.layout.nieuws_item, parent, false);
return new NieuwsViewHolder(v);
}
#Override
public void onBindViewHolder(NieuwsViewHolder holder, int position) {
NieuwsItem currentitem = NieuwsList.get(position);
String ImageUrl = currentitem.getImageUrl();
String Heading = currentitem.getHeading();
String Excerpt = currentitem.getExcerpt();
holder.NieuwsTextViewHeading.setText(Heading);
holder.NieuwsTextViewExcerpt.setText(Excerpt);
Picasso.get().load(ImageUrl).fit().centerInside().into(holder.NieuwsImageView);
}
#Override
public int getItemCount() {
return NieuwsList.size();
}
public class NieuwsViewHolder extends RecyclerView.ViewHolder {
public ImageView NieuwsImageView;
public TextView NieuwsTextViewHeading;
public TextView NieuwsTextViewExcerpt;
public NieuwsViewHolder(#NonNull View itemView) {
super(itemView);
NieuwsImageView = itemView.findViewById(R.id.nieuws_image);
NieuwsTextViewHeading = itemView.findViewById(R.id.nieuws_heading);
NieuwsTextViewExcerpt = itemView.findViewById(R.id.nieuws_excerpt);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (NieuwsListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
NieuwsListener.onItemClick(position);
}
}
}
});
}
}
}
DetailActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent intent = getIntent();
String imageUrl = intent.getStringExtra("EXTRA_URL");
String creatorName = intent.getStringExtra("EXTRA_HEADING");
String likeCount = intent.getStringExtra("EXTRA_CONTENT");
ImageView imageView = findViewById(R.id.nieuws_detail_image);
TextView textViewHeading = findViewById(R.id.nieuws_detail_heading);
TextView textViewContent = findViewById(R.id.nieuws_detail_content);
Picasso.get().load(imageUrl).fit().centerInside().into(imageView);
textViewHeading.setText(creatorName);
textViewContent.setText("Likes: " + likeCount);
}
}
You cant use NieuwsAdapter.setOnItemClickListener(getActivity()); , unless your activity implements OnItemClickListener interface, but im seeing that your fragment implements OnItemClickListener, so you can use the fragment instead like this :
fNieuwsAdapter.setOnItemClickListener(NieuwsFragment.this);
And by the way, you are sending the data via intent with :
detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
detailIntent.putExtra(EXTRA_HEADING, clickedItem.getHeading());
detailIntent.putExtra(EXTRA_CONTENT, clickedItem.getContent());
You have to get them with the same parameters (remove the ""):
String imageUrl = intent.getStringExtra(EXTRA_URL);
String creatorName = intent.getStringExtra(EXTRA_HEADING);
String likeCount = intent.getStringExtra(EXTRA_CONTENT);
Hope this helps
change
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist) {
NieuwsContext = context;
NieuwsList = nieuwslist;
}
to
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist, OnItemClickListener mOnClickListener) {
this.NieuwsContext = context;
this.NieuwsList = nieuwslist;
this.NieuwsListener = mOnClickListener;
}
and this
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (NieuwsListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
NieuwsListener.onItemClick(position);
}
}
}
});
change to
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NieuwsListener.onItemClick(int position);
}
});
and then in fragment You can do it like this
fNieuwsAdapter = new NieuwsAdapter(getActivity(), fNieuwsList,new NieuwsAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position)
{
//DoSomethingHere
}
});

BaseAdapter crashes on notifyDataSetChanged update?

When trying to update my array adapter upon a network request, the program crashes with Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference, I have seen other posts with the same time but every method I try seems to just result in an error, the same crashing bug most likely.
Of course the title says, I am using notifyDataSetChanged() to update my lists.
Here is my code that I am using
import android.app.DownloadManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MyActivity";
public ArrayList<String> aContacts = new ArrayList<String>();
public ListView contacts;
public CustomAdapter customAdapter;
// User Setup Defaults
String server = "https://xxxxxxxx";
String suser = "xxxxxx";
String spass = "xxxxxx";
String sreq;
public void getContacts() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url = server+"/xxxxxx/?username="+suser+"&password="+spass+"&getcontacts=yes";
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Log.v(TAG, "I recieved: " + response);
try {
JSONArray parseContacts = new JSONArray(response);
for (int x = 0; x < parseContacts.length(); x++) {
JSONArray array = (JSONArray) parseContacts.get(x);
for (int j = 0; j < array.length(); j++){
// print: array.get(j).toString();
}
aContacts.add(array.get(0).toString());
customAdapter.notifyDataSetChanged(); // ERROR IS HERE
}
}catch(JSONException e) {
Log.v(TAG, "Error: "+e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v(TAG, "Oops, an error occurred");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView contacts = (ListView)findViewById(R.id.contacts);
getContacts();
CustomAdapter customAdapter = new CustomAdapter();
contacts.setAdapter(customAdapter);
contacts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object o = contacts.getItemAtPosition(position);
Toast.makeText(getBaseContext(),aContacts.get(position),Toast.LENGTH_SHORT).show();
}
});
}
class CustomAdapter extends BaseAdapter {
#Override
public int getCount() {
return aContacts.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.row,null);
TextView username = (TextView) convertView.findViewById(R.id.username);
username.setText(aContacts.get(position));
return convertView;
}
}
}
Im trying to parse JSON data and that works fine, and I add the results to an array and it would appear something like this {"one", "two", "three"}, but it doesnt seem to have to do with that and just crashes with that error on runtime. I have struggled at this forever now, if someone could give me some code that is the working version would be really nice but probably wouldnt happen, so just reference the issue please, or whatever you can do to help, thanks!

Categories