I have this weird periodic error, when i boot the app, and the onCreate is called, but the CardView is not showing anything. Other times I do the exact same thing, booting the app, and the CardView is showing exactly what it should.
I can't seem to find the error..
The main class:
package lassebjoerklund.easyfridge;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class BootActivity extends Activity {
//TODO Make get method for table with barcode.
//TODO Update postRequest so that it macthes the barcode to the database, and getting a json object. object -> toString
private ArrayList<Products> productsToDisplayInlist;
private String TAG = BootActivity.class.getSimpleName();
private String getDataurl = "http://XXX.XXX.XXX.XXX/selectAll.php";
private static String insertDataUrl = "http://XXX.XXX.XXX.XXX/insertAll.php";
private JsonArrayRequest jsonArrayRequest;
private RecyclerView.Adapter mAdapter;
private String jsonRespons = "";
private static RequestQueue rQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Layout
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_boot_layout);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.cardList);
recyclerView.setHasFixedSize(false);
recyclerView.setLayoutManager(linearLayoutManager);
//RequestQueue
rQueue = Volley.newRequestQueue(this);
productsToDisplayInlist = new ArrayList<>();
getRequest();
Log.d(TAG, productsToDisplayInlist.toString());
mAdapter = new ProductCardAdapter(productsToDisplayInlist);
recyclerView.setAdapter(mAdapter);
//Intent to switch to activity
//final Intent dispalyProductsIntent = new Intent(BootActivity.this, ProductViewController.class);
//final Intent scanBarcodeIntent = new Intent(BootActivity.this, BarcodeTracking.class);
//final ImageButton updateViewButton = (ImageButton) findViewById(R.id.bViewProducts);
/*updateViewButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(dispalyProductsIntent);
}
});*/
/* final ImageButton addNewEntry = (ImageButton) findViewById(R.id.addEntry);
addNewEntry.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
startActivity(scanBarcodeIntent);
}
});*/
}
#Override
protected void onResume() {
Log.d("onResume", "onResume");
/*Toast toast = Toast.makeText(this, "onResume", Toast.LENGTH_LONG);
toast.show();*/
super.onResume();
}
#Override
protected void onRestart() {
Log.d("onRestart", "onRestart");
/*Toast toast = Toast.makeText(this, "onRestart", Toast.LENGTH_SHORT);
toast.show();*/
super.onRestart();
}
#Override
protected void onStop() {
Log.d("onStop", "onStop");
// productsToDisplayInlist.clear();
super.onStop();
}
#Override
protected void onPause() {
Log.d("onPause", "onPause");
super.onPause();
}
//TODO make error msg if there is no connection.
public void getRequest() {
productsToDisplayInlist.clear();
jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, getDataurl, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject productToBuild = (JSONObject) response.get(i);
jsonRespons = productToBuild.toString();
String barcode = productToBuild.getString("code");
String name = productToBuild.getString("name");
String type = productToBuild.getString("type");
int id = productToBuild.optInt("id");
String rmDate = productToBuild.getString("rm_date");
String exDate = productToBuild.getString("ex_date");
String placementDate = productToBuild.getString("add_date");
Products product = new Products(barcode, name, placementDate, exDate, rmDate, type);
productsToDisplayInlist.add(product);
Log.d("Product", product.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Volly", "Error");
error.printStackTrace();
}
});
rQueue.add(jsonArrayRequest);
}
public static void postRequest(final Products product) {
try {
StringRequest stringRequest = new StringRequest(Request.Method.POST, insertDataUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d("onResponse", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Volley insertData", "ERROR");
Log.d("error: ", error.getCause().toString());
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> perameters = new HashMap<>();
perameters.put("barcode", product.getBarcode());
perameters.put("addDate", product.getDayOfadd());
perameters.put("exDate", product.getExDate());
return perameters;
}
};
rQueue.add(stringRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here I init the layout and add the adapter for the RecycleView. The productsToDisplayInList is populated in the getRequest() method. But somehow, it's only periodic getting populated..
Adapter class:
package lassebjoerklund.easyfridge;
import android.graphics.Color;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class ProductCardAdapter extends RecyclerView.Adapter<ProductHolder> {
private CardView cardView;
private List<Products> productses;
private Calendar c;
public ProductCardAdapter(ArrayList<Products> items) {
productses = items;
}
#Override
public int getItemCount() {
return productses.size();
}
#Override
public void onBindViewHolder(ProductHolder holder, int position) {
Products product = productses.get(position);
Date returnDate = Util.parseDateString(product.getExDate());
if (Util.getCurrentDate().after(returnDate)) {
cardView.setCardBackgroundColor(Color.parseColor("#FF000D"));
holder.cardName.setText(product.getName());
holder.cardAddDate.setText(product.getDayOfadd());
holder.cardExDate.setText(product.getExDate());
holder.cardType.setText(product.getType());
Log.d("Product Card", product.toString());
} else {
holder.cardName.setText(product.getName());
holder.cardAddDate.setText(product.getDayOfadd());
holder.cardExDate.setText(product.getExDate());
holder.cardType.setText(product.getType());
Log.d("Product Card", product.toString());
}
}
#Override
public ProductHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardlayout, parent, false);
cardView = new CardView(parent.getContext());
return new ProductHolder(itemView);
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
Holder Class:
package lassebjoerklund.easyfridge;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
public class ProductHolder extends RecyclerView.ViewHolder {
protected TextView cardName;
protected TextView cardAddDate;
protected TextView cardExDate;
protected TextView cardType;
public ProductHolder(View itemView) {
super(itemView);
cardName = (TextView) itemView.findViewById(R.id.cardName);
cardAddDate = (TextView) itemView.findViewById(R.id.cardAddDate);
cardExDate = (TextView) itemView.findViewById(R.id.cardExDate);
cardType = (TextView) itemView.findViewById(R.id.cardType);
}
}
Related
I have made an android application using java, and I have made a click listener interface but nothing seems to happen and I can't figure out what is wrong with my code. Please help.
Following is the code of my recyclerViewAdapter:
package com.example.ashwamedh.adapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.ashwamedh.R;
import com.example.ashwamedh.model.AdminConfirmation;
import com.example.ashwamedh.model.Attendance;
import com.example.ashwamedh.model.Confirmation;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.List;
import java.util.Objects;
public class ManageAttendanceRecyclerViewAdapter extends RecyclerView.Adapter<ManageAttendanceRecyclerViewAdapter.ViewHolder> {
private List<Confirmation> practiceList;
private Context context;
private OnAttendanceClickListener onAttendanceClickListener;
private CollectionReference collectionReference = FirebaseFirestore.getInstance().collection("Users");
public ManageAttendanceRecyclerViewAdapter(List<Confirmation> practiceList, Context context, OnAttendanceClickListener onAttendanceClickListener) {
this.practiceList = practiceList;
this.context = context;
this.onAttendanceClickListener = onAttendanceClickListener;
}
#NonNull
#Override
public ManageAttendanceRecyclerViewAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context)
.inflate(R.layout.manage_attendance_row, parent, false);
return new ViewHolder(view, context);
}
#Override
public void onBindViewHolder(#NonNull ManageAttendanceRecyclerViewAdapter.ViewHolder holder, int position) {
Confirmation confirmation = practiceList.get(position);
holder.nameTextView.setText(confirmation.getUsername());
if (confirmation.getRemarkOrReason() == "") {
holder.remarkOrReasonTextView.setText("null");
}else {
holder.remarkOrReasonTextView.setText(confirmation.getRemarkOrReason());
}
if (Objects.equals(confirmation.getConfirmation(), "present")) {
holder.confirmation.setImageResource(R.drawable.ic_baseline_check_24);
} else if (Objects.equals(confirmation.getConfirmation(), "absent")){
holder.confirmation.setImageResource(R.drawable.ic_baseline_close_24);
}
}
#Override
public int getItemCount() {
return practiceList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView nameTextView;
private ImageView confirmation;
private TextView remarkOrReasonTextView;
OnAttendanceClickListener onAttendanceClickListener;
public ViewHolder(#NonNull View itemView, Context ctx) {
super(itemView);
this.onAttendanceClickListener = ManageAttendanceRecyclerViewAdapter.this.onAttendanceClickListener;
context = ctx;
nameTextView = itemView.findViewById(R.id.manage_attendance_name_textview);
confirmation = itemView.findViewById(R.id.manage_attendance_confirmation);
remarkOrReasonTextView = itemView.findViewById(R.id.manage_attendance_remark_reason_textview);
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id){
case R.id.manage_attendance_row:
Log.d("from recycler view", "onClick: " + "row clicked");
Confirmation confirmation = practiceList.get(getAdapterPosition());
String userId = confirmation.getUserId();
onAttendanceClickListener.OnAttendanceClick(userId);
}
}
}
}
Following is the code of OnAttendanceClickListener:
package com.example.ashwamedh.adapter;
public interface OnAttendanceClickListener {
void OnAttendanceClick(String userId);
}
Following is the code of the activity where the recycler view is used and the interface implemented:
package com.example.ashwamedh;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ashwamedh.adapter.ManageAttendanceRecyclerViewAdapter;
import com.example.ashwamedh.adapter.OnAttendanceClickListener;
import com.example.ashwamedh.model.Confirmation;
import com.example.ashwamedh.util.UserApi;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;
public class ManagePracticeConfirmationActivity extends AppCompatActivity implements OnAttendanceClickListener {
private static final String TAG = "PRACTICE_CONFIRMATION";
private RecyclerView recyclerView;
private BottomNavigationView bottomNavigationView;
private CardView markAttendanceCardView;
private FloatingActionButton presentFab;
private FloatingActionButton absentFab;
private Button updateButton;
private TextView noPracticeTextView;
private ImageButton signOut;
private Boolean isAdmin;
private String attendance;
private ManageAttendanceRecyclerViewAdapter manageAttendanceRecyclerViewAdapter;
private String practiceDate;
private List<Confirmation> practiceList;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference collectionReference = db.collection("Confirmations");
private CollectionReference userCollection = db.collection("Users");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_practice_confirmation);
Objects.requireNonNull(getSupportActionBar()).hide();
practiceList = new ArrayList<>();
recyclerView = findViewById(R.id.manage_attendance_recycler_view);
bottomNavigationView = findViewById(R.id.bottomNavigationView);
markAttendanceCardView = findViewById(R.id.mark_attendance_cardView);
presentFab = findViewById(R.id.present_fab);
absentFab = findViewById(R.id.absent_fab);
updateButton = findViewById(R.id.update_attendance_button);
noPracticeTextView = findViewById(R.id.no_practice_textView);
signOut = findViewById(R.id.signOut_manage_attendance);
absentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.absent_button_color)));
presentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.present_button_color)));
bottomNavigationView.setSelectedItemId(R.id.manage_practice_confirmation_button);
markAttendanceCardView.setVisibility(View.INVISIBLE);
UserApi userApi = UserApi.getInstance();
isAdmin = Objects.equals(userApi.getUsername(), "ADMIN");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
attendance = "";
Date today = Calendar.getInstance().getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
practiceDate = simpleDateFormat.format(today);
Log.d(TAG, "onCreate: " + Calendar.DAY_OF_WEEK);
if (Calendar.getInstance().get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
|| Calendar.getInstance().get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
recyclerView.setVisibility(View.INVISIBLE);
noPracticeTextView.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
noPracticeTextView.setVisibility(View.INVISIBLE);
}
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.home_button) {
Intent intent = new Intent(ManagePracticeConfirmationActivity.this, Dashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
return true;
}
if (item.getItemId() == R.id.council_button) {
Intent intent = new Intent(ManagePracticeConfirmationActivity.this, CouncilActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
return true;
}
if (item.getItemId() == R.id.attendance_button) {
Intent intent = new Intent(ManagePracticeConfirmationActivity.this, BatchmateAttendance.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
return true;
}
if (item.getItemId() == R.id.manage_practice_confirmation_button) {
return true;
}
return false;
}
});
}
#Override
protected void onStart() {
super.onStart();
Date today = Calendar.getInstance().getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
practiceDate = simpleDateFormat.format(today);
collectionReference.whereEqualTo("practiceDate", practiceDate)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
for (QueryDocumentSnapshot snapshot : queryDocumentSnapshots) {
Confirmation confirmation = snapshot.toObject(Confirmation.class);
practiceList.add(confirmation);
}
manageAttendanceRecyclerViewAdapter = new ManageAttendanceRecyclerViewAdapter(practiceList,
ManagePracticeConfirmationActivity.this,
ManagePracticeConfirmationActivity.this);
recyclerView.setAdapter(manageAttendanceRecyclerViewAdapter);
manageAttendanceRecyclerViewAdapter.notifyDataSetChanged();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
#Override
public void OnAttendanceClick(String userId) {
Log.d(TAG, "OnAttendanceClick: "+ isAdmin);
UserApi userApi = UserApi.getInstance();
isAdmin = Objects.equals(userApi.getUsername(), "ADMIN");
if (isAdmin) {
markAttendanceCardView.setVisibility(View.VISIBLE);
presentFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
attendance = "present";
presentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.selected_button_color)));
absentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.absent_button_color)));
}
});
absentFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
attendance = "absent";
absentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.selected_button_color)));
presentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.present_button_color)));
}
});
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Confirmation confirmation = new Confirmation();
confirmation.setUserId(userId);
confirmation.setConfirmation(attendance);
confirmation.setPracticeDate(practiceDate);
if (Objects.equals(attendance, "present")) {
confirmation.setRemarkOrReason("PRESENT ON PRACTICE");
} else if (Objects.equals(attendance, "absent")){
confirmation.setRemarkOrReason("ABSENT ON PRACTICE");
}
SimpleDateFormat documentDateFormat = new SimpleDateFormat("dd_MM_yyyy");
String docDate = documentDateFormat.format(practiceDate);
String docAddress = userId+"_"+docDate;
collectionReference.document(docAddress)
.set(confirmation)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(ManagePracticeConfirmationActivity.this, "Attendance marked!", Toast.LENGTH_SHORT)
.show();
}
});
attendance = "";
absentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.absent_button_color)));
presentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.present_button_color)));
markAttendanceCardView.setVisibility(View.INVISIBLE);
manageAttendanceRecyclerViewAdapter.notifyDataSetChanged();
}
});
} else {
Toast.makeText(ManagePracticeConfirmationActivity.this, "Only admins can mark attendance!", Toast.LENGTH_SHORT)
.show();
}
}
}
Please help me I am clueless of where is the error
RecyclerView clicks doesn't work like that.
Firstly you should write click event in onBindViewHolder
holder.itemView.setOnClickListener(view -> onAttendanceClickListener.OnAttendanceClick(userId));
Put this code in your onBindViewHolder and you are good to go!
You will receive click events in Activity.
I try to get data from the database via API but the recyclerview doesn't display anything and the log displays an error.
This is my code
Fragment
package com.example.hp.retailmakanan;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
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 com.example.hp.retailmakanan.Model.MenuModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class FragHome extends Fragment {
RecyclerView recV;
BottomNavigationView top_navigation;
HomeAdapter listAdapter;
List<MenuModel> listMenu= new ArrayList<>();
private BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment sfragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_noodle:
recV.setAdapter(listAdapter);
break;
case R.id.nav_beverage:
recV.setAdapter(listAdapter);
break;
case R.id.nav_toping:
recV.setAdapter(listAdapter);
break;
case R.id.nav_cari:
recV.setAdapter(listAdapter);
break;
}
return false;
}
};
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.act_home, container, false);
recV = (RecyclerView) v.findViewById(R.id.rec_ramen);
getData();
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recV.setLayoutManager(layoutManager);
listAdapter = new HomeAdapter(listMenu, getActivity());
recV.setAdapter(listAdapter);
top_navigation = (BottomNavigationView) v.findViewById(R.id.top_nav);
top_navigation.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener);
return v;
}
this is the code that i used to get data
private void getData() {
String url ="https://waggish-requisition.000webhostapp.com/GetAllMenu.php";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listMenu.clear();
for (int i = 0; i < response.length(); i++) {
try {
Log.d("menu",response.toString());
JSONObject jsonObject = response.getJSONObject(i);
String id_menu = jsonObject.getString("id");
String nama_menu = jsonObject.getString("nama_menu");
String deskripsi = jsonObject.getString("deskripsi");
int harga = jsonObject.getInt("harga");
MenuModel menus = new MenuModel(id_menu,nama_menu,deskripsi,harga);
listMenu.add(menus);
System.out.println(menus);
//Toast.makeText(this,"Download data "+i,Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
Log.d("menu",e.toString());
}
listAdapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonArrayRequest);
}
}
Adapter
package com.example.hp.retailmakanan;
import android.content.Context;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v7.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.TextView;
import com.example.hp.retailmakanan.Model.MenuModel;
import java.util.Arrays;
import java.util.List;
public class HomeAdapter extends RecyclerView.Adapter {
private List<MenuModel> menus;
private Context context;
public HomeAdapter(List<MenuModel> menus, Context context) {
this.context = context;
this.menus = menus;
//System.out.println(menus);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recv_desain, viewGroup, false);
return new ListViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int pos) {
}
#Override
public int getItemCount() {
return menus.size();
}
public class ListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView mText,txt2, txt3, txtQty;
ImageView img;
Button btnMin, btnPlus;
int x;
public ListViewHolder(View itemView){
super(itemView);
mText = itemView.findViewById(R.id.text_item);
txt2 = itemView.findViewById(R.id.text_item2);
txt3 = itemView.findViewById(R.id.textView3);
img = itemView.findViewById(R.id.image_item);
btnMin = itemView.findViewById(R.id.buttonMinMenu);
btnPlus = itemView.findViewById(R.id.buttonPlusMenu);
txtQty = itemView.findViewById(R.id.textQtyMenu);
itemView.setOnClickListener(this);
}
public void bindView (int pos){
x=0;
MenuModel model = menus.get(pos);
mText.setText(model.getNama_menu());
txt2.setText(model.getDeskripsi());
txt3.setText(model.getHarga());
//img.setImageResource(DataMenu.picture[pos]);
txtQty.setText(String.valueOf(x));
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x++;
txtQty.setText(String.valueOf(x));
}
});
btnMin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x--;
if (x<=0){
x=0;
txtQty.setText(String.valueOf(x));
}else if (x>0){
txtQty.setText(String.valueOf(x));
}
}
});
}
#Override
public void onClick(View v) {
}
}
}
And this is my php code
<?php
require_once('connection.php');
//public $mServerName;
//public $mConnectionInfo;
//public $conn;
//Create query to retrieve all contacts
$query = "SELECT * FROM menu";
$stmt = mysqli_query($conn, $query);
if (!$stmt)
{
//Query failed
echo 'Query failed';
}
else
{
$menus= array(); //Create an array to hold all of the contacts
//Query successful, begin putting each contact into an array of contacts
while ($row = mysqli_fetch_array($stmt)) //While there are still contacts
{
//Create an associative array to hold the current contact
//the names must match exactly the property names in the contact class in our C# code.
$menu= array("id" => $row['id_menu'],
"deskripsi" => $row['Deskripsi'],
"nama_menu" => $row['nm_menu'],
"harga" => $row['harga_menu'],
"ImageUrl" =>$row['gambar']
);
//Add the contact to the contacts array
array_push($menus, $menu);
}
//Echo out the contacts array in JSON format
echo json_encode($menus);
}
?>
I changed JSONObject to JSONArray, but that caused many other errors. I am a beginner please help me. I really don't know what to do :(
I am new to android. I am trying to download data using the Github api and display in and infinite scrolling RecyclerView, the JSON data is been parsed, but somehow the data is not been attached to the recyclerview.
Here is the code below:
Developer_RV_Adapter.java
package com.davidshare.githubdevelopers;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by GemShare on 9/6/2017.
*/
public class Developer_RV_Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private OnLoadMoreListener mOnLoadMoreListener;
private boolean isLoading;
private int visibleThreshold = 10;
private int lastVisibleItem, totalItemCount;
private List<Developer> developerList;
Context context;
RecyclerView recyclerView;
public Developer_RV_Adapter(Context context, List<Developer> developerList, RecyclerView recyclerView) {
this.developerList = developerList;
this.context = context;
this.recyclerView = recyclerView;
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
if(!isLoading && totalItemCount<=(lastVisibleItem+visibleThreshold)){
if(mOnLoadMoreListener!=null){
mOnLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
});
}
public void setmOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener){
this.mOnLoadMoreListener = mOnLoadMoreListener;
}
#Override
public int getItemViewType(int position){
return developerList.get(position) == null? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == VIEW_TYPE_ITEM){
View developerView = LayoutInflater.from(context).inflate(R.layout.developer_list_item, parent, false);
return new DeveloperViewHolder(developerView);
}else if(viewType== VIEW_TYPE_LOADING){
View loadingView = LayoutInflater.from(context).inflate(R.layout.progress_bar_item, parent, false);
return new ProgressViewHolder(loadingView);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Log.w("binder function", "Just entered the binder");
Developer developer = developerList.get(position);
if(holder instanceof DeveloperViewHolder){
DeveloperViewHolder developerViewHolder = (DeveloperViewHolder) holder;
developerViewHolder.gitNameTv.setText(developer.getGitUsername());
Log.w("binder ", developer.getGitProfileUrl());
developerViewHolder.gitUrlTv.setText(developer.getGitProfileUrl());
developerViewHolder.gitPicUrlTv.setText(developer.getGitProfilePicUrl());
Log.w("profile pic", developer.getGitProfilePicUrl());
Picasso.with(developerViewHolder.gitNameTv.getContext()).load(developer.getGitProfilePicUrl()).transform(new RoundedImage(2)).fit().centerCrop().into(developerViewHolder.profilePicImgV);
}else if (holder instanceof ProgressViewHolder) {
ProgressViewHolder loadingViewHolder = (ProgressViewHolder) holder;
loadingViewHolder.loadingProgress.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
return developerList == null ? 0 : developerList.size();
}
public void setLoaded() {
isLoading = false;
}
public class DeveloperViewHolder extends RecyclerView.ViewHolder{
TextView gitNameTv;
TextView gitUrlTv;
ImageView profilePicImgV;
TextView gitPicUrlTv;
public DeveloperViewHolder(final View itemView) {
super(itemView);
gitNameTv = (TextView) itemView.findViewById(R.id.developerName);
gitUrlTv = (TextView) itemView.findViewById(R.id.developerUrl);
profilePicImgV = (ImageView) itemView.findViewById(R.id.developerPic);
gitPicUrlTv = (TextView) itemView.findViewById(R.id.developerPicUrl);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent i = new Intent(itemView.getContext(), Profile.class);
i.putExtra("profile_name", gitNameTv.getText().toString());
i.putExtra("profile_url", gitUrlTv.getText().toString());
i.putExtra("profile_pic_url", gitPicUrlTv.getText().toString());
v.getContext().startActivity(i);
}
});
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder{
public ProgressBar loadingProgress;
public ProgressViewHolder(View itemView) {
super(itemView);
loadingProgress = (ProgressBar) itemView.findViewById(R.id.loading_progress_bar);
}
}
}
DeveloperList.java
package com.davidshare.githubdevelopers;
import android.app.ProgressDialog;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
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.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.List;
public class DeveloperList extends AppCompatActivity {
List<Developer> developerList;
Developer_RV_Adapter developer_rv_adapter;
Developer developer;
RecyclerView developerRV;
private static final String GIT_BASE_URL = "https://api.github.com/search/users?q=location:";
private static int page = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_developer_list);
developerRV = (RecyclerView) findViewById(R.id.developer_rv);
developerRV.setLayoutManager(new LinearLayoutManager(this));
developerList = new ArrayList<>();
getDevelopersData(prepareQuery("java", "lagos", page));
developer_rv_adapter = new Developer_RV_Adapter(DeveloperList.this, developerList, developerRV);
developerRV.setAdapter(developer_rv_adapter);
developer_rv_adapter.setmOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
developerList.add(null);
developer_rv_adapter.notifyItemInserted(developerList.size()-1);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
developerList.remove(developerList.size()-1);
developer_rv_adapter.notifyItemRemoved(developerList.size());
getDevelopersData(prepareQuery("java", "lagos", page));
developer_rv_adapter.notifyDataSetChanged();
developer_rv_adapter.setLoaded();
}
}, 5000);
}
});
}
the getDevelopersData method uses volley to query the github api and parse the JSON response into a List
public void getDevelopersData(String requestUrl) {
StringRequest jsonSringRequest = new StringRequest(Request.Method.GET, requestUrl, new Response.Listener<String>() {
#Override
public void onResponse(String jsonResponse) {
try {
JSONObject gitJSONOBject = new JSONObject(jsonResponse);
JSONArray gitItemsArray = gitJSONOBject.getJSONArray("items");
for (int i = 0; i < gitItemsArray.length(); i++) {
JSONObject developerObject = gitItemsArray.getJSONObject(i);
developer = new Developer(developerObject.getString("login"),
developerObject.getString("html_url"),
developerObject.getString("avatar_url"));
developerList.add(developer);
Log.w("developer_data ", developer.getGitUsername());
}
Log.w("JSON DATA", "getting the json data");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("Volley error", volleyError.getMessage());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonSringRequest);
}
//get the location and language and the page of the api data you want to load
private String prepareQuery(String language, String location, int page){
this.page++;
String queryUrl = GIT_BASE_URL+location+"+language:"+language+"&page="+page+"&per_page=50";
Log.w("Query URL = > ", queryUrl);
return queryUrl;
}
}
Can anyone help me with this?
try to notify adapter in getDevelopersData() after data add to array list like add this line developer_rv_adapter.notifyDataSetChanged();
Instead of notifyItemInserted() inserted use
notifyItemRangedChanged(fromIndex,toIndex);
This will notify the adapter that some set of data is changed among the whole data and it tells the adapter that adapter should refresh the data and reload it into the recyclerView starting from fromIndex to toIndex as passed into the method.
If all data are changed then use :
notifyDataSetChanged();
if only one dataItem is changed then use :
notifyItemChanged(dataPosition);
Also I think this statment is causing problem.Try to remove this statment and check again.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
developerList.remove(developerList.size()-1);
developer_rv_adapter.notifyItemRemoved(developerList.size());
getDevelopersData(prepareQuery("java", "lagos", page));
developer_rv_adapter.notifyDataSetChanged();
developer_rv_adapter.setLoaded();
}
}, 5000);
The problem was resolved by just adding developer_rv_adapter.notifyDataSetChanged(); just below developerList.add(developer); this notifies the adapter that new items have been added to the list.
When i tap search donor then it shows blank screen in listview i don't know why This is the response that i get back from server
This is my custom adapter code:
package com.example.kamran.ebloodbank;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by Kamran on 4/12/2017.
*/
public class DonorAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<DataSet> donorItems;
public DonorAdapter(Activity activity,List<DataSet> donorItems) {
this.activity = activity;
this.donorItems = donorItems;
}
#Override
public int getCount() {
return donorItems.size();
}
#Override
public Object getItem(int location) {
return donorItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.donor_search_list_theme, null);
TextView nameTextView = (TextView) convertView.findViewById(R.id.donor_name);
TextView areaTextView = (TextView) convertView.findViewById(R.id.donor_area);
DataSet d = donorItems.get(position);
nameTextView.setText(d.getName());
areaTextView.setText(d.getArea());
return convertView;
}
}
This is my model code:
package com.example.kamran.ebloodbank;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
/**
* Created by Kamran on 4/12/2017.
*/
public class DataSet {
private String name;
private int area;
public void setArea(int area) {
this.area = area;
}
public void setName(String name) {
this.name = name;
}
public int getArea() {
return area;
}
public String getName() {
return name;
}
}
This is my first activity code:
package com.example.kamran.ebloodbank;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import com.android.volley.AuthFailureError;
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.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.kamran.ebloodbank.data.BloodContract.BloodEntry;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FindDonor extends AppCompatActivity {
Spinner bloodgroup;
Spinner area;
String findDonorUrl = "https://wwwkamranalitk.000webhostapp.com/findDonor.php";
int mBlood = BloodEntry.BLOOD_GROUP_A_POS;
int mArea = BloodEntry.DONOR_AREA_MALIR;
Button searchButton;
RequestQueue requestQueue;
StringRequest request;
JSONObject jsonObject;
JSONArray result;
private List<DataSet> donorList = new ArrayList<DataSet>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_donor);
bloodgroup = (Spinner) findViewById(R.id.bloodspinnerfinddonor);
area = (Spinner) findViewById(R.id.areaSpinner);
searchButton = (Button) findViewById(R.id.searchDonor);
setupSpinnerBlood();
setupSpinnerArea();
requestQueue = Volley.newRequestQueue(getApplicationContext());
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request = new StringRequest(Request.Method.POST, findDonorUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
jsonObject = new JSONObject(response);
result = jsonObject.getJSONArray("result");
JSONObject donorData = result.getJSONObject(0);
DataSet donorSet = new DataSet();
donorSet.setName(donorData.getString("name"));
donorSet.setArea(donorData.getInt("area"));
donorList.add(donorSet);
Intent intent = new Intent(FindDonor.this, DonorSearchList.class);
startActivity(intent);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> parameters = new HashMap<String, String>();
parameters.put("bloodgroup", String.valueOf(mBlood));
parameters.put("area", String.valueOf(mArea));
return parameters;
}
};
requestQueue.add(request);
}
});
}
private void setupSpinnerBlood() {
ArrayAdapter bloodGroupSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.blood_group, android.R.layout.simple_spinner_item);
bloodGroupSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
bloodgroup.setAdapter(bloodGroupSpinnerAdapter);
bloodgroup.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.blood_apos))) {
mBlood = BloodEntry.BLOOD_GROUP_A_POS;
} else if (selection.equals((getString(R.string.blood_bpos)))) {
mBlood = BloodEntry.BLOOD_GROUP_B_POS;
} else if (selection.equals(getString(R.string.blood_opos))) {
mBlood = BloodEntry.BLOOD_GROUP_O_POS;
} else if (selection.equals((getString(R.string.blood_oneg)))) {
mBlood = BloodEntry.BLOOD_GROUP_O_NEG;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
mBlood = BloodEntry.BLOOD_GROUP_A_POS;
}
});
}
private void setupSpinnerArea() {
ArrayAdapter areaSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.area, android.R.layout.simple_spinner_item);
areaSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
area.setAdapter(areaSpinnerAdapter);
area.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.donor_area_malir))) {
mArea = BloodEntry.DONOR_AREA_MALIR;
} else if (selection.equals(getString(R.string.donor_area_defence))) {
mArea = BloodEntry.DONOR_AREA_DEFENCE;
} else if (selection.equals(getString(R.string.donor_area_korangi))) {
mArea = BloodEntry.DONOR_AREA_KORANGI;
} else if (selection.equals(getString(R.string.donor_area_johar))) {
mArea = BloodEntry.DONOR_AREA_JOHAR;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
mArea = BloodEntry.DONOR_AREA_MALIR;
}
});
}
}
and This is the code in which data will be shown:
package com.example.kamran.ebloodbank;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DonorSearchList extends AppCompatActivity {
private String mArea;
private List<DataSet> donorList = new ArrayList<DataSet>();
private ListView listView;
private DonorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_donor_search_list);
listView = (ListView) findViewById(R.id.donorListView);
adapter = new DonorAdapter(this, donorList);
listView.setAdapter(adapter);
}
}
You need to transfer data from the search to list activity.
Try something like this:
public class bridge {
public static List<DataSet> donorList = new ArrayList<DataSet>();
}
Then, in the class FindDonor:
donorSet.setName(donorData.getString("name"));
donorSet.setArea(donorData.getInt("area"));
donorList.add(donorSet);
//here put this line
bridge.donarList = donarList;
//rest code
Intent intent = new Intent(FindDonor.this, DonorSearchList.class);
Then, in the DonorSearchList class:
adapter = new DonorAdapter(this, bridge.donorList);
Excuse me i already had an Application which Display my Sites articles and Novels in Android the codes in Main Activity to display only one Section
i create in the site 5 sections every section had a different content
i Added items to Navigation Drawers and i defined the fragment and its connectivity but the Problem in the Code i failed so
i want to know how to load Data in 4 Fragments
RecyclerViewAdapter.class
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private int previousPosition = 0;
private List<com.salim3dd.recyclerview_moredata.List_Item> List_Item;
private Context context;
public RecyclerViewAdapter(List<List_Item> list_Item, Context context) {
List_Item = list_Item;
this.context = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View menu1 = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.row_item, viewGroup, false);
return new MenuItemViewHolder(menu1);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
MenuItemViewHolder menuItemHolder = (MenuItemViewHolder) holder;
menuItemHolder.TextName.setText(List_Item.get(position).getStory());
Picasso.with(context).load(List_Item.get(position).getImg_link()).into(menuItemHolder.imageView);
menuItemHolder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, List_Item.get(position).getStory(), Toast.LENGTH_SHORT).show();
}
});
if (position > previousPosition) { //scrolling DOWN
AnimationUtil.animate(menuItemHolder, true);
} else { // scrolling UP
AnimationUtil.animate(menuItemHolder, false);
}
previousPosition = position;
}
#Override
public int getItemCount() {
return (null != List_Item ? List_Item.size() : 0);
}
protected class MenuItemViewHolder extends RecyclerView.ViewHolder {
private CardView cardView;
private ImageView imageView;
private TextView TextName;
public MenuItemViewHolder(View view) {
super(view);
cardView = (CardView) view.findViewById(R.id.cardView);
imageView = (ImageView) view.findViewById(R.id.imageView);
TextName = (TextView) view.findViewById(R.id.TextName);
}
}
}
MainActivity
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
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.StringRequest;
import com.android.volley.toolbox.Volley;
import com.salim3dd.recyclerview_moredata.CheckInternetConnection;
import com.salim3dd.recyclerview_moredata.List_Item;
import com.salim3dd.recyclerview_moredata.R;
import com.salim3dd.recyclerview_moredata.RecyclerViewAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerView_dAdapter;
public List<List_Item> listItem = new ArrayList<>();
private GridLayoutManager gridLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.m_RecyclerView);
recyclerView.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(this, 1);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView_dAdapter = new RecyclerViewAdapter(listItem, this);
recyclerView.setAdapter(recyclerView_dAdapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (gridLayoutManager.findLastCompletelyVisibleItemPosition() == listItem.size() - 1) {
Get_All_Users(listItem.get(listItem.size()-1).getId());
}
}
});
Get_All_Users(0);
}
public void Get_All_Users(int limit) {
CheckInternetConnection cic = new CheckInternetConnection(getApplicationContext());
Boolean Ch = cic.isConnectingToInternet();
if (!Ch) {
Toast.makeText(this, R.string.no_internet_connection, Toast.LENGTH_SHORT).show();
} else {
StringRequest stringRequest = new StringRequest(Request.Method.GET,
"Data Link" + limit
,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonResponse = jsonArray.getJSONObject(0);
JSONArray jsonArray_usersS = jsonResponse.getJSONArray("All_storys");
for (int i = 0; i < jsonArray_usersS.length(); i++) {
JSONObject responsS = jsonArray_usersS.getJSONObject(i);
int id = responsS.getInt("id");
String story = responsS.getString("story_name");
String img_link = responsS.getString("img_link");
listItem.add(new List_Item(id, story, img_link));
}
recyclerView_dAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringRequest);
stringRequest.setShouldCache(false);
}
}
}
List Items.class
public class List_Item {
public int id;
public String story;
public String img_link;
public List_Item(int id, String story, String img_link) {
this.id = id;
this.story = story;
this.img_link = img_link;
}
public int getId() {
return id;
}
public String getStory() {
return story;
}
public String getImg_link() {
return img_link;
}
public void setId(int id) {
this.id = id;
}
}