I'm currently using the Parse API for Android, and I currently have a Array of Strings in my application. I currently have a ListView with all of my Strings. Inside my app inside the ListView itself I have implemented a setOnItemLongClickListener with a Dialog. I want to delete a the selected ListView item's string from Parse.
Image of the Database Row
NotesFragment.java
public class NotesFragment extends Fragment {
ParseUser user;
ListView notesList;
private FloatingActionButton FAB;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_notes, container, false);
notesList = (ListView) rootView.findViewById(R.id.lv_contact);
user = ParseUser.getCurrentUser();
FAB = (FloatingActionButton) rootView.findViewById(R.id.fab);
FAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), AddNoteActivity.class);
getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
startActivity(intent);
}
});
final ArrayList<ParseObject> list1 = (ArrayList) user.getList("notes");
ArrayAdapter<ParseObject> arrayAdapter;
arrayAdapter = new ArrayAdapter<ParseObject>(getContext(), android.R.layout.simple_list_item_1, list1);
RelativeLayout emptyView = (RelativeLayout) rootView.findViewById(R.id.empty);
if (list1 == null) {
emptyView.setVisibility(View.VISIBLE);
} else {
notesList.setAdapter(arrayAdapter);
emptyView.setVisibility(View.INVISIBLE);
}
notesList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
new AlertDialog.Builder(getContext())
.setTitle("Are you sure you want to Delete?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
ArrayList<String> toRemove = new ArrayList<>();
toRemove.add("Hey");
ParseUser.getCurrentUser().removeAll("checklistDat", toRemove);
ParseUser.getCurrentUser().saveInBackground();
ParseUser.getCurrentUser().deleteInBackground();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.show();
return true;
}
});
return rootView;
}
}
I was able to fix this by doing this
NotesFragment.java
public class NotesFragment extends Fragment {
ParseUser user;
ListView notesList;
ProgressBar mPB;
private FloatingActionButton FAB;
ArrayList<ParseObject> list1 = (ArrayList) ParseUser.getCurrentUser().getList("notes");
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_notes, container, false);
mPB = (ProgressBar) rootView.findViewById(R.id.progress_bar);
mPB.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mPB.setVisibility(View.GONE);
}
}, 3500);
notesList = (ListView) rootView.findViewById(R.id.lv_contact);
user = ParseUser.getCurrentUser();
FAB = (FloatingActionButton) rootView.findViewById(R.id.fab);
FAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), AddNoteActivity.class);
getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
startActivity(intent);
}
});
final ArrayAdapter<ParseObject> arrayAdapter;
arrayAdapter = new ArrayAdapter<ParseObject>(getContext(), android.R.layout.simple_list_item_1, list1);
final RelativeLayout emptyView = (RelativeLayout) rootView.findViewById(R.id.empty);
if (list1 == null) {
emptyView.setVisibility(View.VISIBLE);
mPB.setVisibility(View.GONE);
} else {
notesList.setAdapter(arrayAdapter);
emptyView.setVisibility(View.INVISIBLE);
}
notesList.setLongClickable(true);
notesList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
new android.app.AlertDialog.Builder(getContext())
.setTitle("Delete?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
list1.remove(position);
ParseUser.getCurrentUser().remove("notes");
ParseUser.getCurrentUser().put("notes", list1);
ParseUser.getCurrentUser().saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Toast.makeText(getContext(), "Deleted", Toast.LENGTH_SHORT).show();
if (list1.toString().equals("[]")) {
emptyView.setVisibility(View.VISIBLE);
mPB.setVisibility(View.GONE);
} else {
notesList.setAdapter(arrayAdapter);
emptyView.setVisibility(View.INVISIBLE);
}
}
});
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.show();
return true;
}
});
return rootView;
}
}
Related
i have some problems with updating fragment view after item deleted. So i have one fragment which one showing all items added from another activity. And when im trying to delete item it's not updating view so i should restart fragment to see updated fragment.
There is my fragment
public class MyGarageFragment extends Fragment {
FloatingActionButton fab;
RecyclerView mRecyclerView;
DatabaseHelper databaseHelper;
RVAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_my_garage, null);
mRecyclerView = v.findViewById(R.id.recyclerView);
databaseHelper = new DatabaseHelper(getContext());
showRecord();
fab = v.findViewById(R.id.addFabButton);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// startActivity(new Intent(getContext(), AddRecordActivity.class));
Intent intent = new Intent(getContext(), AddAutoActivity.class);
intent.putExtra("editMode",false);
startActivity(intent);
}
});
return v;
}
private void showRecord() {
adapter = new RVAdapter(getContext(),databaseHelper.getAllData(Constants.C_ADD_TIMESTAMP + " DESC"));
mRecyclerView.setAdapter(adapter);
}
#Override
public void onResume(){
super.onResume();
showRecord();
}
also my Recyclerview Adapter
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.Holder> {
private Context context;
private ArrayList<Model> arrayList;
DatabaseHelper databaseHelper;
#NonNull
#Override
public Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_my_garage,parent,false);
return new Holder(view);
}
public RVAdapter(Context context, ArrayList<Model> arrayList) {
this.context = context;
this.arrayList = arrayList;
databaseHelper = new DatabaseHelper(context);
}
#Override
public void onBindViewHolder(#NonNull Holder holder, int position) {
Model model = arrayList.get(position);
String id = model.getId();
String image = model.getImage();
String name = model.getName();
String age = model.getAge();
String phone = model.getPhone();
String addTimeStamp = model.getAddTimeStamp();
String updateTimeStamp = model.getUpdateTimeStamp();
holder.profileIv.setImageURI(Uri.parse(image));
holder.name.setText(name);
holder.age.setText(age);
holder.phone.setText(phone);
holder.editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(context, holder.editButton);
popupMenu.inflate(R.menu.popup_menu);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:
editDialog(
""+position,
""+id,
""+name,
""+age,
""+phone,
""+image,
""+addTimeStamp,
""+updateTimeStamp
);
break;
case R.id.action_delete:
deleteDialog(""+id);
break;
default:
break;
}
return false;
}
});
popupMenu.show();
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,"item " + id, Toast.LENGTH_SHORT).show();
}
});
}
private void deleteDialog(String id) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Delete");
builder.setMessage("Are you sure?");
builder.setCancelable(false);
builder.setIcon(R.drawable.ic_baseline_delete_24);
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
databaseHelper.deleteInfo(id);
((MyGarageFragment)context).onResume();
Toast.makeText(context, "Delete Success!", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.create().show();
}
private void editDialog(String position, String id, String name, String age, String phone, String image, String addTimeStamp, String updateTimeStamp) {
Intent intent = new Intent(context, EditAutoActivity.class);
intent.putExtra("ID",id);
intent.putExtra("NAME",name);
intent.putExtra("AGE",age);
intent.putExtra("PHONE",phone);
intent.putExtra("IMAGE",image);
intent.putExtra("ADD_TIMESTAMP",addTimeStamp);
intent.putExtra("UPDATE_TIMESTAMP",updateTimeStamp);
intent.putExtra("editMode",true);
context.startActivity(intent);
}
#Override
public int getItemCount() {
return arrayList.size();
}
class Holder extends RecyclerView.ViewHolder {
ImageView profileIv;
TextView name,age,phone;
ImageView editButton;
public Holder (#NonNull View itemView){
super(itemView);
profileIv = itemView.findViewById(R.id.profileIv);
name = itemView.findViewById(R.id.name);
age = itemView.findViewById(R.id.age);
phone = itemView.findViewById(R.id.phone);
editButton = itemView.findViewById(R.id.editBtn);
}
}
}
so what should i do in deleteDialog to delete cardview item and refresh ui?
private void deleteDialog(String id) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Delete");
builder.setMessage("Are you sure?");
builder.setCancelable(false);
builder.setIcon(R.drawable.ic_baseline_delete_24);
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
databaseHelper.deleteInfo(id);
((MyGarageFragment)context).onResume();
Toast.makeText(context, "Delete Success!", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.create().show();
}
I'm making a todo app and when an item is marked as finished an image should be displayed in front of the list item. But images are not visible in the list view even if the item status in the database is changed as finished.
This is my adapter class.
public class ToDoAdapter extends ArrayAdapter {
private Context context;
private int resource;
List<ToDoModel> todos;
public ToDoAdapter(#NonNull Context context, int resource, #NonNull List<ToDoModel> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.todos = objects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//Inflate card view
LayoutInflater inflater = LayoutInflater.from(context);
View row = inflater.inflate(resource, parent, false);
TextView title = row.findViewById(R.id.title);
TextView description = row.findViewById(R.id.txtDescription);
ImageView img = (ImageView)row.findViewById(R.id.img_done);
img.setVisibility(View.VISIBLE);
//Set data in card view
ToDoModel todo = todos.get(position);
title.setText(todo.getTitle());
description.setText(todo.getDescription());
//Show done image
if(todo.getFinished() > 0){
img.setVisibility(View.VISIBLE);
}
return row;
}
}
This is MainActivity.
public class MainActivity extends AppCompatActivity {
private ListView todoList;
private TextView countTxt;
private Button addTodo;
private List<ToDoModel> toDos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
todoList = (ListView)findViewById(R.id.listViewToDo);
countTxt = (TextView)findViewById(R.id.txtCount);
addTodo = (Button)findViewById(R.id.btnAdd);
toDos = new ArrayList<>();
addTodo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Go to next activity
startActivity(new Intent(getApplicationContext(), AddToDO.class));
}
});
}
#Override
protected void onResume() {
super.onResume();
DBHandler dbh = new DBHandler(getApplicationContext());
//Set count
int count = dbh.getCountTODO();
countTxt.setText("You have " + count + " TODOs");
//Save list
toDos = dbh.getAllToDos();
//Set adapter to list
ToDoAdapter toDoAdapter = new ToDoAdapter(getApplicationContext(), R.layout.todo_cardview, toDos);
todoList.setAdapter(toDoAdapter);
//Add click listener to list element
todoList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Get clicked item
ToDoModel todo = toDos.get(position);
//Dialog box
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(todo.getTitle());
builder.setMessage(todo.getDescription());
//Buttons
builder.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dbh.deleteItem(todo.getId());
Toast.makeText(getApplicationContext(), "ToDo Deleted", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
builder.setPositiveButton("Finished", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
long time = System.currentTimeMillis();
//Update status
dbh.updateFinished(todo.getId(), time);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
builder.setNeutralButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, AddToDO.class);
intent.putExtra("id", todo.getId());
intent.putExtra("title", todo.getTitle());
intent.putExtra("description", todo.getDescription());
intent.putExtra("finished", todo.getFinished());
startActivity(intent);
}
});
builder.show();
}
});
}
}
Use Glide or Picasso Library to Displaying Image with any other Shape.
Glide Example:
Glide.with(mContext).load(responseList.getLogoUrl()).apply(RequestOptions.circleCropTransform()).into(holder.imageName);
Picasso Example:
Picasso.get().load(clsobjname.getLogoUrl())
.into(viewHolder.imagename);
I have Listview in a Fragment in which i am setting data using ArrayAdapter, when i am deleting the data with Dialog box the Value is duplicating in the listview. i don't know what to do i was thinkint to refresh my fragment when the delete button is clicked in dialog box but i don't how to do that.I am new to Android please let me know what can i do to solve this.Here is my Code.
ListOfFaculty
public class ListOfFaculty extends Fragment {
DatabaseReference ref;
ListView listview;
List<String> store;
List<String> UserID;
String[] faculty_list;
String a;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ref = FirebaseDatabase.getInstance().getReference("Faculty");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View root = inflater.inflate(R.layout.fragment_list_of_faculty, container, false);
listview = root.findViewById(R.id.lv);
store =new ArrayList<>();
UserID =new ArrayList<>();
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postsap : dataSnapshot.getChildren() ) {
DataSnapshot data = postsap.child("name");
if(data.exists()){
a = data.getValue().toString();
}
store.add(a);
String Id = postsap.getKey();
UserID.add(Id);
}
faculty_list = new String[store.size()];
for(int i=0;i<faculty_list.length;i++){
faculty_list[i] =store.get(i);
}
if (getActivity() != null) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, faculty_list);
listview.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getContext(),Faculty.class);
i.putExtra("User_Id",UserID.get(position));
startActivity(i);
}
});
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
String name = faculty_list[position];
Toast.makeText(getContext(), ""+UserID.get(position), Toast.LENGTH_SHORT).show();
DialogFragment dialogFragment =new MyDailogFragment();
Bundle bundle =new Bundle();
bundle.putString("Name",name);
bundle.putString("Id",UserID.get(position));
dialogFragment.setArguments(bundle);
dialogFragment.show(getChildFragmentManager(),"missiles");
return true;
}
});
return root;
}
}
This is my Dialog Box Code,I am calling this Dialog box with .setOnItemLongClickListener from my ListofFaculty fragment.
MyDailogFragment
public class MyDailogFragment extends DialogFragment {
DatabaseReference dailog;
String Id;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Bundle bundle = getArguments();
final String name= bundle.getString("Name","");
Id = bundle.getString("Id","");
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setMessage("Delete "+name+ " ?")
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(), ""+Id, Toast.LENGTH_SHORT).show();
dailog = FirebaseDatabase.getInstance().getReference("Faculty").child(Id);
dailog.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
dataSnapshot.getRef().removeValue();
Toast.makeText(getActivity(), name+" Deleted Successfully ", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(), "Nothing", Toast.LENGTH_SHORT).show();
}
});
return alertDialog.create();
}
}
You have to clear old data when have new value
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
store.clear();
for(DataSnapshot postsap : dataSnapshot.getChildren() ){
DataSnapshot data = postsap.child("name");
if(data.exists()){
a = data.getValue().toString();
}
store.add(a);
String Id = postsap.getKey();
UserID.add(Id);
}
faculty_list = new String[store.size()];
for(int i=0;i<faculty_list.length;i++){
faculty_list[i] =store.get(i);
}
if (getActivity() != null) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, faculty_list);
listview.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I have a list that I saved in sharedpreferences I want to delete an item from the listview when the user longclicks so on the long click the app prompts you with a question to delete or not when you confirm it deletes it. This works but when i come back to the activity the list still contains that item that has been deleted
This is the code for the onCreateView. tinyDB is sharedprefrences.Thank you
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tab_secondsemester, container, false);
btnAddNew = (Button)rootView.findViewById(R.id.btnAddNewYearOneSecondSemester);
listView = (ListView)rootView.findViewById(R.id.listViewSubjectsMyCoursesSecondSemester);
tinyDB = new TinyDB(getContext());
storedList = new ArrayList<>(tinyDB.getListString("storedList"));
generalList = new ArrayList<>();
spinnerValues = new ArrayList<>();
getActivity().setTitle("Year One");
setHasOptionsMenu(true);
btnAddNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext(),R.style.DialogeTheme);
// Setting Dialog Title
alertDialog.setTitle("Add new");
// Setting Dialog Message
String getUsername = tinyDB.getString("Username");
alertDialog.setMessage("Hello "+ getUsername + ", please write the new subject");
final EditText input = new EditText(getContext());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
input.setTextColor(Color.parseColor("#f06292"));
alertDialog.setView(input);
alertDialog.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String getSubjectInput = input.getText().toString();
storedList.add(getSubjectInput);
tinyDB.putListString("storedList", storedList);
arrayAdapter.notifyDataSetChanged();
}
});
alertDialog.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.create();
alertDialog.show();
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> adapterView, View view, final int i, long l) {
new SweetAlertDialog(getContext(), SweetAlertDialog.WARNING_TYPE)
.setTitleText("Delete")
.setContentText("Are you sure you want to delete this course")
.setConfirmText("YES")
.setCancelText("NO")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
storedList.remove(i);
arrayAdapter.notifyDataSetChanged();
tinyDB.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
arrayAdapter.notifyDataSetChanged();
}
});
sweetAlertDialog.dismiss();
}
})
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.dismiss();
}
})
.show();
return true;
}
});
arrayAdapter = new CustomListAdapter(getContext(),storedList);
listView.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
return rootView;
}
Use this when the user deletes it
public void removeAt(int position) {
mDataset.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mDataSet.size());
}
mDataset is the array/list in which you save all the data for the adapter
I am trying to fetch some data from parse, but my app is getting crashed every time due to this error: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) at java.util.ArrayList.get(ArrayList.java:308) at com.abc.xyz.AcceptARequest$1$1.done(AcceptARequest.java:157)
Here's AcceptARequest.java(in which I'm fetching data from parse) file's code :
public class AcceptARequest extends Fragment{
private OnFragmentInteractionListener mListener;
public List<ListContentAAR> listContentAARs;
public RecyclerView recyclerView;
ImageView hPicAccept;
TextView hDescriptionAccept, currentCoordinatesTagAccept, currentLatAccept, currentLngAccept, post_date, post_time, posted_by;
String hDescriptionAcceptS, currentCoordinatesTagAcceptS, currentLatAcceptS, currentLngAcceptS, post_dateS, post_timeS, posted_byS;
Button btn_accept, btn_share;
LinearLayout latContainerAccept, lngContainerAccept, dateTimeContainer;
ParseQuery<ParseObject> query;
String hDescription, cLat, cLng;
public AcceptARequest() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_accept_a_request, container, false);
listContentAARs = new ArrayList<>();
hPicAccept = (ImageView) rootView.findViewById(R.id.h_pic_accept);
hDescriptionAccept = (TextView) rootView.findViewById(R.id.h_description_accept);
currentCoordinatesTagAccept = (TextView) rootView.findViewById(R.id.currentCoordinatesTagAccept);
currentLatAccept = (TextView) rootView.findViewById(R.id.currentLatAccept);
currentLngAccept = (TextView) rootView.findViewById(R.id.currentLngAccept);
btn_accept = (Button) rootView.findViewById(R.id.btn_accept);
btn_share = (Button) rootView.findViewById(R.id.btn_share);
latContainerAccept = (LinearLayout) rootView.findViewById(R.id.latContainerAccept);
lngContainerAccept = (LinearLayout) rootView.findViewById(R.id.lngContainerAccept);
dateTimeContainer = (LinearLayout) rootView.findViewById(R.id.date_time_container);
post_date = (TextView) rootView.findViewById(R.id.post_date);
post_time = (TextView) rootView.findViewById(R.id.post_time);
posted_by = (TextView) rootView.findViewById(R.id.posted_by);
hDescriptionAcceptS = hDescriptionAccept.getText().toString();
currentCoordinatesTagAcceptS = currentCoordinatesTagAccept.getText().toString();
currentLatAcceptS = currentLatAccept.getText().toString();
currentLngAcceptS = currentLngAccept.getText().toString();
post_dateS = post_date.getText().toString();
post_timeS = post_time.getText().toString();
posted_byS = posted_by.getText().toString();
currentCoordinatesTagAccept.setVisibility(View.INVISIBLE);
currentLatAccept.setVisibility(View.INVISIBLE);
currentLngAccept.setVisibility(View.INVISIBLE);
latContainerAccept.setVisibility(View.INVISIBLE);
lngContainerAccept.setVisibility(View.INVISIBLE);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
query = ParseQuery.getQuery("HomelessDetails");
query.whereEqualTo("objectId", ParseUser.getCurrentUser().getObjectId());
query.addDescendingOrder("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e == null) {
currentCoordinatesTagAccept.setVisibility(View.VISIBLE);
currentLatAccept.setVisibility(View.VISIBLE);
currentLngAccept.setVisibility(View.VISIBLE);
latContainerAccept.setVisibility(View.VISIBLE);
lngContainerAccept.setVisibility(View.VISIBLE);
hDescriptionAcceptS = list.get(1).getString("hDescription");
hDescriptionAccept.setText(hDescriptionAcceptS);
currentLatAcceptS = list.get(1).getString("hLatitude");
currentLatAccept.setText(currentLatAcceptS);
currentLngAcceptS = list.get(1).getString("hLongitude");
currentLngAccept.setText(currentLngAcceptS);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(e.getMessage());
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}, 1000);
recyclerView = (RecyclerView) rootView.findViewById(R.id.accept_request_list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Button btnAccept = (Button) view.findViewById(R.id.btn_accept);
btnAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.request_accepted_txt);
builder.setPositiveButton("Navigate me", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getActivity(), "Navigating you to the needy...", Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getActivity(), "The help-request has been rejected.", Toast.LENGTH_LONG).show();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
Button btnShare = (Button) view.findViewById(R.id.btn_share);
btnShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// share the help-request here.
}
});
}
#Override
public void onLongClick(View view, int position) {
}
}));
initializeAdapter();
return rootView;
}
private void initializeAdapter(){
RVAdapterAAR adapter = new RVAdapterAAR(listContentAARs);
recyclerView.setAdapter(adapter);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public void itemClicked(View view, int position) {
}
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));
}
super.onLongPress(e);
}
});
}
#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) {
}
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
I don't know what's going wrong here.
Please let me know.
Please cooperate if question seems to be badly formatted, I'm still learning to post good questions.
You are trying to access the ArrayList which does not have any element in it. SO list.get(1) won't work.
Make sure that your ArrayList is getting populated correctly.
#Hammad:
The error that you are getting is because of the array list that you are using does not contain any elements/objects in it.
You need to populate the arraylist using list.Add()(or based on your preference) method.