Hi everyone My problem is weird. I have an app that works with volley and mysql. When I launch the app using xampp it works fine. The list is saved in the adapter and adapter works well in the recycler view. But when I change the url to my mysql database hosted on my website, the recycler view does not show the data. The JSON data is correctly received and saved correctly in the Arraylist (check it with Toast messages). I have the same problem in real devices
Android Studio will not throw me any error or warning running
Rubros
public class Rubros {
String nombre;
String rubro_id;
public Rubros(String nombre, String rubro_id) {
this.nombre = nombre;
this.rubro_id = rubro_id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getRubro_id() {
return rubro_id;
}
public void setRubro_id(String rubro_id) {
this.rubro_id = rubro_id;
}
}
ListaRubros.class
public class ListaRubros extends AppCompatActivity {
RecyclerView rv_rubros;
RubroAdapter adapter;
List <Rubros> listarubros;
String categoria;
String categoria_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_rubros);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Buscamos la categoria
Bundle bundle = getIntent().getExtras();
categoria = bundle.getString("categoria");
setTitle(categoria);
categoria_id = bundle.getString("categoria_id");
//Declaramos variable textview
listarubros= new ArrayList<>();
//cargamos la lista de rubros
rv_rubros = (RecyclerView) findViewById(R.id.rv_rubros);
//Preparamos el adapter
rv_rubros.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv_rubros.setLayoutManager(llm);
//guardamos la lista en adapter
cargarRubros(categoria_id);
adapter = new RubroAdapter(listarubros);
rv_rubros.setAdapter(adapter);
//agregamos el onClick Listener
adapter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String rubro=listarubros.get(rv_rubros.getChildAdapterPosition(view)).getNombre();
String rubro_id=listarubros.get(rv_rubros.getChildAdapterPosition(view)).getRubro_id();
Intent intent = new Intent(ListaRubros.this,ListaNegocios.class);
intent.putExtra("rubro",rubro);
intent.putExtra("rubro_id",rubro_id);
startActivity(intent);
}
});
}
public void cargarRubros(String categoria){
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://10.0.3.2/listin/plantilla/sql/vistarubros_categoria_id.php?cc="+categoria; //Creamos la url
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
response = response.replace("][",",");
if (response.length()>0){
try {
JSONArray ja = new JSONArray(response);
for(int i=0;i<ja.length();i+=2){
try {
Rubros rubro = new Rubros(ja.getString(i),ja.getString(i+1));
listarubros.add(rubro);
Toast.makeText(getApplicationContext(),listarubros.get(0).getNombre(), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(stringRequest);
}
}
RubrosAdapter
public class RubroAdapter extends RecyclerView.Adapter<RubroAdapter.DatosRubroViewHolder>
implements View.OnClickListener{
List<Rubros> listarubros;
private View.OnClickListener listener;
public RubroAdapter(List<Rubros> listarubros) {
this.listarubros = listarubros;
}
#NonNull
#Override
public RubroAdapter.DatosRubroViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.vista_rv_rubros,parent,false);
v.setOnClickListener(this);
DatosRubroViewHolder holder = new DatosRubroViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(#NonNull RubroAdapter.DatosRubroViewHolder holder, int position) {
holder.rubro.setText(listarubros.get(position).getNombre());
holder.rubro_id.setText(listarubros.get(position).getRubro_id());
}
#Override
public int getItemCount() {
return listarubros.size();
}
public void setOnClickListener(View.OnClickListener listener){
this.listener=listener;
}
#Override
public void onClick(View view) {
if(listener!=null){
listener.onClick(view);
}
}
public static class DatosRubroViewHolder extends RecyclerView.ViewHolder{
TextView rubro;
TextView rubro_id;
public DatosRubroViewHolder(View itemView){
super(itemView);
rubro = (TextView) itemView.findViewById(R.id.tv_rubro);
rubro_id = (TextView) itemView.findViewById(R.id.tv_rubro_id);
}
}
}
EDIT
I already solved the problem. I had forgotten to add adapter.notifyDataSetChanged (); after saving the data in the arraylist
Related
I have set up recyclerview for same Api data on two fragments.After clicking on one of Card, a new Detail fragment for same Card is open on Another Fragment.The cardview contain images.After clicking one of image I need to get information of that CardView position.But as I click on one of card in First Fragment and I move to same card position in Second Fragment but I swipe to other cards and click on Image of other CardView still I am getting information for same Card which was clicked first.
This is code for Adapter
class public class StatusInfoAdapter extends RecyclerView.Adapter<StatusInfoAdapter.ViewHolder> {
private FragmentManager fm;
private FragmentTransaction tx;
private ArrayList<StatusEntry> entries;
private int finalPos,tempPos;
Context context;
String People, id,Id;
SnackBarAlert alertMsg=new SnackBarAlert();
private String myToken;
public StatusInfoAdapter(ArrayList<StatusEntry> entries, Context context) {
this.entries = entries;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.status_info_card, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder,int position) {
StatusEntry entry = entries.get(position);
tempPos = holder.getAdapterPosition();
finalPos = tempPos + 1;
holder.id.setText(entry.getid());
holder.Idno.setText(entry.getidno());
holder.fname.setText(entry.getFname());
holder.lname.setText(entry.getLname());
holder.people.setText(entry.getPeople());
noOfPeople = entries.get(position).getPeople();
fid = entries.get(position).getFyraid();
Id = entries.get(position).getid();
}
#Override
public int getItemCount() {
return entries.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView fname;
public TextView lname;
public TextView people;
public TextView d;
TextView Idno;
ImageView cancelEntry;
public ViewHolder(View v) {
super(v);
SharedPreferences preferences=context.getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
fname = (TextView) v.findViewById(R.id.fname);
lname = (TextView) v.findViewById(R.id.lname);
people = (TextView) v.findViewById(R.id.adults);
fyra_id = (TextView) v.findViewById(R.id.fyraid);
Idno = (TextView) v.findViewById(R.id.Id);
cancelEntry = (ImageView) v.findViewById(R.id.cancel);
cancelEntry.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
final AppCompatActivity activity = (AppCompatActivity) v.getContext();
final Dialog dialog=new Dialog(activity);
dialog.setContentView(R.layout.cancel_reason);
dialog.show();
Button yes = (Button) dialog.findViewById(R.id.yes);
Button no = (Button) dialog.findViewById(R.id.no);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
removeFromQueue();
alertMsg.infoMessage(v,"Removed from List");
entries.remove(tempPos);
notifyItemRemoved(tempPos);
ChooseTab chooseTab1=new ChooseTab();
fm=activity.getSupportFragmentManager();
CurrentStatus currentStatus=new CurrentStatus();
tx=fm.beginTransaction();
tx.detach(currentStatus);
tx.attach(currentStatus);
tx.replace(R.id.frame,chooseTab1);
tx.commit();
}
});
}
});
}
}
This is code for setting RecyclerView
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 object=response.getJSONObject(i);
final StatusEntry entry=new StatusEntry();
String id=object.getString("fid");
Idno=object.getString("idno");
JsonObjectRequest(Request.Method.GET,url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String first_name=response.getString("firstname");
String last_name=response.getString("lastname");
String id=response.getString("id");
entry.setFname(first_name);
entry.setLname(last_name);
entry.setid(id);
entry.setidNo(Idno);
adapter.notifyDataSetChanged();
progressDialog.hide();
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
};
AppController.getInstance().addToRequestQueue(foodie_request,foodie_data);
String no_of_people=object.getString("no_people");
entry.setPeople(no_of_people);
progressDialog.dismiss();
entries.add(entry);
adapter = new StatusInfoAdapter(entries, getActivity().getApplicationContext());
recyclerView.setAdapter(adapter);
}
}catch(JSONException e)
{
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
};
AppController.getInstance().addToRequestQueue(request,foo_request);
}
I am getting the same Idno for all CardView after swiping to other cards.How to resolve this ?
pass the model of list in the constructor of the fragment at time of begin transaction and receive it by creating same model in another fragment from constructor
I'm traying to get data from my mysql database and display them in a list view but the probleme is that the list view show only one attribut and for the others i have an error:RecyclerView: No adapter attached; skipping layout
this is my adapter :
public class DerpAdapter extends RecyclerView.Adapter<DerpAdapter.DerpHolder>{
private List<ListItem> ListData;
private LayoutInflater inflater;
private ItemClickCallback itemClickCallback;
public interface ItemClickCallback{
void onItemClick(int p);
void onSecondaryIconClick(int p);
}
public void setItemClickCallback(final ItemClickCallback itemClickCallback){
this.itemClickCallback = itemClickCallback;
}
public DerpAdapter(List<ListItem> listData, Context c){
this.inflater = LayoutInflater.from(c);
this.ListData = listData;
}
#Override
public DerpHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row,parent,false);
return new DerpHolder(view);
}
#Override
public void onBindViewHolder(DerpHolder holder, int position) {
ListItem item = ListData.get(position);
holder.title.setText(item.getTitle());
holder.subtitle.setText(item.getSubtitle());
holder.gaga.setText(item.getGaga());
}
#Override
public int getItemCount() {
return ListData.size();
}
class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView title;
private TextView subtitle;
private TextView gaga;
public DerpHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.lbl_item_text);
subtitle = (TextView) itemView.findViewById(R.id.lbl_item_sub_title);
gaga = (TextView) itemView.findViewById(R.id.gaga);
}
#Override
public void onClick(View view) {
/* if(view.getId() == R.id.cont_item_root){
}else{
}*/
}
}
this is my list item:
public class ListItem {
private String title;
private String subtitle;
private String gaga;
public String getGaga() {
return gaga;
}
public void setGaga(String gaga) {
this.gaga = gaga;
}
public ListItem(String title, String subtitle, String gaga) {
this.title = title;
this.subtitle = subtitle;
this.gaga = gaga;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
public String getSubtitle() {
return subtitle;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
and finally this is my mainActivity:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private DerpAdapter adapter;
private final String url_Data = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
List<ListItem> data ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.drawarlist);
//Layout Manager: GridLayoutManager or StaggerdeGridLayoutManager
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//adapter = new DerpAdapter(DerpData.getListData(), this);
recyclerView.setAdapter(adapter);
loadData();
}
public void loadData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url_Data,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("soucat");
data = new ArrayList<>();
for (int i = 0; i < array.length(); i++){
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(o.getString("soucat"),"hello","fefe");
data.add(item);
}
adapter = new DerpAdapter(data,getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
First, your initial setting of the adapter variable is commented out:
//adapter = new DerpAdapter(DerpData.getListData(), this);
recyclerView.setAdapter(adapter);
This will always set the adapter to null, you need to change it to this:
adapter = new DerpAdapter(DerpData.getListData(), this);
recyclerView.setAdapter(adapter);
Also, I don't see a call to start the Volley RequestQueue, make sure you are calling requestQueue.start(); before adding the stringRequest.
Then verify that that code for setting the adapter is being executed. You may always be hitting the ErrorListener which never sets the adapter.
You are trying to set null reference adapter to the RecyclerView, firstly you initialize adapter then set into the RecyclerView.
#Bobbake4 this is the code:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private DerpAdapter adapter;
private final String url_Data = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
List<ListItem> data ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.drawarlist);
//Layout Manager: GridLayoutManager or StaggerdeGridLayoutManager
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new DerpAdapter(DerpData.getListData(), this);
recyclerView.setAdapter(adapter);
loadData();
}
public void loadData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url_Data,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("soucat");
data = new ArrayList<>();
for (int i = 0; i < array.length(); i++){
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(o.getString("soucat"),"hello","fefe");
data.add(item);
}
adapter = new DerpAdapter(data,getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.start();
requestQueue.add(stringRequest);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want display Review text and its Rating in another activity.
Here is my AddReview class
public class AddReview extends AppCompatActivity implements ServerRequests.AddReviewreponse {
private Button submit;
EditText addReview;
RatingBar ratingBar;
Toolbar toolbar;
ServerRequests serverRequests;
JSONParser jsonParser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_review);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setAddReviewreponse(this);
addReview=(EditText)findViewById(R.id.reviewBox);
ratingBar=(RatingBar) findViewById(R.id.ratingBar);
submit=(Button)findViewById(R.id.submit);
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar_top);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Add Review");
// toolbar.setNavigationIcon(R.drawable.back_30);
/* toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});*/
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
String ReviewTxt = addReview.getText().toString();
float rating = ratingBar.getRating();
JSONObject obj = jsonParser.makeAddReviewJson(1,1,ReviewTxt,rating);
Log.e("final Json", obj.toString());
serverRequests.addReview(obj);
} catch (Exception e) {
}
/* Reviews.displayName.setText(RegisterActivity.name.getText().toString());
Reviews.displayReview.setText("Your Review : "+addReview.getText().toString());
Reviews.displayStars.setRating(ratingBar.getRating());*/
/* Reviews.displayStars.setText("Your Rating : " + ratingBar.getRating());
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
Reviews.displayDate.setText(currentDateTimeString);*/
AlertDialog alertDialog = new AlertDialog.Builder(AddReview.this).create();
alertDialog.setTitle("Review Submitted!");
alertDialog.setMessage("Thanks for your valueable review!");
alertDialog.setIcon(R.drawable.star_48);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
// startActivity(new Intent(getApplicationContext(), Reviews.class));
}
});
// Showing Alert Message
alertDialog.show();
}
});
}
#Override
public void onAddReviewReposne(JSONObject object) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home)
{
finish();
}
return super.onOptionsItemSelected(item);
}
}
This is the Review class where I want to display the review and its ratings
public class Reviews extends AppCompatActivity implements ServerRequests.GetReviewResponse {
public static TextView displayReview, displayDate, displayName;
public static RatingBar displayStars;
Button addReviewBtn;
android.support.v7.widget.Toolbar toolbar;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "CardViewActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reviews);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view1);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
// mAdapter = new ReviewAdapter(getDataSet(jsonObject));
mRecyclerView.setAdapter(mAdapter);
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar_top1);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Reviews");
/*displayReview = (TextView) findViewById(R.id.review);
displayStars = (RatingBar) findViewById(R.id.rating);
displayDate = (TextView)findViewById(R.id.displayDate);
displayName = (TextView)findViewById(R.id.displayName);*/
addReviewBtn = (Button)findViewById(R.id.addReviewBtn);
addReviewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), AddReview.class));
}
});
ServerRequests serverRequests=new ServerRequests(getApplicationContext());
serverRequests.setReviewResponse(this);
serverRequests.getReviews("one");
}
private ArrayList<Review> getDataSet(JSONArray array) {
ArrayList results = new ArrayList<Review>();
for (int i = 0; i < array.length(); i++) {
try {
JSONObject object = array.getJSONObject(i);
Review obj = new Review(object.getInt("reviewId"),object.getInt("userId"),object.getString("Name"),object.getString("Review"),object.getLong("rating"));
results.add(i,obj);
}
catch (Exception e){
e.printStackTrace();
}
}
return results;
}
#Override
public void onGetReviewResponse(JSONArray jsonObject) {
mAdapter = new ReviewAdapter(getDataSet(jsonObject));
mRecyclerView.setAdapter(mAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home)
{
finish();
}
return super.onOptionsItemSelected(item);
}
}
This is the ReviewAdapter
public class ReviewAdapter extends RecyclerView.Adapter<ReviewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<Review> mDataset;
private static MyClickListener myClickListener;
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public static TextView name,review;
public static RatingBar rating;
public DataObjectHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
review = (TextView) itemView.findViewById(R.id.review);
rating = (RatingBar) itemView.findViewById(R.id.rating);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public ReviewAdapter(ArrayList<Review> myDataset) {
mDataset = myDataset;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view_review, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.name.setText(mDataset.get(position).getName());
holder.review.setText(mDataset.get(position).getReview());
holder.rating.setRating(mDataset.get(position).getRating());
}
public void addItem(Review dataObj, int index) {
mDataset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
This is the Pojo class of Review
public class Review {
private String name,review;
private float rating;
private int reviewId,userId;
public Review (int ReviewId, int UserId, String Name, String Review, float Rating){
reviewId = ReviewId;
userId = UserId;
name = Name;
review = Review;
rating = Rating;
}
public int getReviewId() {
return reviewId;
}
public void setReviewId(int reviewId) {
this.reviewId = reviewId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
}
This is the ServerRequests for add and get Review
//------------For add review------------------------------
public void setAddReviewreponse(AddReviewreponse addreviewreponse) {
this.addreviewreponse = addreviewreponse;
}
private AddReviewreponse addreviewreponse;
public interface AddReviewreponse {
void onAddReviewReposne(JSONObject object);
}
public void addReview(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.ADD_REVIEW, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (addreviewreponse != null) {
addreviewreponse.onAddReviewReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
//------------For get review------------------------------
public void setReviewResponse(GetReviewResponse reviewResponse) {
this.getReviewResponse = reviewResponse;
}
public GetReviewResponse getReviewResponse;
public interface GetReviewResponse {
void onGetReviewResponse(JSONArray jsonObject);
}
public void getReviews(final String id) {
StringRequest request = new StringRequest(Request.Method.GET, Services.GET_REVIEW,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
Log.e("Server response", response);
if (array.length() > 0) {
if (getReviewResponse != null) {
getReviewResponse.onGetReviewResponse(array);
}
} else {
Log.e("Error is occured", "asd");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//send error repsonse back to user
Log.e("Error: ", error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("courseId", id);
return params;
}
};
queue.add(request);
}
This is JSONParser class for AddReview
//--------For Add review---------------------------------
public JSONObject makeAddReviewJson(int studentID, int courseID, String reviewTxt, float rating) throws JSONException {
JSONObject object = new JSONObject();
object.put("studentId", studentID);
object.put("courseId", courseID);
object.put("review", reviewTxt);
object.put("ratings", rating);
return object;
}
This is the JSON response I am getting after posting the Review
E/final Json: {"studentId":1,"courseId":1,"review":"Hellooooo","ratings":3}
E/Json response: {"success":true,"msg":"Your review has been added successfully","data":{"reviewsId":18}}
private ArrayList<Review> getDataSet(JSONArray array) {
ArrayList results = new ArrayList<Review>();
for (int i = 0; i < array.length(); i++) {
try {
JSONObject object = array.getJSONObject(i);
Review obj = new Review(object.getInt("studentId"),object.getInt("courseId"),object.getString("Review"),object.getLong("rating"));
results.add(i,obj);
}
catch (Exception e){
e.printStackTrace();
}
}
return results;
}
try to change your getDataSet function with above code and check with debug point if you get any problem in some line. feel free to ask further will help you
EDIT:
You need to change your Pojo class of Review also. Because in JSON response you are not getting userId and reviewId. Hope you understand
I am creating an app where there are 2 RecyclerView in one layout. I set one for category and second for text based on category. when i am debug my code that give me recyclerview display null value on this line recyclerView.setAdapter(adapter); in adapter see in image
I want to select category item then give the text that contain that category.
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private List<TextJson> listtext;
private List<CategoryJson> horizentallylist;
private RecyclerView recyclerView , horizantalrcview;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
String textUrl = "http:www.extample.com/texturl.php";
String categoryUrl ="http:www.extample.com/categoryurl.php";
private static final String TAG = MainActivity.class.getSimpleName();
private JSONArray result;
ArrayAdapter<String> adapterSpin;
CategoryJson categoryJson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView_text);
horizantalrcview = (RecyclerView)findViewById(R.id.recyclerView_cate);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
listtext = new ArrayList<>();
horizentallylist = new ArrayList<>();
getData();
verticalData();
}
private void getData() {
final ProgressDialog loading = ProgressDialog.show(this, "Loading Data", "Please wait...", false, false);
loading.setCancelable(true);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(textUrl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("text", "resopnce is =>" + response);
loading.dismiss();
verticalParse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private void verticalParse(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
TextJson jsonitem = new TextJson();
JSONObject json = null;
try {
json = array.getJSONObject(i);
String text = json.getString("txt");
String txtcate = json.getString("category");
jsonitem.setText_status(text);
jsonitem.setCategory(txtcate);
Log.e("text", "is==> " + text);
Log.e("cate", "is==> " + txtcate);
} catch (JSONException e) {
e.printStackTrace();
}
listtext.add(jsonitem);
}
//Finally initializing our adapter
adapter = new VerticalAdapter(listtext, this);
adapter.notifyDataSetChanged();
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
private void verticalData() {
final ProgressDialog loading = ProgressDialog.show(this, "Loading Data", "Please wait...", false, false);
loading.setCancelable(true);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(categoryUrl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("Response is", "first==>" + response);
loading.dismiss();
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError) {
Log.e("NoConnectionError>>", "NoConnectionError....");
} else if (error instanceof AuthFailureError) {
Log.e("AuthFailureError>>>", "AuthFailureError...");
} else if (error instanceof ServerError) {
Log.e("ServerError>>>>>>>>>", "ServerError.......");
} else if (error instanceof NetworkError) {
Log.e("NetworkError>>>>>>>>>", "NetworkError.......");
} else if (error instanceof ParseError) {
Log.e("ParseError>>>>>>>>>", "ParseError.......");
} else if (error instanceof TimeoutError) {
Log.d("TimeoutError>>>>>>>>>", "TimeoutError.......");
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
CategoryJson model1 = new CategoryJson();
JSONObject json = null;
try {
json = array.getJSONObject(i);
String imgurl = json.getString("cat_img");
String imgname = json.getString("category");
Log.e("value in","link=>"+imgurl);
Log.e("value in","imagename=>"+imgname);
model1.setImageUrl(imgurl);
model1.setName(imgname);
} catch (JSONException e) {
e.printStackTrace();
}
horizentallylist.add(model1);
}
//Finally initializing our adapter
adapter = new HorizantalAdapter(horizentallylist, this);
adapter.notifyDataSetChanged();
//Adding adapter to recyclerview
horizantalrcview.setAdapter(adapter);
}
private void selectData() {
NewModel newModel = new NewModel();
final ProgressDialog loading = ProgressDialog.show(this, "Loading Data", "Please wait...", false, false);
loading.setCancelable(true);
String txtselect =newModel.getItem().toString();
String select_cate ="http:www.extample.com/filter.php"+selectitem;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(select_cate ,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("text", "resopnce is =>" + response);
loading.dismiss();
selectParse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private void selectParse(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
TextJson jsonitem = new TextJson();
JSONObject json = null;
try {
json = array.getJSONObject(i);
String text = json.getString("txt");
String txtcate = json.getString("category");
jsonitem.setText_status(text);
jsonitem.setCategory(txtcate);
Log.e("text", "is==> " + text);
Log.e("cate", "is==> " + txtcate);
} catch (JSONException e) {
e.printStackTrace();
}
listtext.add(jsonitem);
}
//Finally initializing our adapter
adapter = new VerticalAdapter(listtext, this);
adapter.notifyDataSetChanged();
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
HorizantalAdapter
public class HorizantalAdapter extends RecyclerView.Adapter<HorizantalAdapter.ViewHolder> {
private ImageLoader imageLoader;
private Context context;
List<CategoryJson> listmodel;
NewModel newModel = new NewModel();
String link;
public HorizantalAdapter(List<CategoryJson> listmodel, Context context) {
super();
this.listmodel = listmodel;
this.context = context;
setHasStableIds(false);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.text_horigentally, parent, false);
HorizantalAdapter.ViewHolder viewHolder = new HorizantalAdapter.ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final HorizantalAdapter.ViewHolder holder, final int position) {
CategoryJson imgModel = listmodel.get(position);
imageLoader =CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(imgModel.getImageUrl(),imageLoader.getImageListener(holder.imageView,R.drawable.placeholder,android.R.drawable.ic_dialog_alert));
holder.imageView.setImageUrl(imgModel.getImageUrl(),imageLoader);
holder.textViewName.setText(imgModel.getName());
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
link = listmodel.get(position).getName();
newModel.setItem(link);
Toast.makeText(context, "select item select" +link, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return listmodel.size();
}
public long getItemId(int position) {
return position;
}
class ViewHolder extends RecyclerView.ViewHolder {
public NetworkImageView imageView;
public TextView textViewName;
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.imageView_img);
imageView.setScaleType(NetworkImageView.ScaleType.FIT_CENTER);
textViewName = (TextView) itemView.findViewById(R.id.text_cate);
}
}
}
VerticalAdapter
public class VerticalAdapter extends RecyclerView.Adapter<VerticalAdapter.ViewHolder> {
private Context context;
String link;
List<TextJson> listmodel;
private Activity parentActivity;
public VerticalAdapter(List<TextJson> listmodel, Context context) {
super();
this.listmodel = listmodel;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.text_virtically, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
TextJson model = listmodel.get(position);
holder.textViewName.setText(model.getText_status());
holder.textViewName.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
link = listmodel.get(position).getText_status();
return true;
}
});
}
#Override
public int getItemCount() {
return listmodel.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName;
public ViewHolder(View itemView) {
super(itemView);
textViewName = (TextView) itemView.findViewById(R.id.texting_status);
}
}
}
Log
08-01 18:28:14.021 11378-11378/com.vm.recyclervirtical E/text: is==> Stinging Jellyfish Come to Jersey, But Beaches Sti
08-01 18:28:14.021 11378-11378/com.vm.recyclervirtical E/cate: is==> speech
08-01 18:28:14.021 11378-11378/com.vm.recyclervirtical E/text: is==> Koala Facts for Kids | Australian Animals
08-01 18:28:14.021 11378-11378/com.vm.recyclervirtical E/cate: is==> motivational
08-01 18:28:14.021 11378-11378/com.vm.recyclervirtical E/text: is==> Antarctic penguins ielts reading passage
08-01 18:28:14.021 11378-11378/com.vm.recyclervirtical E/cate: is==> dance
08-01 18:28:14.061 11378-11378/com.vm.recyclervirtical E/Cache is: 0_0==>com.android.volley.toolbox.DiskBasedCache#41812ce8
08-01 18:28:24.861 11378-11378/com.vm.recyclervirtical E/text: resopnce is =>http://www.example.com/filtered/evideo/json/jsoncategory.php?category=motivational
08-01 18:28:25.331 11378-11378/com.vm.recyclervirtical E/text: resopnce is =>[{"txt":"Koala Facts for Kids | Australian Animals"}]
08-01 18:28:25.351 11378-11378/com.vm.recyclervirtical E/text: is==> Koala Facts for Kids | Australian Animals
Image
After debug
This is a broad problem, so I can suggest some basic approach, which is to pass the click listener into the constructor of the adapter.
public class HorizantalAdapter extends RecyclerView.Adapter<HorizantalAdapter.ViewHolder>
/*** Store a reference ***/
private View.OnClickListener clickListener;
/*** Add that reference ***/
public HorizantalAdapter(List<CategoryJson> listmodel, Context context, View.OnClickListener clickListener) {
super();
this.listmodel = listmodel;
this.context = context;
setHasStableIds(false);
/*** Set the reference ***/
this.clickListener = clickListener;
}
.......
#Override
public void onBindViewHolder(final HorizantalAdapter.ViewHolder holder, final int position) {
.........
/*** Use the reference ***/
holder.imageView.setOnClickListener(clickListener);
}
Then in the Activity, where you set the horizontal adapter
private void parseData(JSONArray array) {
.........
/*** Define the listener ***/
final View.OnClickListener horizontalClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
link = listmodel.get(position).getName();
newModel.setItem(link);
Toast.makeText(context, "select item select" +link, Toast.LENGTH_SHORT).show();
// TODO: Make Volley request for Categories here...
// Should be able to set other adapter in onResponse there
}
};
/*** Pass in the listener reference ***/
adapter = new HorizantalAdapter(horizentallylist, this, horizontalClickListener);
}
In response to the edit, the messages are coming from these lines
Log.e("text", "is==> " + text);
Log.e("cate", "is==> " + txtcate);
when I conduct onRefresh, my recyclerView adds on another copy to my current recyclerView instead of refreshing it, by looking at my code below does anyone know what the problem is?I have tried everything but nothing seems to work?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
//send our volley JSON Request
//Initialize VolleySingleton
mVolleySingleton = VolleySingleton.getInstance();
//intitalize Volley Singleton request key
mRequestQueue = mVolleySingleton.getRequestQueue();
//2 types of requests an Array request and an Object Request
JSONArrayRequest();
}
private void JSONArrayRequest() {
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_API, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listblogs=parseJSONResponse(response);
mAdapterDashBoard.setBloglist(listblogs);
System.out.println("it worked!!!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
ToastTest.t(getActivity(), error.toString());
}
});
mRequestQueue.add(request);
}
private ArrayList<Blogs> parseJSONResponse(JSONArray response) {
if (!response.equals("")) {
ArrayList<Blogs> blogsArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String points = currentQuestions.getString("points");
String ID=currentQuestions.getString("id");
String courseId = currentQuestions.getString("courseId");
String studentId = currentQuestions.getString("studentId");
data.append(text + "\n" + points + "\n" + courseId + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setId(ID);
blogs.setMstudentId(studentId);
blogs.setMtext(text);
blogs.setPoints(points);
listblogs.add(blogs);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_dashboard,container,false);
mRecyclerView=(RecyclerView)view.findViewById(R.id.fragment_dashboard);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapterDashBoard=new AdapterDashBoard(getActivity());
mRecyclerView.setAdapter(mAdapterDashBoard);
mPullToRefreshView = (PullToRefreshView)view.findViewById(R.id.pull_to_refresh);
mPullToRefreshView.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
#Override
public void onRefresh() {
mPullToRefreshView.postDelayed(new Runnable() {
#Override
public void run() {
mPullToRefreshView.setRefreshing(false);
JSONArrayRequest();
}
}, REFRESH_DELAY);
}
});
return view;
}
}
public class AdapterDashBoard extends RecyclerView.Adapter<AdapterDashBoard.ViewDashboard>{
private LayoutInflater mLayoutInflater;
private ArrayList<Blogs> listblogs=new ArrayList<>();
public AdapterDashBoard(Context context){
mLayoutInflater=LayoutInflater.from(context);
}
public void setBloglist(ArrayList<Blogs> listBlogs){
this.listblogs=listBlogs;
notifyItemRangeChanged(0,listBlogs.size());
}
#Override
public ViewDashboard onCreateViewHolder(ViewGroup parent, int viewType) {
View view= mLayoutInflater.inflate(R.layout.customizejson,parent,false);
ViewDashboard viewholder=new ViewDashboard(view);
return viewholder;
}
#Override
public void onBindViewHolder(ViewDashboard holder, int position) {
Blogs currentBlog=listblogs.get(position);
holder.questionText.setText(currentBlog.getMtext().toString());
holder.points.setText(currentBlog.getPoints().toString());
holder.id.setText(currentBlog.getId().toString());
}
#Override
public int getItemCount() {
return listblogs.size();
}
static class ViewDashboard extends RecyclerView.ViewHolder{
private ImageView thumbnail;
private TextView questionText;
private TextView points;
private TextView id;
public ViewDashboard (View itemView){
super(itemView);
//thumbnail=(ImageView)itemView.findViewById(R.id.thumbnail);
questionText=(TextView)itemView.findViewById(R.id.questionText);
points=(TextView)itemView.findViewById(R.id.points);
id=(TextView)itemView.findViewById(R.id.ID);
}
}
}
You need to clear your listblogs list before adding new items. This is why you get duplicated values.
Also you're already adding new items to listblogs in parseJSONResponse() method, so there is no need for listblogs=parseJSONResponse(response); in onResponse() method, while its the same list.
Change your onResponse() method to:
#Override
public void onResponse(JSONArray response) {
listblogs.clear(); // here you clear the old data
parseJSONResponse(response);
mAdapterDashBoard.setBloglist(listblogs);
System.out.println("it worked!!!");
}