OnBindViewHolder in Android Get ID in Mysql - java

I'm really confused about, How can I get the ID of the specific cardView when I click the check button , I want to get or Toast the id from database it already shown in the image I just want to get that id , but currently when I click the button in first row only the last id return which is the last number 12 instead of 2 need help
RecycleAdapterPending.java
#Override
public void onBindViewHolder(#NonNull MyViewHolderPending holder, #SuppressLint("RecyclerView") int position) {
final AppointmentPending appointment = appointments.get(position);
int id = 0;
int userId =0;
id = Integer.parseInt(appointment.getIdd());
userId = Integer.parseInt(appointment.getUserId());
finalId = id;
int finalUserId = userId;
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String idd = String.valueOf(finalId);
//button to be clickeddd but it the output always `12`
Toast.makeText(mContext.getApplicationContext(), "click me" + idd ,Toast.LENGTH_SHORT).show();
}
});
holder.aptCategory.setText(appointment.getIdd());
holder.aptSubCat.setText(appointment.getSub_cat());
String schedule = appointment.getSchedule();
holder.aptDate.setText(schedule);
}
AppointmentPending.java
package com.example.clinicsys.Appointment.pending;
public class AppointmentPending {
private String idd,userId,category_name, sub_cat, schedule;
public AppointmentPending(String idd,String userId, String category_name, String sub_cat, String schedule){
this.idd = idd;
this.userId = userId;
this.category_name = category_name;
this.sub_cat = sub_cat;
this.schedule = schedule;
}
public String getIdd() {
return idd;
}
public void setIdd(String idd) {
this.idd = idd;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getCategory() {
return category_name;
}
public void setCategory(String category_name) {
this.category_name = category_name;
}
public String getSub_cat() {
return sub_cat;
}
public void setSub_cat(String sub_cat) {
this.sub_cat = sub_cat;
}
public String getSchedule() {
return schedule;
}
public void setSchedule(String schedule) {
this.schedule = schedule;
}
}
Home.java Get data from mysql
StringRequest stringRequest = new StringRequest(Request.Method.GET, BASE_URL+Urltype,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressBar.setVisibility(View.GONE);
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);
String idd = object.getString("id");
String categoryName = object.getString("category");
String subCat = object.getString("subCategory");
String schedule = object.getString("schedule");
String userId = useridd;
AppointmentPending appointment = new AppointmentPending(idd,userId,categoryName,subCat,schedule);
appointments.add(appointment);
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), "catch error " + e, Toast.LENGTH_SHORT).show();
}
mAdapter = new RecyclerAdapterPending(HomePending.this,appointments);
recyclerView.setAdapter(mAdapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(HomePending.this, "Database connection failed " + error.toString(),Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(HomePending.this).add(stringRequest);

Related

How to save like button state in android?

I am using jd-alexander/LikeButton https://github.com/jd-alexander/LikeButton instead of normal buttons in the android app. The code works fine while enabling and disabling switches. But I want to save the state of the like button. Suppose I enable the like button and swap the list the background code will run fine but the like button state will change to unliked.
Every time when I swap the list the like button state becomes unliked. Is there any way to save the like button State??
Activity codes:
public class CollectorListAdapter extends ArrayAdapter<Collector> {
private static final String TAG = "CollectorListAdapter";
private Context mContext;
private int mResource;
public CollectorListAdapter(Context context, int resource, ArrayList<Collector> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
}
public View getView(final int position, View convertView, ViewGroup parent) {
//Get the Shop information
String Shopname = getItem(position).getName();
String Specialoffers = getItem(position).getSpecialoffers();
int Price = getItem(position).getPrice();
final Double startLatitude = getItem(position).getLatitude();
final Double startLongitude = getItem(position).getLongitude();
final String user_id = String.valueOf(getItem(position).getUserid());
final String shop_id = String.valueOf(getItem(position).getShopid());
final String product_id = String.valueOf(getItem(position).getProductid());
//create the view result for showing the animation
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
TextView sname = (TextView) convertView.findViewById(R.id.textView);
TextView tvname = (TextView) convertView.findViewById(R.id.textView7);
TextView Location = (TextView) convertView.findViewById(R.id.textView9);
TextView tvdescription = (TextView) convertView.findViewById(R.id.textView10);
sname.setText(Shopname);
tvdescription.setText(Specialoffers);
tvname.setText(CurrencyFormatting(Integer.toString(Price)) + " EGP");
Location.setText(format(results[0]) + " km");
LikeButton heart;
heart = convertView.findViewById(R.id.favBtn);
heart.setOnLikeListener(new OnLikeListener() {
// Add Data to the Saved Shop Table by like
#Override
public void liked(LikeButton likeButton) {
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.URL_SAVED_SHOPS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", user_id);
params.put("shop_id", shop_id);
params.put("product_id", product_id);
return params;
}
};
Volley.newRequestQueue(getContext()).add(strReq);
Toast.makeText(getContext(),
"Shop Saved Successfully", Toast.LENGTH_LONG).show();
}
// Delete Data to the Saved Shop Table by Unlike
#Override
public void unLiked(LikeButton likeButton) {
StringRequest strReq10 = new StringRequest(Request.Method.POST, AppConfig.URL_Delete_SAVED_SHOPS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", user_id);
params.put("shop_id", shop_id);
params.put("product_id", product_id);
return params;
}
};
Volley.newRequestQueue(getContext()).add(strReq10);
Toast.makeText(getContext(),
"Shop Saved Deleted Successfully", Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
Collector Class:
public class Collector implements java.io.Serializable {
private String specialoffers, name;
private Double latitude, longitude;
private int price,userid,shopid,productid;
public Collector() {
}
//Sorting by Price method
public static Comparator<Collector> PriceSort = new Comparator<Collector>() {
public int compare(Collector s1, Collector s2) {
int rollno1 = s1.getPrice();
int rollno2 = s2.getPrice();
/*For ascending order*/
return rollno1 - rollno2;
/*For descending order*/
//rollno2-rollno1;
}
};
//Sorting by Distance method
public static Comparator<Collector> DistanceSort = new Comparator<Collector>() {
public int compare(Collector s1, Collector s2) {
float[] results1 = new float[3];
Location.distanceBetween(
LocationActivity.currentLocation.getLatitude(),
LocationActivity.currentLocation.getLongitude(),s1.getLatitude(),
s1.getLongitude(),
results1);
float[] results2 = new float[3];
Location.distanceBetween(
LocationActivity.currentLocation.getLatitude(),
LocationActivity.currentLocation.getLongitude(),s2.getLatitude(),
s2.getLongitude(),
results2);
/*For ascending order*/
return Float.compare(results1[0], results2[0]);
/*For descending order*/
//rollno2-rollno1;
}
};
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public int getShopid() {
return shopid;
}
public void setShopid(int shopid) {
this.shopid = shopid;
}
public int getProductid() {
return productid;
}
public void setProductid(int productid) {
this.productid = productid;
}
public String toString() {
return ("Shop Name:" + getName() +
" Price : " + getPrice() +
" SpecialOffers : " + getSpecialoffers() +
" latitude : " + getLatitude()) +
" longitude : " + getLongitude();
}
public String getSpecialoffers() {
return specialoffers;
}
public void setSpecialoffers(String specialoffers) {
this.specialoffers = specialoffers;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
This is the normal behaviour in ArrayAdapter, the whole list gets recreated again so you lose the state of the button. You should save the boolean of the button in the local list variable.
Add a field like isLiked = true/false in the Collector class and update the value at the particular position every time user click like/unlike buttons.

Realm update one object and others instance is also updated

I have Class Orders:
public class Order extends RealmObject {
#PrimaryKey
#SerializedName("Id")
private int id;
#SerializedName("Contractor")
private Contractor contractor;
#SerializedName("ItemAmounts")
private RealmList<ItemAmount> itemsAmounts = new RealmList<>();
#SerializedName("ModificationDate")
private Date modificationDate;
#SerializedName("ExportDate")
private Date exportDate;
#SerializedName("Export")
private boolean exportStatus;
#SerializedName("User")
private User user;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Contractor getContractor() {
return contractor;
}
public void setContractor(Contractor contractor) {
this.contractor = contractor;
}
public RealmList<ItemAmount> getItemsAmounts() {
return itemsAmounts;
}
public void setItemsAmounts(RealmList<ItemAmount> itemsAmounts) {
this.itemsAmounts = itemsAmounts;
}
public Date getModificationDate() {
return modificationDate;
}
public void setModificationDate(Date modificationDate) {
this.modificationDate = modificationDate;
}
public Date getExportDate() {
return exportDate;
}
public void setExportDate(Date exportDate) {
this.exportDate = exportDate;
}
public boolean isExportStatus() {
return exportStatus;
}
public void setExportStatus(boolean exportStatus) {
this.exportStatus = exportStatus;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
And i Create any new order save to Realm:
public void insertOrUpdate(Order order) {
Order orderToCompare = realm.where(Order.class)
.equalTo("id", order.getId()).findFirst();
realm.beginTransaction();
if (orderToCompare == null) {
Order orderRealm = realm.createObject(Order.class, order.getId());
orderRealm.setExportStatus(order.isExportStatus());
orderRealm.setContractor(order.getContractor());
orderRealm.setModificationDate(order.getModificationDate());
} else if (!orderToCompare.equals(order)) {
realm.copyToRealmOrUpdate(order);
}
realm.commitTransaction();
}
All my Orders have List of ItemAmount and ItemAmount have single item(Items is also contains in Realm) and his amount. So when i try change the amount of item in one order all my amount in others ItemAmount is updated. Below its function which I update the amount:
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
itemPosition = position;
AlertDialog.Builder builder = new AlertDialog.Builder(OrderItemsActivity.this);
View mView = getLayoutInflater().inflate(R.layout.change_amount, null);
builder.setView(mView);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
Button changeAmountButton = (Button) mView.findViewById(R.id.changeAmountButton);
final EditText setAmountEditText = (EditText) mView.findViewById(R.id.setAmountEditText);
changeAmountButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (setAmountEditText.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(), "Pole nie może być puste", Toast.LENGTH_SHORT).show();
} else {
orderDAO = new OrderDAO();
orderDAO.updateAmountOfItem(Integer.parseInt(setAmountEditText.getText().toString()), itemPosition, selectedOrderId);
itemAmounts.clear();
alertDialog.dismiss();
prepareOrderData();
}
}
});
}
public void updateAmountOfItem(int amount, int itemPosition, int orderId) {
realm.beginTransaction();
Order orderToCompare = realm.where(Order.class)
.equalTo("id", orderId).findFirst();
orderToCompare = realm.copyFromRealm(orderToCompare);
RealmList<ItemAmount> itemAmounts = orderToCompare.getItemsAmounts();
ItemAmount itemAmount = itemAmounts.get(itemPosition);
itemAmount.setAmount(amount);
itemAmounts.set(itemPosition,itemAmount);
orderToCompare.setItemsAmounts(itemAmounts);
realm.insertOrUpdate(orderToCompare);
realm.commitTransaction();
}
How fix it? Because i need update only one instance, not all of them.

How do you do pojo with asynctask json

I take https://jsonplaceholder.typicode.com/users with asynctask but i take to use pojo object .
What should I add code between ? What line should I write and how should i write ?
DataRetriever.java
public DataRetriever(Activity activity) {
activityWeakReference = new WeakReference<>(activity);
current_activity = activityWeakReference.get();
}
#Override
protected void onPreExecute() {
imageView = (ImageView) current_activity.findViewById(R.id.imageView);
if (current_activity != null) {
recyclerView = (RecyclerView) current_activity.findViewById(R.id.recyclerView);
swipeRefreshLayout = (SwipeRefreshLayout) current_activity.findViewById(R.id.swipe_container);
swipeRefreshLayout.setColorSchemeResources(
android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
recyclerView.setHasFixedSize(true);
} else {
Log.d(TAG, "unable to get current activity");
Toast.makeText(current_activity, "unable to get current activity", Toast.LENGTH_SHORT).show();
}
super.onPreExecute();
progressDialog = new ProgressDialog(current_activity);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#SafeVarargs
#Override
protected final Integer doInBackground(List<String>... integers) {
HttpURLConnection httpURLConnection = null;
URL url;
List<String> local_list = integers[0];
type = Integer.parseInt(local_list.get(0));
String jsonString, jsonData;
return_status = 0;
switch (type) {
case 1:
url_string = "https://jsonplaceholder.typicode.com/users";
break;
case 2:
url_string = "https://jsonplaceholder.typicode.com/albums";
recieved_id = Integer.parseInt(local_list.get(1));
title = local_list.get(2);
break;
case 3:
url_string = "https://jsonplaceholder.typicode.com/photos";
recieved_id = Integer.parseInt(local_list.get(1));
title = local_list.get(2);
break;
}
try {
url = new URL(url_string);
httpURLConnection = (HttpURLConnection) url.openConnection();
int statusCode = httpURLConnection.getResponseCode();
if (statusCode == 200) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
while ((jsonData = bufferedReader.readLine()) != null) {
stringBuilder.append(jsonData);
}
jsonString = stringBuilder.toString();
jsonParser(jsonString);
return_status = 1;
} else {
Log.d(TAG, "Some error occurred could'nt fetch data");
Toast.makeText(current_activity, "Some error occurred could'nt fetch data", Toast.LENGTH_SHORT).show();
return_status = 0;
}
publishProgress(local_list);
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return return_status;
}
private void jsonParser(String jsonString) {
int names_count, id;
String name;
try {
JSONArray jsonArray = new JSONArray(jsonString);
names_count = jsonArray.length();
if (!listValues.isEmpty())
listValues.clear();
if (!pictureValues.isEmpty())
pictureValues.clear();
for (int i = 0; i < names_count; i++) {
JSONObject array_items = jsonArray.getJSONObject(i);
ListValues jsonValues, pictureValue;
switch (type) {
case 1:
id = array_items.optInt("id");
name = array_items.optString("name");
jsonValues = new ListValues(id, name);
listValues.add(jsonValues);
break;
case 2:
id = array_items.optInt("userId");
name = array_items.optString("title");
if (id == recieved_id) {
jsonValues = new ListValues(id, name);
listValues.add(jsonValues);
}
break;
case 3:
id = array_items.optInt("albumId");
name = array_items.optString("title");
String pictureURL = array_items.getString("url");
if (id == recieved_id) {
jsonValues = new ListValues(id, name);
pictureValue = new ListValues(id, pictureURL);
listValues.add(jsonValues);
pictureValues.add(pictureValue);
}
break;
}
}
} catch (JSONException e) {
Log.d(TAG, e.getLocalizedMessage());
}
}
#Override
protected void onProgressUpdate(final List<String>... values) {
List<String> progressList = values[0];
Log.d(TAG, progressList.get(0));
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
switch (type) {
case 1:
new DataRetriever(current_activity).execute(values[0]);
case 2:
new DataRetriever(current_activity).execute(values[0]);
case 3:
new DataRetriever(current_activity).execute(values[0]);
}
}
});
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(final Integer integer) {
if (integer != 0) {
recyclerAdapter = new RecyclerAdapter(listValues);
recyclerView.addItemDecoration(new ListItemDecorator(current_activity.getApplicationContext()));
recyclerView.setAdapter(recyclerAdapter);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(current_activity);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
if (swipeRefreshLayout.isRefreshing())
swipeRefreshLayout.setRefreshing(false);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(current_activity.getApplicationContext(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
String pictureURL = null;
ListValues feed = listValues.get(position);
if (!pictureValues.isEmpty()) {
ListValues feed2 = pictureValues.get(position);
pictureURL = feed2.getValue();
}
String value = feed.getValue();
switch (type) {
case 1:
intent = new Intent(current_activity, AlbumActivity.class);
intent.putExtra("id", (position + 1));
intent.putExtra("value", value);
current_activity.startActivity(intent);
break;
case 2:
intent = new Intent(current_activity, PhotosActivity.class);
intent.putExtra("id", (position + 1));
intent.putExtra("value", value);
current_activity.startActivity(intent);
break;
case 3:
intent = new Intent(current_activity, ImageDisplay.class);
intent.putExtra("imageUrl", pictureURL);
current_activity.startActivity(intent);
break;
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
} else {
// Log.d(TAG, "unable to get data");
if (swipeRefreshLayout.isRefreshing()) {
Toast.makeText(current_activity, "Unable to refresh data! Try opening application again", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(current_activity, "Failed to fetch data! try again", Toast.LENGTH_SHORT).show();
}
}
super.onPostExecute(integer);
progressDialog.dismiss();
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
Post.java
public class Post implements Serializable {
#SerializedName("userId")
private int userId;
#SerializedName("name")
#Expose
public String name;
#SerializedName("id")
private int id;
#SerializedName("title")
private String title;
#SerializedName("body")
private String body;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
Your important advice for me
Thank you!
You can easily do that with GSON and POJO
first.. you need to create several model
Post.java
public class Post
{
private String id;
private String phone;
private String username;
private String website;
private Address address;
private String email;
private Company company;
private String name;
//setter and getter
}
Company.java
public class Company
{
private String catchPhrase;
private String name;
private String bs;
//setter and getter
}
Address.java
public class Address
{
private Geo geo;
private String zipcode;
private String street;
private String suite;
private String city;
//setter and getter
}
Geo.java
public class Geo
{
private String lng;
private String lat;
//setter and getter
}
After that, json string you get from the API. parse it using Gson..
List<Post> post = new Gson().fromJson(YOUR_JSON_STRING,new TypeToken<List<Post>>() {}.getType());

I have a view and inside that view I have a textview I would like to update that textview?

I have three classes, my adapter class, Voting class, and an acitivty where my JSONrequest is as shown below.The problem is as you can see that I call my JSONrequest in my activity which will get a list of views, inside that view I have a mVote textview. In my adapter you can also see I have a likeButton when someone presses that I would like mVotes to change from 0 to 1. I get all my data from a server so I am assuming I would need to make a new request, do I need to make a new adapter to? and JSON parseing method? How do I do this?!??!
public class AdapterQuestion extends RecyclerView.Adapter<AdapterQuestion.ViewQuestion>{
private LayoutInflater mLayoutInflater;
private ArrayList<QuestionData> data =new ArrayList<>();
public AdapterQuestion(Context context){
//get from context
mLayoutInflater=LayoutInflater.from(context);
}
public void setBloglist(ArrayList<QuestionData> data){
this.data =data;
notifyItemRangeChanged(0, this.data.size());
}
#Override
public ViewQuestion onCreateViewHolder(ViewGroup parent, int viewType){
ViewQuestion holder=new ViewQuestion(view);
return holder;
}
#Override
public void onBindViewHolder(ViewQuestion holder, int position) {
holder.answerText.setText(currentObj.getMtext());
holder.answerId.setText(currentObj.getId());
holder.mVotes.setText(currentObj.getVotes());
holder.mLikeButton.setTag(currentObj);
}
#Override
public int getItemCount() {
return data.size();
}
public class ViewQuestion extends RecyclerView.ViewHolder{
private TextView answerText;
private TextView answerId;
private TextView mVotes;
private LikeButton mLikeButton;
public ViewQuestion (View itemView){
super(itemView);
answerText=(TextView)itemView.findViewById(R.id.answerText);
answerId=(TextView)itemView.findViewById(R.id.answerId);
mVotes=(TextView)itemView.findViewById(R.id.VoteTextView);
mLikeButton= (LikeButton)itemView.findViewById(R.id.heart_buttons);
mLikeButton.setOnLikeListener(new OnLikeListener() {
#Override
public void liked(LikeButton likeButton) {
Voting vote = new Voting();
vote.onUpVote(answerId());
System.out.print("Adapter Position"+getAdapterPosition());
}
#Override
public void unLiked(LikeButton likeButton) {
Voting onDown=new Voting();
onDown.onDownVote(answerId());
}
});
}
public String getVoteView(){
String voteView=mVotes.getText().toString();
return voteView;
}
public String answerId(){
String converted=answerId.getText().toString();
return converted;
}
public int convertToInt(){
String converted=answerId.getText().toString();
int ConvertedInt=Integer.parseInt(converted);
return ConvertedInt;
}
}
}
Voting
public class Voting {
private VolleySingleton mVolleySingleton;
private RequestQueue mRequestQueue;
private AdapterVoteUpdate mAdapterVotes;
private ArrayList<QuestionData> updateVotes = new ArrayList<>();
public void onUpVote(final String answerId) {
final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();
final String PUT_VOTE_UP = "url" + answerId + "url\n";
StringRequest PostVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_UP, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mrequestQueue.add(PostVoteUp);
}
public void onDownVote(final String answerId) {
System.out.println("Voted Down");
final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();
final String PUT_VOTE_DOWN = "url" + answerId + "urul";
StringRequest PostVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_DOWN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println("************Answer" + error + "error");
}
});
mrequestQueue.add(PostVoteUp);
}
JSON RequestClass
public void JsonRequestMethod(String Id) {
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
final String URL_ANSWER = "url" + Id + "url";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_ANSWER, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
mListblogs.clear();
mListblogs = parseJSONResponseQuestion(response);
mAdapterQuestion.setBloglist(mListblogs);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
});
mRequestQueue.add(request);
}
private ArrayList<QuestionData> parseJSONResponseQuestion(JSONArray response) {
if (!response.equals("")) {
ArrayList<QuestionData> questionDataArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String questionId = currentQuestions.getString("questionId");
String votes = currentQuestions.getString("votes");
System.out.println(votes+" VOTES");
int voteInt=Integer.parseInt(votes);
System.out.println(voteInt);
String Answerid = currentQuestions.getString("id");
String selectedId = currentQuestions.getString("selected");
System.out.println(response.length() + "length");
data.append(text + Answerid + "\n");
System.out.println(data);
QuestionData questionData = new QuestionData();
questionData.setMtext(text);
questionData.setVotes(votes);
questionData.setId(Answerid);
questionData.setSelected(selectedId);
mListblogs.add(questionData);
}
System.out.println(data.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
return mListblogs;
}
"I get all my data from a server so I am assuming I would need to make a new request."
-> Actually you don't need to re-request the data from your server again. You just need to update
private ArrayList<QuestionData> data =new ArrayList<>();
on your AdapterQuestion then call AdapterQuestion.notifyDataSetChanged(); after you get a success response from onUpVote or onDownVote
"Do I need to make a new adapter to? and JSON parseing method? How do I do this?!??!"
-> No need
To change a particular ItemView in your recyclerview use this below code.
notifyItemChanged(index);
If you want to change the particular Textview in onItemclick you have to get the item position.
#Override
public void onBindViewHolder(ViewQuestion holder, int position) {
holder.answerText.setText(currentObj.getMtext());
holder.answerId.setText(currentObj.getId());
holder.mVotes.setText(currentObj.getVotes());
holder.mVotes.setTag(currentObj);
holder.mLikeButton.setTag(holder);
}
In your like button click event change the code like the below
mLikeButton.setOnLikeListener(new OnLikeListener() {
#Override
public void liked(LikeButton likeButton) {
Voting vote = new Voting();
vote.onUpVote(answerId());
final ViewQuestion holder=(ViewQuestionholder)likeButton.getTag();
currentObj co=(currentObj)holder.mVotes.getTag();
holder.mVotes.setText("16");
System.out.print("Adapter Position"+getAdapterPosition());
}
#Override
public void unLiked(LikeButton likeButton) {
Voting onDown=new Voting();
onDown.onDownVote(answerId());
final ViewQuestion holder=(ViewQuestionholder)likeButton.getTag();
currentObj co=(currentObj)holder.mVotes.getTag();
holder.mVotes.setText("14");
}
});

SQLite db isn't created

I have problem with sqlite database adapter in my project.I'm new to android development so I don't have much idea to how can handle this problem. I want to save user information in data base .Although no error while execution,database doesn't create? can any one help.
DatabaseAdapter :
public class DatabaseAdapter {
private final String TAG = "DatabaseAdapter";
private DatabaseOpenHelper openHelper;
public static final String TBL_PERSONS = "persons";
public static final String PERSON_ID = "_id";
public static final String PERSON_USERNAME = "_username";
public static final String PERSON_HEIGHT = "_height";
public static final String PERSON_WEIGHT = "_weight";
public static final String PERSON_AGE = "_age";
public static final String PERSON_GENDER = "_gender";
public static final String PERSON_PA = "_pa";
public static final String PERSON_BMI = "_bmivalue";
public static final String PERSON_INTERPRETATION = "_bmiInterpretation";
public static final String PERSON_IDEALWEIGHT = "_idealweight";
public static final String PERSON_DAILYCALORIES = "_dailycalories";
// ???????????
public DatabaseAdapter(Context context) {
openHelper = new DatabaseOpenHelper(context, "Persons.db", null, 1);
}
// ====================insert in
// database===========================================================
public Long insertPerson(Person person) {
SQLiteDatabase db = null;
Long id = -1L;
try {
ContentValues values = new ContentValues();
values.put("PERSON_USERNAME", person.getUsername());
values.put("PERSON_HEIGHT", person.getHeight());
values.put("PERSON_WEIGHT", person.getWeight());
values.put("PERSON_AGE", person.getAge());
values.put("PERSON_GENDER", person.getGender());
values.put("PERSON_PA", person.getPa());
values.put("PERSON_BMI", person.getBmivalue());
values.put("PERSON_INTERPRETAION", person.getBmiInterpretation());
values.put("PERSON_IDEALWEIGHT", person.getIdealweight());
values.put("PERSON_DAILYCALORIES", person.getDailycalories());
db = openHelper.getWritableDatabase();
id = db.insert(TBL_PERSONS, null, values);
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
} finally {
if (db != null && db.isOpen())
db.close();
}
return id;
}
// ================delete from
// database=============================================================
public int deletePerson(long id) {
SQLiteDatabase db = null;
int count = -1;
try {
db = openHelper.getWritableDatabase();
count = db.delete(TBL_PERSONS, PERSON_ID + "=?",
new String[] { String.valueOf(id) });
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
} finally {
db.close();
}
return count;
}
// ===============update
// database===================================================================
public int updatePerson(Person person) {
SQLiteDatabase db = null;
int count = -1;
try {
db = openHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PERSON_USERNAME, person.getUsername());
values.put(PERSON_HEIGHT, person.getHeight());
values.put(PERSON_WEIGHT, person.getWeight());
values.put(PERSON_AGE, person.getAge());
values.put(PERSON_GENDER, person.getGender());
values.put(PERSON_PA, person.getPa());
values.put(PERSON_BMI, person.getBmivalue());
values.put(PERSON_INTERPRETATION, person.getBmiInterpretation());
values.put(PERSON_IDEALWEIGHT, person.getIdealweight());
values.put(PERSON_DAILYCALORIES, person.getDailycalories());
count = db.update(TBL_PERSONS, values, PERSON_ID + "=?",
new String[] { String.valueOf(person.getId()) });
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
} finally {
db.close();
}
return count;
}
// ===================================================================DATABASEOPENHELPER
// CLASS=========================
class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = String
.format("create table %s(%$ integer primary key,%s text,%s text,%s text,%s text,%s text,%s tetx,%s text,%s text,%s text,%s text)",
TBL_PERSONS, PERSON_ID, PERSON_USERNAME,
PERSON_HEIGHT, PERSON_WEIGHT, PERSON_AGE,
PERSON_GENDER, PERSON_PA, PERSON_BMI,
PERSON_INTERPRETATION, PERSON_IDEALWEIGHT,
PERSON_DAILYCALORIES);
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
person.java (I pass the user data to person.java)
package Databasedata;
public class Person {
private Long id;
private String username;
private float height;
private int weight;
private int age;
private String gender;
private String pa;
private int bmivalue;
private String bmiInterpretation;
private double idealweight;
private double dailycalories;
public double getIdealweight() {
return idealweight;
}
public void setIdealweight(double idealweight) {
this.idealweight = idealweight;
}
public double getDailycalories() {
return dailycalories;
}
public void setDailycalories(double dailycalories) {
this.dailycalories = dailycalories;
}
public int getBmivalue() {
return bmivalue;
}
public void setBmivalue(int bmivalue) {
this.bmivalue = bmivalue;
}
public String getBmiInterpretation() {
return bmiInterpretation;
}
public void setBmiInterpretation(String bmiInterpretation) {
this.bmiInterpretation = bmiInterpretation;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPa() {
return pa;
}
public void setPa(String pa) {
this.pa = pa;
}
}
MAIN ACTIVITY
public class MainActivity extends Activity {
String gender;
RadioButton maleRadioButton;
RadioButton femaleRadioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
maleRadioButton = (RadioButton) findViewById(R.id.maleselected);
femaleRadioButton = (RadioButton) findViewById(R.id.femaleselected);
final RadioGroup genderselected = (RadioGroup) findViewById(R.id.selectgender);
genderselected.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int selectedId) {
selectedId=genderselected.getCheckedRadioButtonId();
RadioButton genderchoosed = (RadioButton) findViewById(selectedId);
gender= genderchoosed.getText().toString();
}
});
Button saveinformation = (Button) findViewById(R.id.saveinformation);
saveinformation.setOnClickListener(new View.OnClickListener() {
EditText weighttext = (EditText) findViewById(R.id.weighttext);
EditText heighttext = (EditText) findViewById(R.id.heighttext);
EditText usernametext = (EditText) findViewById(R.id.usernametext);
EditText agetext = (EditText) findViewById(R.id.agetext);
Spinner activitytext = (Spinner) findViewById(R.id.chooseactivity);
Button saveinformation = (Button) findViewById(R.id.saveinformation);
String pa = activitytext.getSelectedItem().toString();
#Override
public void onClick(View v) {
if(maleRadioButton.isChecked()) {
gender= maleRadioButton.getText().toString();
} else {
gender = femaleRadioButton.getText().toString();
}
int weight = (int) Float.parseFloat(weighttext.getText()
.toString());
float height = Float.parseFloat(heighttext.getText()
.toString());
String username = usernametext.getText().toString();
int age = (int) Float.parseFloat(agetext.getText().toString());
String pa = activitytext.getSelectedItem().toString();
// BMI
// ============================================================================================
int Bmivalue = calculateBMI(weight, height);
String bmiInterpretation = interpretBMI(Bmivalue);
float idealweight = idealweight(weight, height, gender, pa, age);
double dailycalories=dailycalories(weight,height,gender,pa,age);
// insert in to
// db==================================================================================
Person person = new Person();
person.setUsername(username);
person.setHeight(height);
person.setWeight(weight);
person.setAge(age);
person.setGender(gender);
person.setPa(pa);
person.setBmivalue(Bmivalue);
person.setBmiInterpretation(bmiInterpretation);
person.setIdealweight(idealweight);
person.setDailycalories(dailycalories);
// ?????????????????????????????????????????/
Databasedata.DatabaseAdapter dbAdapter = new Databasedata.DatabaseAdapter(
MainActivity.this);
dbAdapter.insertPerson(person);
Toast.makeText(getApplicationContext(),
Bmivalue + "and you are" + bmiInterpretation,
Toast.LENGTH_LONG).show();
}
});
}
}
One Problem I see is in your insertPerson() method. Don't include the "" in the values.put()
try replacing below code
ContentValues values = new ContentValues();
values.put("PERSON_USERNAME", person.getUsername());
values.put("PERSON_HEIGHT", person.getHeight());
values.put("PERSON_WEIGHT", person.getWeight());
values.put("PERSON_AGE", person.getAge());
values.put("PERSON_GENDER", person.getGender());
values.put("PERSON_PA", person.getPa());
values.put("PERSON_BMI", person.getBmivalue());
values.put("PERSON_INTERPRETAION", person.getBmiInterpretation());
values.put("PERSON_IDEALWEIGHT", person.getIdealweight());
values.put("PERSON_DAILYCALORIES", person.getDailycalories());
with
ContentValues values = new ContentValues();
values.put(PERSON_USERNAME, person.getUsername());
values.put(PERSON_HEIGHT, person.getHeight());
values.put(PERSON_WEIGHT, person.getWeight());
values.put(PERSON_AGE, person.getAge());
values.put(PERSON_GENDER, person.getGender());
values.put(PERSON_PA, person.getPa());
values.put(PERSON_BMI, person.getBmivalue());
values.put(PERSON_INTERPRETATION, person.getBmiInterpretation());
values.put(PERSON_IDEALWEIGHT, person.getIdealweight());
values.put(PERSON_DAILYCALORIES, person.getDailycalories());

Categories