I have a recyclerview that populate the json data which is coming from an api.
Here are the items in each recylerview item project_id,title,etc, with each recyclerview i have checkbox associated with it.
Here is the code for populating the data in recyclerview.
for (int j = 0, count = data.length(); j < count; j++) {
String name = json.getString(TAG_PROJECT_ID);
PROJECT_ID.add(name);
Log.e("array id added",name);
String name1 = json.getString(TAG_PROJECT_TITLE);
PROJECT_TITLE.add(name1);
}
when click on the checkbox on each recyclerviewitem i want to get the project_id of the corresponding item.
//click listener
mCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//GET THE PROJECT ID
}
)}
UPDATED THE ACTUAL CODE
(for simplicity ,i had added only relevant code here )
My Recyclerview adapter
public class FavouriteManager extends RecyclerView.Adapter<FavouriteManager.RecyclerViewHolder> {
ArrayList<String> PROJECT_ID;
ArrayList<String> PROJECT_TITLE;
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
v1 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recyclerview_item, viewGroup, false);
return new RecyclerViewHolder(v1);
}
#Override
public void onBindViewHolder(final RecyclerViewHolder viewHolder, int i) {
projecttitle = PROJECT_TITLE.get(i);
viewHolder.mProjectName.setText(projecttitle);
#Override
public int getItemCount() {
SharedPreferences pref = getContext().getSharedPreferences("MirSP", Context.MODE_PRIVATE);
set = pref.getStringSet("FAV", null);
if (set != null) {
selected = new ArrayList<String>(set);
Log.e("Item Added", "");
} else {
selected = new ArrayList<String>();
}
Length = selected.size();
if (Length == 0) {
RelativeLayout IMG = (RelativeLayout) getActivity().findViewById(R.id.fav_img);
IMG.setVisibility(View.VISIBLE);
}
return Length;
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView mProjectName;
CheckBox mCheck;
RecyclerViewHolder(final View itemView) {
super(itemView);
mProjectName = (TextView) itemView.findViewById(R.id.PROJECT_name);
mCheck = (CheckBox) itemView.findViewById(R.id.PROJECT_fav);
mCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int h = getAdapterPosition();
if (!offlinejson.equals("")) {
try {
JSONObject jsonObject = new JSONObject(offlinejson);
JSONArray data = jsonObject.getJSONArray(TAG_DATA);
JSONObject jsondata = data.getJSONObject(h);
Log.e("getCheckedPos(getID)", String.valueOf(jsondata));
check = PROJECT_ID.get(h);
Log.e("getCheckedPos(getID)", String.valueOf(jsondata));
if (selected.contains(check)) {
selected.remove(check);
mCheck.setBackgroundResource(R.drawable.ic_favorite_white1_24dp);
Snackbar snackbar = Snackbar.make(v, "Property Unfavorited", Snackbar.LENGTH_SHORT);
snackbar.show();
notifyItemRemoved(h);
Log.e("FOUND","found");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
try {
JSONObject jsonObject = new JSONObject(offlinejson);
JSONArray data = jsonObject.getJSONArray(TAG_DATA);
PROJECT_ID = new ArrayList<String>();
PROJECT_TITLE = new ArrayList<String>();
for (int j = 0, count = data.length(); j < count; j++) {
json = data.getJSONObject(j);
//JSONArray jsonArray = new JSONArray(json);
// Log.e("JSON", String.valueOf(json));
if (selected.contains(String.valueOf(json.get(TAG_PROJECT_ID)))) {
try {
String name = json.getString(TAG_PROJECT_ID);
PROJECT_ID.add(name);
Log.e("array id added",name);
String name1 = json.getString(TAG_PROJECT_TITLE);
PROJECT_TITLE.add(name1);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
Note:
I don't want use getAdapterPosition() method because its not applicable with my json structure.
Among different types of solutions, you can also use setTag() and getTag().
Set your project id in to checkbox and get when required.
Eg: mCheck.setTag(); //(key,value) or (value).
For getting ID use getTag() and to set ID use setTag().
http://developer.android.com/reference/android/widget/CheckBox.html
Related
//MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String JSON_URL = "http://kedaiagan.000webhostapp.com/kedaiagan/kedaiagan/menus.php";
List menusList;
ListView listView;
private Button btnKirimPesan;
EditText nomeja;
AlertDialog.Builder builder;
JSONArray jsonArray = new JSONArray();
//initializing objects
private void inisialisasi(){
listView = (ListView) findViewById(R.id.listview);
menusList = new ArrayList<>();
btnKirimPesan= (Button) findViewById(R.id.btnKirimPesan);
nomeja = (EditText) findViewById(R.id.input_meja);
builder = new AlertDialog.Builder(MainActivity.this);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inisialisasi();
//this method will fetch and parse the data
loadMenuList();
btnKirimPesan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i < listView.getCount(); i++) {
View v = getViewByPosition(i, listView);
String id_menu = ((TextView) v.findViewById(R.id.textViewIdMenu)).getText().toString();
String ket_menu = ((EditText) v.findViewById(R.id.textKeterangan)).getText().toString();
String qty_menu = ((EditText) v.findViewById(R.id.textQuantity)).getText().toString();
JSONObject pesanan = new JSONObject();
try {
if(!qty_menu.equals("")) {
if (Integer.valueOf(qty_menu) >= 1) {
pesanan.put("id_menu", id_menu);
pesanan.put("keterangan", ket_menu);
pesanan.put("jumlah_porsi", qty_menu);
jsonArray.put(pesanan);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String url = "http://kedaiagan.000webhostapp.com/kedaiagan/kedaiagan/insertpesanan.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
builder.setTitle("Pesanan Terkirim");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
nomeja.setText("");
Intent intent = new Intent(MainActivity.this, HalUtama.class);
startActivity(intent);
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(MainActivity.this, volleyError.toString(), Toast.LENGTH_LONG).show();
volleyError.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("nomeja", nomeja.getText().toString());
params.put("pesanan", jsonArray.toString());
return params;
}
};
Process.getInstance(MainActivity.this).addTorequestque(stringRequest);
}
public View getViewByPosition(int position, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;
if (position < firstListItemPosition || position > lastListItemPosition ) {
return listView.getAdapter().getView(position, listView.getChildAt(position), listView);
} else {
final int childIndex = position - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}
});
}
public void getTotalHeightofListView() {
ListAdapter mAdapter = listView.getAdapter();
int totalHeight = 0;
int height = 0;
for (int i = 0; i < mAdapter.getCount(); i++) {
View mView = mAdapter.getView(i, null, listView);
mView.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
height = mView.getMeasuredHeight();
totalHeight += mView.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (mAdapter.getCount() - 1))
+ height;
Log.i("Height", "" + totalHeight);
listView.setLayoutParams(params);
listView.requestLayout();
}
private void loadMenuList() {
//getting the progressbar
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
//making the progressbar visible
progressBar.setVisibility(View.VISIBLE);
//creating a string request to send request to the url
StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
//we have the array named hero inside the object
//so here we are getting that json array
JSONArray menuArray = obj.getJSONArray("menus");
//now looping through all the elements of the json array
for (int i = 0; i < menuArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject menuObject = menuArray.getJSONObject(i);
//creating a hero object and giving them the values from json object
Menus menu = new Menus(menuObject.getString("nama_menu"), menuObject.getString("id_menu"));
//adding the hero to herolist
menusList.add(menu);
}
//creating custom adapter object
final MyListAdapter adapter = new MyListAdapter(menusList, getApplicationContext());
//adding the adapter to listview
listView.setAdapter(adapter);
getTotalHeightofListView();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("error", error.getMessage());
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(stringRequest);
}
}
//MyListAdapter.java
public class MyListAdapter extends ArrayAdapter<Menus> {
//the hero list that will be displayed
List<Menus> menusList;
//the context object
Context mCtx;
//here we are getting the herolist and context
//so while creating the object of this adapter class we need to give herolist and context
public MyListAdapter(List<Menus> menusList, Context mCtx) {
super(mCtx, R.layout.my_custom_list, menusList);
this.mCtx = mCtx;
this.menusList = menusList;
}
//this method will return the list item
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//getting the layoutinflater
LayoutInflater inflater = LayoutInflater.from(mCtx);
//creating a view with our xml layout
View listViewItem = inflater.inflate(R.layout.my_custom_list, null, true);
//getting text views
TextView textViewName = listViewItem.findViewById(R.id.textViewName);
TextView textViewIdMenu = listViewItem.findViewById(R.id.textViewIdMenu);
//Getting the hero for the specified position
Menus hero = menusList.get(position);
//setting hero values to textviews
textViewName.setText(hero.getNama_menu());
textViewIdMenu.setText(hero.getId_menu());
//returning the listitem
return listViewItem;
}
}
//Menus.java
public class Menus {
String nama_menu;
String id_menu;
public Menus(String nama_menu, String id_menu) {
this.nama_menu = nama_menu;
this.id_menu = id_menu;
}
public String getNama_menu() {
return nama_menu;
}
public String getId_menu() {
return id_menu;
}
}
1. List item
Easy way is that you use GSON to parse JSON string to POJOs and from there you'll get the list of type POJO and from there you can apply required filters on the list to generate a required list.
import java.util.ArrayList;
public class ListHandler{
private ArrayList<POJO_Name> metrics;
public ArrayList<POJO_Name> getMetrics() {
return metrics;
}
public void setMetrics(ArrayList<POJO_Name> metrics) {
this.metrics = metrics;
}
}
This will generate an instance of list that you'll get from parsing the JSON using GSON. And for the parsing process
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
ListHandler handler= gson.fromJson(json_string, POJOName.class);
Just make sure you POJO must be serialized. If you like to create POJO without pain I suggest you to use JSON to POJO.
Now all is done just create a method that will return you a new list after applying conditions over the base list so that you don't mess the base list.
Please help me out to load more data from the server upon scrolling my RecyclerView . Here I have successfully created RecyclerView by loading data from my Mysql server by using volley string request.
Here is my code.
private void populateRecycleView() {
if (Utility.checkNetworkConnection(this)) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Searching...");
progressDialog.setMessage("Searching for the blood donor. Please wait a moment.");
progressDialog.setCancelable(false);
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_DONORS_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONArray jsonArray = new JSONArray(response);
int count = 0;
while (count < jsonArray.length()) {
JSONObject jsonObject = jsonArray.getJSONObject(count);
String firstName = jsonObject.getString("fName");
String secondName = jsonObject.getString("sName");
String email = jsonObject.getString("emailid");
String password = jsonObject.getString("pass");
String mobile = jsonObject.getString("mobile");
String bloodRt = jsonObject.getString("blood");
String age = jsonObject.getString("age");
String gender = jsonObject.getString("gender");
String country = jsonObject.getString("country");
String location = jsonObject.getString("location");
String latitude = jsonObject.getString("latitude");
String longitude = jsonObject.getString("longitude");
String profilePicFIleName = jsonObject.getString("picname");
String profilePicURL = jsonObject.getString("pic");
Donor donor = new Donor(firstName, secondName, email, password, mobile, bloodRt, age, gender,
country, location, latitude, longitude, profilePicFIleName, profilePicURL);
donorsList.add(donor);
count++;
}
donorsAdapter = new DonorsAdapter(FindDonorResult.this, donorsList);
recyclerView = (RecyclerView) findViewById(R.id.rv_search_result_donor);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(FindDonorResult.this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(donorsAdapter);
donorsAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(FindDonorResult.this, "Active data network is not available.", Toast.LENGTH_LONG).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("bloodGroup", bloodGroup);
return params;
}
};
NetworkRequestSingleTon.getOurInstance(this).addToRequestQue(stringRequest);
} else {
Utility.checkNetworkConnectionFound(this);
}
}
And this is my RecyclerView adapter...
public class DonorsAdapter extends RecyclerView.Adapter<DonorsAdapter.CustomViewHolder> {
private Context context;
private ArrayList<Donor> donorList;
private String bloodGroup;
public DonorsAdapter(Context context, ArrayList<Donor> donorList) {
this.context = context;
this.donorList = donorList;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_blood_donors_result,
parent, false);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
final Donor donor = donorList.get(position);
String displayName = donor.getFirstName() + " " + donor.getSecondName();
holder.tvDisplayName.setText(displayName);
holder.tvEmailID.setText(donor.getEmail());
String userProfileURL = donor.getProfilePicURL();
if (!userProfileURL.equals("")) {
Picasso.with(context).load(userProfileURL).resize(80, 80).centerCrop().
into(holder.ivProfilePic);
} else {
holder.ivProfilePic.setImageResource(R.drawable.ic_person_white_24dp);
}
bloodGroup = donor.getBloodGroup();
if (bloodGroup.equals("A+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_);
else if (bloodGroup.equals("A-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_negative);
else if (bloodGroup.equals("B+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_positive);
else if (bloodGroup.equals("B-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_negative);
else if (bloodGroup.equals("O+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_positive);
else if (bloodGroup.equals("O-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_negative);
else if (bloodGroup.equals("AB+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_positive);
else if (bloodGroup.equals("AB-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_negative);
if(Utility.isNetworkEnabled){
holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, DisplayDonorDetails.class);
intent.putExtra("donor", donor);
context.startActivity(intent);
}
});
}else {
Toast.makeText(context, "Network not available.", Toast.LENGTH_SHORT).show();
}
}
#Override
public int getItemCount() {
if(donorList != null){
return donorList.size();
}else {
return 0;
}
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
ImageView ivProfilePic, ivBloodTypeDisplay, ivArrow;
TextView tvDisplayName;
TextView tvEmailID;
ConstraintLayout constraintLayout;
public CustomViewHolder(View itemView) {
super(itemView);
ivProfilePic = (ImageView) itemView.findViewById(R.id.civ_user_profile_picture);
ivBloodTypeDisplay = (ImageView) itemView.findViewById(R.id.civ_user_blood_type_display);
ivArrow = (ImageView) itemView.findViewById(R.id.civ_arrow);
tvDisplayName = (TextView) itemView.findViewById(R.id.tvUserNameOnRV);
tvEmailID = (TextView) itemView.findViewById(R.id.tvEmailDisplayOnRV);
constraintLayout = (ConstraintLayout) itemView.findViewById(R.id.recycle_view_item_container);
}
}
}
Populate your donorsAdapter only with the 50 first elements of your donorsList, create a function that save the position of the latest element displayed and add other 50 donors to your adapter starting from the latest position saved when you need it.
Hope it helps.
EDIT
First create an emptyList:
List<Donor> subElements = new ArrayList<>();
and pass it to your adapter:
donorsAdapter = new DonorsAdapter(FindDonorResult.this, subElements);
Now you can create a method like this (you can call in onClick event for example):
private int LAST_POSITION = 0;
private int DONORS_NUM_TOSHOW = 50;
public void showMoreDonors(){
if(donarsList.size() > Last_postion+50){
List<Donor> tempList = new ArrayList<Donor>(donorsList.subList(Last_postion,Last_postion+DONORS_NUM_TOSHOW));
for(Donor a : tempList){
subElements.add(a);
}
Last_postion += DONORS_NUM_TOSHOW;
donorsAdapter.notifyDataSetChanged();
}else{
List<Donor> tempList = new ArrayList<Donor>(donorsList.subList(Last_postion,donorsList.size()));
for(Donor a : tempList){
subElements.add(a);
}
donorsAdapter.notifyDataSetChanged();
}
}
Remember to check when donorsList is over.
I didn't test it, but i hope it is usefull to understand the idea.
Finally, I sort this out. I have got an awesome tutorial from this blog.
http://android-pratap.blogspot.in/2015/06/endless-recyclerview-with-progress-bar.html.
I made some changes to populate the list because my data is on a remote server and by using volley library I fetched the data into the list. Remaining things are same.
I am creating an application with a list that list cards based on the value from the server.
I created a StudentCardArrayAdapter to achieve this and everything works fine. All the data has been populated in card list. also I able to get the values on button click in each card separately.
What I need is on clicking the button it will call a method requestion server for data asynchronously and get a value from the server and according to that value, i need to change the button text in that particular card.
My StudentCardArrayAdapter code:
public class StudentCardArrayAdapter extends ArrayAdapter<StudentCard> {
private static final String TAG = "CardArrayAdapter";
private List<StudentCard> cardList = new ArrayList<StudentCard>();
private Context mContext;
String selected = "0";
PreferenceHelper prefs;
CardViewHolder viewHolder;
View row;
ProgressDialog pd;
static class CardViewHolder {
TextView studentname;
TextView stop;
Button selectbutton;
CircleImageView imageId;
}
public StudentCardArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
this.mContext = context;
prefs = new PreferenceHelper(this.mContext);
pd = new ProgressDialog(this.mContext);
}
#Override
public void add(StudentCard object) {
cardList.add(object);
super.add(object);
}
#Override
public int getCount() {
return this.cardList.size();
}
#Override
public StudentCard getItem(int index) {
return this.cardList.get(index);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.student_card, parent, false);
viewHolder = new CardViewHolder();
viewHolder.studentname = (TextView) row.findViewById(R.id.studentname);
viewHolder.stop = (TextView) row.findViewById(R.id.stop);
viewHolder.selectbutton = (Button) row.findViewById(R.id.selectbutton);
viewHolder.imageId = (CircleImageView) row.findViewById(R.id.imageId);
row.setTag(viewHolder);
} else {
viewHolder = (CardViewHolder)row.getTag();
}
StudentCard card = getItem(position);
viewHolder.studentname.setText(card.getStudName());
viewHolder.studentname.setTextColor(Color.parseColor("#000000"));
viewHolder.stop.setText(card.getStudStop());
viewHolder.stop.setTextColor(Color.parseColor("#000000"));
if(card.getSelected().equals("1")){
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.selected));
viewHolder.selectbutton.setEnabled(false);
}
else{
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.select));
viewHolder.selectbutton.setEnabled(true);
}
final String studid = card.getStudId();
final String busname = prefs.getString("busname", "0");
final String schoolid = prefs.getString("schoolid", "");
viewHolder.selectbutton.setOnClickListener(new View.OnClickListener()
{
String updatedvalue = "0";
#Override
public void onClick(View v)
{
Log.e("studid",studid);
Log.e("busname",busname);
Log.e("schoolid",schoolid);
selectstudent(v, studid, busname, schoolid,mContext);
//Toast.makeText(v.getContext(), amountinfo, Toast.LENGTH_SHORT).show();
/*SnackbarManager.show(Snackbar.with(this) // context
.text(amountinfo));*/
}
});
Picasso.with(mContext).load(card.getImageUrl()).fit().error(R.mipmap.ic_launcher).into(viewHolder.imageId);
return row;
}
public void selectstudent(final View v, String studid, String busname, String schoolid, final Context mContext) {
String returnedselected = "0";
Log.e("BASE_URL_STUDENT_UPDATE", Constants.BASE_URL_STUDENT_UPDATE + "?studid=" + studid+"&busname="+busname+"&schoolid="+schoolid);
RestClientHelper.getInstance().get(Constants.BASE_URL_STUDENT_UPDATE + "?studid=" + studid+"&busname="+busname+"&schoolid="+schoolid, new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
Log.e("RESULT", response);
try {
JSONObject result = new JSONObject(response);
JSONArray posts = result.optJSONArray("status");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String status = post.optString("status");
if (status.equals("true")) {
selected = post.optString("selected");
} else {
selected = post.optString("selected");
String error = post.optString("error");
SnackbarManager.show(Snackbar.with(getContext()) // context
.text(error));
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
} finally {
if(selected.equals("1")){
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.selected));
viewHolder.selectbutton.setEnabled(false);
}
}
}
#Override
public void onError(String error) {
Log.e("error", error);
selected = "0";
}
});
}
}
I used the below code but nothing works.. No error also.. and not change in button text.I get value of selected as 1 from server.
if(selected.equals("1")){
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.selected));
viewHolder.selectbutton.setEnabled(false);
}
I am new to android.. and is stuck here. Please help me out.
FINALLY IT WORKED
As changes mention by Krish, I updated the code suggested by him.
And added this changes in onClick it worked
if(card.getSelected().equals("1")){
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.selected));
viewHolder.selectbutton.setEnabled(false);
}
Change the code like this,
public void selectstudent(StudentCard card, String studid, String busname, String schoolid, final Context mContext) {
String returnedselected = "0";
Log.e("BASE_URL_STUDENT_UPDATE", Constants.BASE_URL_STUDENT_UPDATE + "?studid=" + studid+"&busname="+busname+"&schoolid="+schoolid);
RestClientHelper.getInstance().get(Constants.BASE_URL_STUDENT_UPDATE + "?studid=" + studid+"&busname="+busname+"&schoolid="+schoolid, new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
Log.e("RESULT", response);
try {
JSONObject result = new JSONObject(response);
JSONArray posts = result.optJSONArray("status");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String status = post.optString("status");
if (status.equals("true")) {
selected = post.optString("selected");
} else {
selected = post.optString("selected");
String error = post.optString("error");
SnackbarManager.show(Snackbar.with(getContext()) // context
.text(error));
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
} finally {
if(selected.equals("1")){
card.setSelected("1");
notifyDataSetChanged();
}
}
}
#Override
public void onError(String error) {
Log.e("error", error);
selected = "0";
}
});
}
and change this line like this ,
final StudentCard card = getItem(position);
and call method inside onclick.
selectstudent(card, studid, busname, schoolid,mContext);
I am trying to implement swipe to refresh in my app. When swipe to refresh is triggered, first all the data is fetched from JSON and then stored in the database. After storing the data, all the new data will be added to the top of the recyclerview. I read a few articles and only managed to find out about adding a single item at the top of the list. But in the case of my app, where more than one item may be available to show, what should I do?
Here is my code for the database table where first new post is fetched with the last post id which is shown in recyclerview:
#Override
public ArrayList<Post> getAllNewPost(int T) {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Post> postList = null;
try {
postList = new ArrayList<Post>();
String QUERY = "SELECT * FROM " + TABLE_NAME + " INNER JOIN "+TABLE_FOLLOWER+
" ON post_table.user_id = follower.user_id WHERE follower.follow = '1' AND post_table.post_id > "+T+" ORDER BY "+POST_ID+" DESC";
Cursor cursor = db.rawQuery(QUERY, null);
if (!cursor.isLast()) {
while (cursor.moveToNext()) {
Post post = new Post();
post.setPost_id(cursor.getString(0));
Log.d("post_id",cursor.getString(0));
post.setUser_id(cursor.getString(1));
post.setUser_name(cursor.getString(2));
post.setImg_link(cursor.getString(3));
post.setPost_title(cursor.getString(4));
post.setPost_cat(cursor.getString(6));
post.setPost_time(cursor.getString(8));
postList.add(post);
}
}
db.close();
} catch (Exception e) {
Log.e("error", e + "");
}
return postList;
}
Here is array adapter of recyclerview:
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
Context context;
ArrayList<Post> listData = new ArrayList<>();
String rpostid,ruserid,rname,rcat,rdate,rtittle,urlThumnail;
private VolleySingleton volleySingleton;
ImageLoader imageLoader = VolleySingleton.getsInstance().getImageLoad();
public PostAdapter(ArrayList<Post> postList) {
this.listData=postList;
}
public PostAdapter(Context context){
this.context = context;
}
#Override
public PostAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.post_item, viewGroup, false);
return new posts(v);
}
public class posts extends ViewHolder {
TextView tvTittle,tvPostId,tvUseId,tvName,tvCat,tvDate;
ImageView row_img;
public posts(View v) {
super(v);
tvTittle = (TextView) v.findViewById(R.id.row_cmnt);
tvPostId = (TextView) v.findViewById(R.id.row_postid);
tvUseId = (TextView) v.findViewById(R.id.row_userid);
tvName = (TextView) v.findViewById(R.id.row_name);
tvCat = (TextView) v.findViewById(R.id.row_cat);
tvDate = (TextView) v.findViewById(R.id.row_date);
row_img = (ImageView) v.findViewById(R.id.row_img);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
TextView text = (TextView) v.findViewById(R.id.row_postid);
String lst_txt = text.getText().toString().trim();
intent = new Intent(v.getContext(), PostView.class);
intent.putExtra("post_id", lst_txt);
v.getContext().startActivity(intent);
}
});
}
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
final posts holder = (posts) viewHolder;
Post post = listData.get(position);
rpostid = post.getPost_id();
ruserid = post.getUser_id();
rname = post.getUser_name();
rcat = post.getPost_cat();
rdate = post.getPost_time();
rtittle = post.getPost_title();
holder.tvPostId.setText(rpostid);
holder.tvUseId.setText(ruserid);
holder.tvName.setText(rname);
holder.tvCat.setText(rcat);
holder.tvDate.setText(rdate);
holder.tvTittle.setText(rtittle);
urlThumnail = post.getImg_link();
Log.d("qwerty","link of image lru: "+ urlThumnail);
if (urlThumnail != null){
imageLoader.get(urlThumnail, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.row_img.setImageBitmap(response.getBitmap());
Log.d("qwerty","post attached 2");
}
#Override
public void onErrorResponse(VolleyError error) {
Log.d("qwerty","post attached 3");
}
});
}
}
#Override
public int getItemCount() {
return (null != listData ? listData.size() : 0);
}
}
And here is the code by which all the new posts will be fetched from the DB:
private ArrayList<Post> parseJSONResponse(JSONObject response) {
if (response == null || response.length() == 0) {
} else {
try {
JSONArray jsonArray = response.getJSONArray("post");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectPOST = jsonArray.getJSONObject(i);
String post_id = jsonObjectPOST.getString(Key_post_id);
String user_id = jsonObjectPOST.getString(Key_user_id);
String user_name = jsonObjectPOST.getString(Key_user_name);
String img_link = jsonObjectPOST.getString(Key_img_link);
String post_title = jsonObjectPOST.getString(Key_post_title);
String post_desc = jsonObjectPOST.getString(Key_post_desc);
String post_exp_date = jsonObjectPOST.getString(Key_post_exp);
String post_cat = jsonObjectPOST.getString(Key_post_cat);
String post_time = jsonObjectPOST.getString(Key_post_time);
Log.d("response",post_id+" "+user_id+" "+user_name+" "+img_link);
Post postitem = new Post();
postitem.setPost_id(post_id);
postitem.setUser_id(user_id);
postitem.setUser_name(user_name);
postitem.setImg_link(img_link);
postitem.setPost_title(post_title);
postitem.setDesc(post_desc);
postitem.setEXP(post_exp_date);
postitem.setPost_cat(post_cat);
postitem.setPost_time(post_time);
if(jsonObjectPOST.has(Key_post_id) &&
jsonObjectPOST.has(Key_user_id) &&
jsonObjectPOST.has(Key_user_name) &&
jsonObjectPOST.has(Key_img_link) &&
jsonObjectPOST.has(Key_post_title) &&
jsonObjectPOST.has(Key_post_desc) &&
jsonObjectPOST.has(Key_post_exp) &&
jsonObjectPOST.has(Key_post_cat) &&
jsonObjectPOST.has(Key_post_time)){
if(!jsonObjectPOST.isNull(Key_post_id) &&
!jsonObjectPOST.isNull(Key_user_id) &&
!jsonObjectPOST.isNull(Key_user_name) &&
!jsonObjectPOST.isNull(Key_img_link) &&
!jsonObjectPOST.isNull(Key_post_title) &&
!jsonObjectPOST.isNull(Key_post_desc) &&
!jsonObjectPOST.isNull(Key_post_exp) &&
!jsonObjectPOST.isNull(Key_post_cat) &&
!jsonObjectPOST.isNull(Key_post_time)){
handler.addPost(postitem);
new CountDownTimer(2000, 1000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
postList = handler.getAllPost();
t = Integer.parseInt(postList.get(1).getPost_id().toString().trim());
Log.d("Check", "postid: "+t);
Hpbar.setVisibility(View.INVISIBLE);
Log.d("jsonCount", String.valueOf(postList));
String AdapterData = String.valueOf(postList);
if(AdapterData.equals("[]")){
Htvnopostfound.setVisibility(View.VISIBLE);
}else{
adapter = new PostAdapter(postList);
listView.setAdapter(adapter);
}
}
}.start();
}else{
}
}else{
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return postList;
}
private ArrayList<Post> swipeJSONResponse(JSONObject response) {
if (response == null || response.length() == 0) {
} else {
try {
JSONArray jsonArray = response.getJSONArray("post");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectPOST = jsonArray.getJSONObject(i);
String post_id = jsonObjectPOST.getString(Key_post_id);
String user_id = jsonObjectPOST.getString(Key_user_id);
String user_name = jsonObjectPOST.getString(Key_user_name);
String img_link = jsonObjectPOST.getString(Key_img_link);
String post_title = jsonObjectPOST.getString(Key_post_title);
String post_desc = jsonObjectPOST.getString(Key_post_desc);
String post_exp_date = jsonObjectPOST.getString(Key_post_exp);
String post_cat = jsonObjectPOST.getString(Key_post_cat);
String post_time = jsonObjectPOST.getString(Key_post_time);
Post postitem = new Post();
postitem.setPost_id(post_id);
postitem.setUser_id(user_id);
postitem.setUser_name(user_name);
postitem.setImg_link(img_link);
postitem.setPost_title(post_title);
postitem.setDesc(post_desc);
postitem.setEXP(post_exp_date);
postitem.setPost_cat(post_cat);
postitem.setPost_time(post_time);
if(jsonObjectPOST.has(Key_post_id) &&
jsonObjectPOST.has(Key_user_id) &&
jsonObjectPOST.has(Key_user_name) &&
jsonObjectPOST.has(Key_img_link) &&
jsonObjectPOST.has(Key_post_title) &&
jsonObjectPOST.has(Key_post_desc) &&
jsonObjectPOST.has(Key_post_exp) &&
jsonObjectPOST.has(Key_post_cat) &&
jsonObjectPOST.has(Key_post_time)){
if(!jsonObjectPOST.isNull(Key_post_id) &&
!jsonObjectPOST.isNull(Key_user_id) &&
!jsonObjectPOST.isNull(Key_user_name) &&
!jsonObjectPOST.isNull(Key_img_link) &&
!jsonObjectPOST.isNull(Key_post_title) &&
!jsonObjectPOST.isNull(Key_post_desc) &&
!jsonObjectPOST.isNull(Key_post_exp) &&
!jsonObjectPOST.isNull(Key_post_cat) &&
!jsonObjectPOST.isNull(Key_post_time)){
handler.addPost(postitem);
new CountDownTimer(2000, 1000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
postList = handler.getAllNewPost(t);
adapter.notifyItemInserted(1);
Log.d("check","post_id "+t+" hello");
/*adapter = new PostAdapter(postList);
listView.setAdapter(adapter);
Log.d("check","post_id "+t+" hello 2");*/
Log.d("check","post_id "+t+" hello 2");
Hpbar.setVisibility(View.INVISIBLE);
swipeRefreshLayout.setRefreshing(false);
}
}.start();
}else{
}
}else{
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return postList;
}
On startup parseJSONResponse is used and for swipeToRefresh swipeJSONResponse is used. In parseJSONResponse, the last displayed post's id is stored in int t and then this int t is passed to swipeJSONResponse to get the new post.
But after refreshing, new data will not show in the list. SO, please tell me how to do so. I've read a few articles where add is used, as such:
listview.add(0, item);
But I don't know how to implement this with multiple rows of data at same time. Thanks in advance.
The correct way to update data in a listView should be:
1) create an update data method in your adapter. In your case could be like this:
public updateData(ArrayList<Post> postList) {
this.listData=postList;
notifyDataSetChanged();
}
or, if you want just append data on the top:
public addNewDataOnTop(ArrayList<Post> postList) {
this.listData.addAll(0,postList);
notifyDataSetChanged();
}
2) When you have new data to add, do not create a new adapter but just update the data
When you create the listView at the beginning you set the empty adapter:
adapter = new PostAdapter(new ArrayList());
listView.setAdapter(adapter);
When you receive the new data, you just update the adapter:
adapter.addNewDataOnTop(postList);
I hope it helped
I would insert each item at the top using:
mArrayList.add(0, item1);
notifyItemInserted(0);
mArrayList.add(0, item2);
notifyItemInserted(0);
Do the following for all your items.
this is my custom adapter i use it for first time its work without repeat
public class MessageAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<MessageList> MessageList;
private final Context context;
public MessageAdapter(Activity activity, List<MessageList> MessageList, Context c) {
this.activity = activity;
this.MessageList = MessageList;
this.context = c;
}
#Override
public int getCount() {
return MessageList.size();
}
#Override
public Object getItem(int location) {
return MessageList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder mHolder;
final MessageList m = MessageList.get(position);
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
if (m.getDir().equals("left")) {
convertView = inflater.inflate(R.layout.left_message, null);
} else if (m.getDir().equals("right")) {
convertView = inflater.inflate(R.layout.right_message, null);
}
mHolder = new ViewHolder();
mHolder.message = (LinearLayout) convertView.findViewById(R.id.messages);
convertView.setTag(mHolder);
for(String message : m.getMessageList()){
TextView text = new MyTextView(activity);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
p.setMargins(0, 0, 0, 2);
text.setLayoutParams(p);
text.setText(message);
text.setPadding(8,8,8,8);
text.setTextSize(14f);
}
}
else {
mHolder = (ViewHolder) convertView.getTag();
}
Log.d("ffffffffffffffffff",""+m.getMessageList().size());
return convertView;
}
private class ViewHolder {
private LinearLayout message;
}
}
this is the result
but when i receive new data and i want to add it after do
adapter.notifyDataSetChanged();
its repeat the first data and add it to listView see result
we can see its repeat the data it must add new data i add it to arrayList not repeat old item on it i am sure about my ArrayList its right
at the end just lets see ho9w i add new data
first when its work without problem
private List<MessageList> Message_List = new ArrayList<MessageList>();
adapter = new MessageAdapter(this, Message_List, getApplicationContext());
message_list.setAdapter(adapter);
now i will add data for the first time
try {
JSONArray jsonarray = new JSONArray(data);
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject jsonobject = jsonarray.getJSONObject(i);
MessageList messageList = new MessageList();
String fname = jsonobject.getString("Fname");
int user_id = jsonobject.getInt("user_id");
String message = jsonobject.getString("message");
String date = jsonobject.getString("date");
String direction = jsonobject.getString("direction");
JSONArray MessageArry = jsonobject.getJSONArray("message");
ArrayList<String> ListMessage = new ArrayList<String>();
for (int j = 0; j < MessageArry.length(); j++) {
ListMessage.add((String) MessageArry.get(j));
}
messageList.setUser_id(user_id);
messageList.setMessage(message);
messageList.setDate(date);
messageList.setFname(fname);
messageList.setDir(direction);
messageList.setMessageList(ListMessage);
Message_List.add(messageList);
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
data used its
String data = "[ { \"direction\": \"left\",\"user_id\": \"50\",\"Fname\": \"Mohamed Mohamed\", \"status\": \"online\" , \"m_status\": \"sent\", \"date\": \"9:20\", \"message\": [\"hello\",\"hahhahah ok ok say hello\",\"-_-\",\"where are \",\"u ?\"] }, { \"direction\": \"right\",\"user_id\": \"50\",\"Fname\": \"Mustafa Naser\", \"status\": \"online\" , \"m_status\": \"sent\", \"date\": \"10:20\", \"message\": [\"hello\",\"what u want :/\",\"xD\"] }]";
when i get new data and i want to append it i add data like this
try {
JSONObject jsonobject1 = new JSONObject(json);
MessageList messageList = new MessageList();
String fname = jsonobject1.getString("name");
int user_id = jsonobject1.getInt("id");
String message = jsonobject1.getString("message");
String date = jsonobject1.getString("date");
String direction = jsonobject1.getString("direction");
ArrayList<String> ListMessage = new ArrayList<String>();
for (int j = 0; j < 1; j++) {
ListMessage.add(message);
}
messageList.setUser_id(user_id);
messageList.setMessage(message);
messageList.setDate(date);
messageList.setFname(fname);
messageList.setDir(direction);
messageList.setMessageList(ListMessage);
Message_List.add(messageList);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
adapter.notifyDataSetChanged();
data used its
{"message":"qqqqqqqq","id":50,"date":"2016-06-24 04:44:06","name":"medo medo","direction":"left","mode":0}
Each time you create a view, you put all messages inside, regardless of whether you have already shown them.
The problem is with the following loop:
for(String message : m.getMessageList()) {
// add a text view for each message
}
You need to find a way to check if the message has already been shown and add it to the layout only if it's not there.
I suggest you to do as follow:
In your adapterclass add this method:
public void updateList(List<MessageList> ){
this.MessageList = l;
notifyDataSetChanged();
}
And, after you fetch the new List, call the adapter.updateList(newList) method! It will update itself with the notifyDataSetChanged(); inside of the method.