Привет! Мне удалось вставить элементы, связав представление корзины с MYSQL PHP, но удаление элементов по-прежнему не удается. Вы можете удалить его на клиенте, но я продолжаю работать с PHP и MYSQL. Могу ли я получить помощь с этим примером или кодом?
Это код утилита
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
//Imageloader to load image
private ImageLoader imageLoader;
private Context context;
//List to store all superheroes
List<recyclerview_list> recyclerview_lists;
//Constructor of this class
public CardAdapter(List<recyclerview_list> recyclerview_lists, recyclerview context) {
super();
//Getting all superheroes
this.recyclerview_lists = recyclerview_lists;
this.context = (Context) context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recyclerview_list, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
//Getting the particular item from the list
recyclerview_list recyclerview_List = recyclerview_lists.get(position);
//Loading image from url
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(recyclerview_List.getImage_path(), ImageLoader.getImageListener(holder.imageView, R.drawable.ic_launcher_background, android.R.drawable.ic_dialog_alert));
//Showing data on the views
holder.imageView.setImageUrl(recyclerview_List.getImage_path(), imageLoader);
holder.textViewName.setText(recyclerview_List.getImage_name());
}
@Override
public int getItemCount() {
return recyclerview_lists.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
//Views
public NetworkImageView imageView;
public TextView textViewName;
public Button deleteButton;
//Initializing Views
public ViewHolder(final View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
textViewName = (TextView) itemView.findViewById(R.id.textViewName);
deleteButton = (Button) itemView.findViewById(R.id.buttonDelete);
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, "Delete", Toast.LENGTH_SHORT).show();
delete(getAdapterPosition());}
});
}
public void delete(int position) {
try {
recyclerview_lists.remove(position);
notifyItemRemoved(position);
} catch (IndexOutOfBoundsException ex) {
ex.printStackTrace();
}
}
}
}
Это код PHP
$con = mysqli_connect("", "", "", "");
$id = $_POST["id"];
$statement = mysqli_prepare($con, "DELETE FROM image WHERE id = ?");
mysqli_stmt_bind_param($statement, "s", $id);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
Добавить новый метод в вызов адаптера
public void deleteFromServer(int id)
{
url = "http://yoururl/delete_image.php";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// if success
delete(id)
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}
) {
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("id", id);
return params;
}
};
queue.add(postRequest);
}
Вызовите этот метод из класса адаптера
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, "Delete", Toast.LENGTH_SHORT).show();
deleteFromServer(recyclerview_lists.get(getAdapterPosition()).id);}
});
Хороший код, но не может получить распознанный идентификатор. Я поделюсь всей моей работой.
Config.java
public static final String DATA_URL = "http:// /images/feed.php?page=";
/*Json으로 가져오는 이미지 테이블의 목록*/
// 이미지 주소
public static final String TAG_IMAGE_URL = "image_path";
// 이미지 이름
public static final String TAG_NAME = "image_name";
}
Пользовательский залп Request.java
private static CustomVolleyRequest customVolleyRequest;
private static Context context;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private CustomVolleyRequest(Context context) {
this.context = context;
this.requestQueue = getRequestQueue();
imageLoader = new ImageLoader(requestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized CustomVolleyRequest getInstance(Context context) {
if (customVolleyRequest == null) {
customVolleyRequest = new CustomVolleyRequest(context);
}
return customVolleyRequest;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
requestQueue = new RequestQueue(cache, network);
requestQueue.start();
}
return requestQueue;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
recyclerview_list.java
private String image_path;
private String image_name;
public String getImage_path() {
return image_path;
}
public void setImage_path(String image_path) {
this.image_path = image_path;
}
public String getImage_name() {
return image_name;
}
public void setImage_name(String image_name) {
this.image_name = image_name;
}
recyclerview. Джава
// Создание списка супергероев
приватный список listSuperHeroes;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;//Volley Request Queue
private RequestQueue requestQueue;
//The request counter to send ?page=1, ?page=2 requests
private int requestCount = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recyclerview);
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing our superheroes list
listSuperHeroes = new ArrayList<>();
requestQueue = Volley.newRequestQueue(this);
//Calling method to get data to fetch data
getData();
//Adding an scroll change listener to recyclerview
recyclerView.setOnScrollChangeListener(this);
//initializing our adapter
adapter = new CardAdapter(listSuperHeroes ,this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
//Request to get json from server we are passing an integer here
//This integer will used to specify the page number for the request ?page = requestcount
//This method would return a JsonArrayRequest that will be added to the request queue
private JsonArrayRequest getDataFromServer(int requestCount) {
//Initializing ProgressBar
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar1);
//Displaying Progressbar
progressBar.setVisibility(View.VISIBLE);
setProgressBarIndeterminateVisibility(true);
//JsonArrayRequest of volley
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL + String.valueOf(requestCount),
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
//Calling method parseData to parse the json response
parseData(response);
//Hiding the progressbar
progressBar.setVisibility(View.GONE);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
//If an error occurs that means end of the list has reached
Toast.makeText(recyclerview.this, "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
//Returning the request
return jsonArrayRequest;
}
//This method will get data from the web api
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
requestQueue.add(getDataFromServer(requestCount));
//Incrementing the request counter
requestCount++;
}
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
//Creating the superhero object
recyclerview_list recyclerviewList = new recyclerview_list();
JSONObject json = null;
try {
//Getting json
json = array.getJSONObject(i);
//Adding data to the superhero object
recyclerviewList.setImage_path(json.getString(Config.TAG_IMAGE_URL));
recyclerviewList.setImage_name(json.getString(Config.TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the superhero object to the list
listSuperHeroes.add(recyclerviewList);
}
//Notifying the adapter that data has been added or changed
adapter.notifyDataSetChanged();
}
//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
//Overriden method to detect scrolling
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//Ifscrolled at last then
if (isLastItemDisplaying(recyclerView)) {
//Calling the method getdata again
getData();
}
}