I tried to edit a value from a mysql database(from "addfav" column), when a star(imageView) is pressed. My database contains: "id, devicename, category, image, addfav" columns.
I have a recyclerview with some devices retrieved from database and every device had a star(for add to favorites) and when this star is pressed, i want that a value from "addfav" column from database to change.
For this, i used HashMap in OnBindViewHolder method, when the star is pressed, but this is not working and an error occurs.
The error:
11-30 15:49:16.584 14907-14907/com.example.photosib E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.photosib, PID: 14907
java.lang.ClassCastException: com.example.photosib.MainHomeActivity.HomeActivity cannot be cast to com.kosalgeek.asynctask.AsyncResponse
at com.example.photosib.MainHomeActivity.Home.HomeRecyclerViewAdapter$2.onClick(HomeRecyclerViewAdapter.java:87)
My recyclelrview/adapter code:
public class HomeRecyclerViewAdapter extends RecyclerView.Adapter<HomeRecyclerViewAdapter.RecyclerViewHolder> {
private static final String URL_UPDATE = "php script";
private Context mCtx;
private List<HomeItemDevicesDetails> devicesList;
private HomeItemDevicesDetails addStarFav;
SwipeRefreshLayout swipeRefreshLayout;
public HomeRecyclerViewAdapter(Context mCtx, List<HomeItemDevicesDetails> devicesList, SwipeRefreshLayout swipeRefreshLayout) {
this.mCtx = mCtx;
this.devicesList = devicesList;
this.swipeRefreshLayout = swipeRefreshLayout;
}
@Override
public HomeRecyclerViewAdapter.RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.home_recyclerview_items, parent, false);
return new RecyclerViewHolder(view);
}
@SuppressLint("SetTextI18n")
@Override
public void onBindViewHolder(final RecyclerViewHolder holder, int position) {
final HomeItemDevicesDetails category = devicesList.get(position);
//loading the image
Glide.with(mCtx)
.load(category.getImage())
.into(holder.imageView);
holder.textViewTitle.setText(category.getDevice_name());
holder.textViewCategory.setText(category.getCategory());
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
HomeRefresh();
}
});
// add to fav star
holder.imageViewFavorites.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (holder.imageViewFavorites.getColorFilter() != null) {
holder.imageViewFavorites.clearColorFilter();
Toast.makeText(view.getContext(), "Removed from Favorites", Toast.LENGTH_SHORT).show();
} else {
holder.imageViewFavorites.setColorFilter(ContextCompat.getColor(mCtx,
R.color.orange));
// here i tried to open and to execute the php file
HashMap addToFav = new HashMap();
addToFav.put("id", category.getId());
PostResponseAsyncTask task = new PostResponseAsyncTask((AsyncResponse) mCtx, addToFav);
task.execute(URL_UPDATE);
Toast.makeText(view.getContext(), "Added to Favorites", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public int getItemCount() {
return devicesList.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView textViewTitle, textViewCategory;
ImageView imageView, imageViewFavorites;
RelativeLayout parentLayout;
public RecyclerViewHolder(final View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.home_item_title);
textViewCategory = itemView.findViewById(R.id.home_single_item_category);
imageView = itemView.findViewById(R.id.img_home_item);
imageViewFavorites = itemView.findViewById(R.id.add_favorites);
parentLayout = itemView.findViewById(R.id.home_single_item_details);
parentLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// OPEN WHEN CLICK ON HOME ITEMS
HomeActivity activity = (HomeActivity) view.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new SingleDeviceDetailsFragment()).commit();
}
});
}
}
public void HomeRefresh()
{
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Collections.shuffle(devicesList);
HomeRecyclerViewAdapter.this.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
},1500);
}
My fragment code, where the recyclerview is call(this works fine, not errors):
public class HomeFragment extends Fragment{
//this is the JSON Data URL
//make sure you are using the correct ip else it will not work
private static final String URL_CATEGORIES = "php script";
//a list to store all the product
List<HomeItemDevicesDetails> devicesList;
//the recyclerview
private RecyclerView recyclerView;
// Home refresh
SwipeRefreshLayout swipeRefreshLayout;
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
devicesList = new ArrayList<>();
//getting the recyclerview from xml
recyclerView = (RecyclerView) view.findViewById(R.id.home_recyclerview_row);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swiper);
//this method will fetch and parse json
//to display it in recyclerview
loadProducts();
return view;
}
private void loadProducts() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_CATEGORIES,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject category = array.getJSONObject(i);
//adding the product to product list
devicesList.add(new HomeItemDevicesDetails(
category.getInt("id"),
category.getString("device_name"),
category.getString("category"),
category.getString("url")
));
}
//creating adapter object and setting it to recyclerview
HomeRecyclerViewAdapter adapter = new HomeRecyclerViewAdapter(getContext(),devicesList, swipeRefreshLayout);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this.getActivity()).add(stringRequest);
}
}
The device model(here i am not sure if i need to retrieve the "addfav" value from database):
public class HomeItemDevicesDetails {
private int id;
private String device_name;
private String category;
private String image;
public HomeItemDevicesDetails(int id, String device_name, String category, String image) {
this.id = id;
this.device_name = device_name;
this.category = category;
this.image = image;
}
public int getId() {
return id;
}
public String getDevice_name() {
return device_name;
}
public String getCategory() {
return category;
}
public String getImage() {
return image;
}
}
The php script for update the value from database:
<?php
$host = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$db = "xxxxxxx";
$id = $_GET['id'];
$conn = new mysqli($host, $username, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE devices SET devices.addfav='1' WHERE devices.id='$id'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
I don't know how to get through this problem. I'm not experienced in Java(i start with the Java development 3 months ago). Can someone give me some solutions/hints?