У меня есть gridView, который показывает кнопки. Я хочу удалить указанную кнопку c, которую нажимают. Однако каждый раз, когда я нажимаю кнопки, удаляется только последний элемент.
В моем buttongridAdapter есть AsyncTask (postWaitListTask), который отправляет запрос на удаление на сервер. Внутри этой AsynckTask onPostExecute я пытаюсь удалить кнопку, которая удаляется успешно. В Log.d newtimeList показывает правильное содержимое.
Например, если newtimeList включает 14: 00,14: 30,15: 00, после того, как я нажал 14:30 и был успешно удален, newTimeList включает 14:00 и 15:00 (что Log.d selectaf показывает). Однако gridView показывает 14:00 и 14:30, что последний элемент (15:00) удаляется, а не 14:30, на который я нажал.
Вот мой adpater
package com.example.user.solviolin;
import android.content.Context;
import android.content.DialogInterface;
import androidx.fragment.app.Fragment;
import androidx.appcompat.app.AlertDialog;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Toast;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import static com.example.user.solviolin.MainActivity.userName;
public class ButtonGridAdapter extends BaseAdapter {
Context context = null;
ArrayList<String> buttonNames = null;
private Fragment parent;
private String courseTeacher;
private String courseBranch;
private String userID;
private String startTime;
private String userDuration;
private String courseDay;
private String startDate;
ButtonGridAdapter myself;
public ButtonGridAdapter(Context context, ArrayList<String> buttonNames, Fragment parent, String courseTeacher, String startDate, String courseDay, String userID, String userBranch, String userDuration) {
this.context = context;
this.buttonNames = buttonNames;
this.parent = parent;
this.courseTeacher = courseTeacher;
this.startDate = startDate;
this.courseDay = courseDay;
this.userID = userID;
this.courseBranch = userBranch;
this.userDuration = userDuration;
}
@Override
public int getCount() {
return (null != buttonNames) ? buttonNames.size() : 0;
}
@Override
public Object getItem(int position) {
return buttonNames.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public void refresh(ArrayList<String> buttonNames)
{
this.buttonNames = buttonNames;
notifyDataSetChanged();
}
@Override
public View getView(int position, View convertView, final ViewGroup parent) {
Button button = null;
if(null != convertView){
button = (Button)convertView;
}
else{
button = new Button(context);
button.setText(buttonNames.get(position));
}
myself = this;
final Button finalButton = button;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startTime = finalButton.getText().toString();
final String url;
if(userName.equals("admin"))
{
url = "http://show981111.cafe24.com/putRegularFromAdmin.php";
}else
{
url = "http://show981111.cafe24.com/putWaitList.php";
}
AlertDialog.Builder builder = new AlertDialog.Builder(parent.getContext());
AlertDialog dialog = builder.setMessage(courseTeacher + "선생님 " + courseDay + "요일 " + startTime + " 시작일 " + startDate + " 으로 레슨을 예약하시겠습니까?")
.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
postWaitListTask postWaitListTask = new postWaitListTask(context, courseTeacher, courseBranch, userID, startTime, userDuration, courseDay, startDate,buttonNames,myself );
postWaitListTask.execute(url);
}
})
.setNegativeButton("취소", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startTime = "";
Toast.makeText(parent.getContext(), "취소하였습니다.", Toast.LENGTH_LONG).show();
}
})
.create();
dialog.show();
}
});
return button;
}
class postWaitListTask extends AsyncTask<String, Void, String>
{
private Context context;
private String pt_courseTeacher;
private String pt_courseBranch;
private String pt_userID;
private String pt_startTime;
private String pt_userDuration;
private String pt_courseDay;
private String pt_startDate;
ButtonGridAdapter buttonGridAdapter;
private ArrayList<String> newtimeList;
public postWaitListTask(Context context, String pt_courseTeacher, String pt_courseBranch, String pt_userID, String pt_startTime, String pt_userDuration, String pt_courseDay, String pt_startDate,ArrayList<String> newtimeList, ButtonGridAdapter buttonGridAdapter ) {
this.context = context;
this.pt_courseTeacher = pt_courseTeacher;
this.pt_courseBranch = pt_courseBranch;
this.pt_userID = pt_userID;
this.pt_startTime = pt_startTime;
this.pt_userDuration = pt_userDuration;
this.pt_courseDay = pt_courseDay;
this.pt_startDate = pt_startDate;
this.newtimeList = newtimeList;
this.buttonGridAdapter = buttonGridAdapter;
}
@Override
protected String doInBackground(String... strings) {
String url = strings[0];
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("courseBranch", pt_courseBranch)
.add("courseDay", pt_courseDay)
.add("courseTeacher", pt_courseTeacher)
.add("startDate",pt_startDate)
.add("userDuration", pt_userDuration)
.add("userID",pt_userID)
.add("startTime",pt_startTime)
.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Log.d("postWaitList", "going");
try {
Response response = client.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
Log.d("postWaitList", e.getMessage());
return null;
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("postWaitList",s);
if(s.equals("success"))
{
for(String time : newtimeList)
{
Log.d("selectedbef", time);
}
newtimeList.remove(pt_startTime);
for(String time : newtimeList)
{
Log.d("selectedaf", time);
}
Log.d("selected", pt_startTime);
buttonGridAdapter.refresh(newtimeList);
Toast toast = Toast.makeText(context,"성공적으로 요청되었습니다.",Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}else if(s.equals("fail")) {
Toast toast = Toast.makeText(context, "시작날짜와 요일을 다시한번 확인해주세요.", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}else if(s.equals("internet_fail"))
{
Toast toast = Toast.makeText(context, "인터넷 연결상태를 확인해주세요.", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}else if(s.equals("already"))
{
Toast toast = Toast.makeText(context, "이미 신청되어있습니다.", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}else if(s.equals("alreadyBooked"))
{
Toast toast = Toast.makeText(context, "이미 예약되었습니다.", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}else if(s.equals("notEmpty"))
{
Toast toast = Toast.makeText(context, "비어있는 자리가 아닙니다.", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
}
}
Вот где совпадают адаптер и gridView.
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.GridView;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import androidx.fragment.app.Fragment;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import static com.example.user.solviolin.MainActivity.userName;
//fetch teacher list for teacherSpinner in monthFragment
public class fetchTimeForMonth extends AsyncTask<String, Void, AvailableTimeForMonth[]> {
private static ArrayList<courseTimeLine> courseTimeLineArrayList = new ArrayList<>();
private static ArrayList<String> timeList = new ArrayList<>();
private GridView timeButtonGrid;
private Context context;
private Fragment parent;
private String courseDay;
private String courseTeacher;
private String startDate;
private String gv_userID;
private String gv_userBranch;
private String gv_userDuration;
public fetchTimeForMonth(GridView gv, Context c, Fragment fragment, String courseDay, String courseTeacher, String startDate, String gv_userID, String gv_userBranch, String gv_userDuration)
{
this.timeButtonGrid = gv;
this.context = c;
this.parent = fragment;
this.courseDay = courseDay;
this.courseTeacher = courseTeacher;
this.startDate = startDate;
this.gv_userID = gv_userID;
this.gv_userBranch = gv_userBranch;
this.gv_userDuration = gv_userDuration;
}
public static ArrayList<courseTimeLine> getCourseTimeLineArrayList() {
return courseTimeLineArrayList;
}
public static void setCourseTimeLineArrayList(ArrayList<courseTimeLine> courseTimeLineArrayList) {
fetchTimeForMonth.courseTimeLineArrayList = courseTimeLineArrayList;
}
@Override
protected AvailableTimeForMonth[] doInBackground(String... strings) {
String url= strings[0];
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("userBranch", gv_userBranch)
.add("courseDay", this.courseDay)
.add("courseTeacher", this.courseTeacher)
.add("startDate",this.startDate)
.add("userDuration", gv_userDuration)
.add("userName",userName)
.build();
Log.d("fetchTimeForMonth",gv_userBranch);
Log.d("fetchTimeForMonth",this.courseDay);
Log.d("fetchTimeForMonth",this.courseTeacher);
Log.d("fetchTimeForMonth",this.startDate);
Log.d("fetchTimeForMonth", gv_userDuration);
Log.d("fetchTimeForMonth",userName);
Log.d("fetchTimeForMonth",gv_userID);
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
try {
Response response = client.newCall(request).execute();
Log.d("fetchTimeForMonth", "res");
Gson gson = new Gson();
AvailableTimeForMonth[] times = gson.fromJson(response.body().charStream(), AvailableTimeForMonth[].class);
return times;
} catch (IOException e) {
e.printStackTrace();
Log.d("fetchTimeForMonth", e.getMessage());
return null;
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(AvailableTimeForMonth[] times) {
super.onPostExecute(times);
timeList.clear();
if(times != null) {
for (AvailableTimeForMonth time : times) {
timeList.add(time.getRegular_Time());
Log.d("fetchTimeForMonth", time.getRegular_Time());
}
ButtonGridAdapter buttonGridAdapter = new ButtonGridAdapter(context, timeList, parent,courseTeacher,startDate,courseDay,gv_userID,gv_userBranch,gv_userDuration);
buttonGridAdapter.notifyDataSetChanged();
timeButtonGrid.setAdapter(buttonGridAdapter);
}else
{
Log.d("fetchTimeForMonth","NULL");
}
}
}