Not Able to delete listItem from ListView Android - java

I am using this code in order to do this, but it is not functional at this point. I can select the checkbox, and when I click the button, nothing happens.
SimpleAdapter adapter;
List<HashMap<String, String>> painItems = new ArrayList<HashMap<String, String>>();
ListView listthings;
...
cb = (CheckBox)findViewById(R.id.checkBox1);
adapter = new SimpleAdapter(this, painItems, R.layout.mylistlayout,
from, to);
listthings.setAdapter(adapter);
listthings.setOnItemClickListener(this);
deleteButton = (Button) findViewById(R.id.deleteButton);
deleteButton.setOnClickListener(this);
...
public void onClick(View v) {
if (v == this.deleteButton) {
// Toast.makeText(this, "delete clicked", Toast.LENGTH_SHORT).show();
deleteCheckedItems();
}
}
...
private void deleteCheckedItems() {
int count = this.listthings.getAdapter().getCount();
for (int i = 0; i < count; i++) {
if (this.listthings.isItemChecked(i)) {
painItems.remove(i);
adapter.notifyDataSetChanged();
listthings.invalidateViews();
}
}
Any help appreciated. Thank You in advance.

1) do not put adapter.notifyDataSetChanged(); into your loop but after deleteCheckedItems();
2) Why did you use: listthings.invalidateViews(); ? You can remove this line, this will redraw your list
3) why havn't you accepted my answer here: How to implement check box in listView Android to delete listItems
4) have you tested a toast after painItems.remove(i); that will show you if items are really removed? Or maybe just after calling deleteCheckedItems(), display the new painItems to see if everything worked

Related

How to show income in intent string array at recyclerview android?

In my application I have draft messages which I can edit. Some of my drafts include attachments which I try to send to my edit activity and show it at recyclerview. In general I have managed to send my string arraylist and get it at my activity. But I can't show my attached files, especially their names at the recyclerview. I tried to make smth like that:
adapter.notifyDataSetChanged();
but it didn't help me.
So, firstly I get from my message names of attached files:
file_name = Objects.requireNonNull(response.body()).getAttachesNames();
then put this names into arraylist:
nameList = new ArrayList<>(Arrays.asList(file_name));
such result I can see in my logs:
W: [eZV9f.jpg, index.html]
and then I send my list via intent to another activity:
intent2.putStringArrayListExtra("attached_files", (ArrayList<String>) nameList);
receiving data from intent:
Intent intent = getIntent();
extras = intent.getExtras();
if (extras != null) {
if (extras.containsKey("attached_files")) {
draft_files = getIntent().getStringArrayListExtra("attached_files");
Log.w("MY_TAG", String.valueOf(draft_files));
}
}
results from logcat:
W: [eZV9f.jpg, index.html]
initialising of my adapter and recyclerview:
adapter = new AttachedFileAdapter(mNames);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(WriteResponseMess.this, LinearLayoutManager.VERTICAL, false));
and then I try to get single element from this list and add to my ArrayList<>:
for (int i = 0; i < draft_files.size(); i++) {
mNames.addAll(Collections.singleton(draft_files.get(i)));
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
Log.w("MY_TAG", draft_files.get(i));
Log.w("MY_TAG", String.valueOf(mNames));
}
all previous pieces of code are used at my onCreate() method and as a result of all these actions I would like to see income data from another activity. Sometimes I managed to do it, but one element contained all income data and looked like this:
[eZV9f.jpg, index.html]
and it was wrong for me. I try to create the list which will contain all elements separately. I also tried to use some info from this link which is connected with Collections, but I didn't manage to reach the goal of my task. In general I'm sure that the solution is very simple but I can't see it.
update
all my activity class has more than 1000 lines and I will share all code which is connected with adding attachments and show attached data at my writing form:
Here is my dialog for getting directory list and choosing some files:
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case CUSTOM_DIALOG_ID:
dialog = new Dialog(WriteResponseMess.this, android.R.style.Theme_DeviceDefault_Light_NoActionBar_Fullscreen);
dialog.setContentView(R.layout.dialog_layout);
dialog.setCanceledOnTouchOutside(true);
Toolbar toolbar = dialog.findViewById(R.id.toolbar_d);
toolbar.setTitle("Add a new file.");
textFolder = dialog.findViewById(R.id.folder);
buttonUp = dialog.findViewById(R.id.up);
buttonUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ListDir(curFolder.getParentFile());
}
});
dialog_ListView = dialog.findViewById(R.id.dialoglist);
final Dialog finalDialog1 = dialog;
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
File selected = new File(curFolder, fileList.get(position));
if (selected.isDirectory()) {
ListDir(selected);
}
if (selected.isFile()) {
if (array.size() == 0) {
array = uploadFiles(array, selected.getName(), convertFileToString(selected.getPath()));
adapter.notifyDataSetChanged();
getImages();
} else {
if (array.toString().contains(selected.getName())) {
Toast.makeText(WriteResponseMess.this, R.string.attaching_message, Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
getImages();
} else {
array = uploadFiles(array, selected.getName(), convertFileToString(selected.getPath()));
adapter.notifyDataSetChanged();
getImages();
}
}
finalDialog1.dismiss();
ms.setArray(array);
}
}
});
break;
}
return dialog;
}
and method for showing attached list, and in general this method works when I create a new message and attach a new file, it works fine:
private void getImages() {
mNames.clear();
adapter.notifyDataSetChanged();
for (int i = 0; i < array.size(); i++) {
JsonObject object = array.get(i).getAsJsonObject();
if (extras != null) {
if (extras.containsKey("attached_files")) {
for (int j = 0; j < draft_files.size(); j++) {
mNames.clear();
mNames.add(draft_files.get(j));
adapter.notifyDataSetChanged();
//Log.w("MY_TAG", draft_files.get(i));
Log.w("MY_TAG", String.valueOf(mNames));
}
mNames.add(object.get("filename").toString().substring(1, object.get("filename").toString().length() - 1));
adapter.notifyDataSetChanged();
//Log.w("MY_TAG", Arrays.toString(draft_files));
Log.w("MY_TAG", Arrays.toString(new ArrayList[]{mNames}));
} else {
mNames.add(object.get("filename").toString().substring(1, object.get("filename").toString().length() - 1));
adapter.notifyDataSetChanged();
Log.w("MY_TAG", String.valueOf(mNames));
}
}
}
}
no need to set Adapter twice . remove this line
recyclerView.setAdapter(adapter);
From
for (int i = 0; i < draft_files.size(); i++) {
mNames.addAll(Collections.singleton(draft_files.get(i)));
adapter.notifyDataSetChanged();
//recyclerView.setAdapter(adapter); no need
Log.w("MY_TAG", draft_files.get(i));
Log.w("MY_TAG", String.valueOf(mNames));
}

Display a SQLite colum one value after another

I'm really strugling to figure this out and had not found an answer or a way to do it.
What I'm trying to do is having questions that are saved in a SQLite colum to be displayed in a TextView one after another until they finish.
What I have done so far on the main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabaseHelper = new DatabaseHelper(this);
btn1star = (Button) findViewById(R.id.btn1star);
btn2star = (Button) findViewById(R.id.btn2star);
btn3star = (Button) findViewById(R.id.btn3star);
mListview = (ListView) findViewById(R.id.qlistview);
qTextView = (TextView) findViewById(R.id.qTextView);
questionsListView();
}
private void questionsListView() {
Cursor data = mDatabaseHelper.getData();
data.moveToFirst();
qTextView.setText(data.getString(1));
}
public void VoteClick(View view){
mDatabaseHelper.getReadableDatabase();
Cursor data = mDatabaseHelper.getData();
if (data.getCount() >=1){
for (int i = 0; i< data.getCount(); i++) {
data.moveToNext();
Log.i("Counted Questions are: ", String.valueOf(data.getCount()));
qTextView.setText(data.getString(1));
}
}
}
private void toastmessage (String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
I'm able to display the first and when i click the button the last question
I'm unable to display the questions between.
Any tip or suggestion?
In your VoteClick method you do your getReadableDatabase, this is too late, move this line into onCreate method. You must open the database before reading from it (in questionsListView).
mDatabaseHelper.getReadableDatabase();//move to onCreate
add this:
startManagingCursor(data);
data.moveToFirst();
BEFORE the line:
if (data.getCount() >=1){
Hello found a solution to my problem
It turns out that i have to make a new int variable
Get its value from the first id
and incrise this by one at the end of each button press until i reach the last cursor place whhere i move the cursor to the first position
public void VoteClick(View view) {
Cursor data = mDatabaseHelper.getData();
data.moveToPosition(q);
data.moveToNext();
qTextView.setText(data.getString(1));
while (data.isLast()) {
data.moveToFirst();
q = data.getPosition();
}
q = q+1;
}

List.setAdapter(thadapter); not work always + screen errors

Hello I have a problwm witch Listview.
I use listview for show items in list.
I have activity where is Listview. And If I longpress on row in listview open popup (dialog) where I can edit word in row.
If edit finish I Call this
AddItemInPacage.obnovitem=true;
AddItemInPacage.indexitem=poz;
AddItemInPacage.novyitem=novypacage;
Boolean is for Timer if is true Start This method
public void ZmenItem(int indexzmeny,String nove) {
ListAdapter.clear();
for (int i=1;i<prvy.getPacageItem2(indexpacage)+1;i++) {
ListAdapter.add(String.valueOf(prvy.citajItem(indexpacage,i)));
}
ListAdapter.set(indexzmeny,nove);
Toast.makeText(this, "citam "+ ListAdapter.get(indexzmeny), Toast.LENGTH_SHORT).show();
thadapter = new MyThumbnailAdapter(getApplication(), R.layout.list_row, ListAdapter);
List.setAdapter(thadapter);
thadapter.notifyDataSetChanged();
}
Everything is OK when I while I not open the same row. If edited row for some times in row Program not work good.
Everything is good while this line List.setAdapter(thadapter); after thise line is Variables good too, but listview in display not rewrite.
Why?
I have three times this List.setAdapter(thadapter); on program but on OnCreate method and when Put new row in listview... So when Edited row I call only thise method ↑↑ which sometimes rewrite good and sometimes not.
Because Thise program isn't it 100% good :(
ListView List;
MyThumbnailAdapter thadapter = null;
ArrayList<String> ListAdapter = new ArrayList<String>();
This is my Adapter
public class MyThumbnailAdapter extends ArrayAdapter<String> {
ArrayList<String> arr;
private TextView text;
public MyThumbnailAdapter(Context context, int textViewResourceId, ArrayList<String> objects) {
super(context, textViewResourceId, objects);
this.arr = objects;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = null;
LayoutInflater inflater = getLayoutInflater();
view = inflater.inflate(R.layout.list_row, parent, false);
TextView textnumber = (TextView) view.findViewById(R.id.text);
ImageView delButton = (ImageView) view.findViewById(R.id.btn_del);
Typeface robtoLight = Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Light.ttf");
textnumber.setTypeface(robtoLight);
delButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
arr.remove(position);
thadapter.notifyDataSetChanged();
Toast.makeText(getContext(), "Item deleted", Toast.LENGTH_SHORT).show();
}
});
textnumber.setText(arr.get(position));
textnumber.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
for (int i=ListAdapter.size()-1;i>=0;i--) {
// for (int i = 0; i < ListAdapter.size() ; i++) {
try {
prvy.pridajItemRemove(ListAdapter.get(i), indexpacage, i+1);
} catch(IndexOutOfBoundsException e) {
prvy.Nulak(indexpacage,i);
}
}
prvy.setPacageItem2(ListAdapter.size(),indexpacage);
prvy.setPocItem(ListAdapter.size());
for (int i=ListAdapter.size();i<99;i++) {
prvy.Nulak(indexpacage,i+1);
}
Serializuj(prvy,nazovtripu);
EditItemDialog cdd=new EditItemDialog(AddItemInPacage.this,nazovtripu,position,indexpacage);
cdd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
cdd.show();
return true;
}
});
return view;
}
}
I put picture
Sometimes if I edit row Toas read good string, but Listview no rewrite.
This may help you
ListAdapter.notifyDataSetChanged()
Hoping ListAdapter is name of your adapter
I need synchronized confirm edit in Dialog with medhod which rewrite Listview.
Or switch sequence from
AddItemInPacage.obnovitem=true;
AddItemInPacage.indexitem=poz;
AddItemInPacage.novyitem=novypacage;
to
AddItemInPacage.indexitem=poz;
AddItemInPacage.novyitem=novypacage;
AddItemInPacage.obnovitem=true;
Because If AddItemInPacage.obnovitem=true; first Activity work with old information in variable novypacage. And when variable novypacage is full from dialog. Listview finish work with old information in this variable.

Cannot resolve constructor ArrayAdapter when using ListView in Android Studio

I have an activity Mainactivity, in this when a button is pressed then it will show a listview. But in
listAdapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, android.R.id.text1, value);
I am getting "Cannot resolve constructor ArrayAdapter (anonymous android view.View.OnClickListener, int, int, java.lang.String)"
My outer class is "Mainactivity" I tried "Mainactivity.this" instead of "this". But It is showing "cannot resolve constructor" error.
MainActivity class extends Actionbaractivity implements onItemelectedListner
My code is:
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(cnt.getText().toString().length() > 0 &&
number.getText().toString().length() > 0 &&
Integer.parseInt(number.getText().toString()) > 0 &&
Integer.parseInt(cnt.getText().toString()) > 0) {
number.requestFocus();
String[] value = new String{"hello","world"};
try {
temp_count = temp_count + Integer.parseInt(cnt.getText().toString());
count.setText(String.valueOf(temp_count));
temp_amt = temp_amt + (Integer.parseInt(cnt.getText().toString()) * tkt_rate);
amount.setText(String.valueOf(temp_amt));
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, value);
lstView.setAdapter(listAdapter);
lstView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
SparseBooleanArray checked = lstView.getCheckedItemPositions();
int size = checked.size(); // number of name-value pairs in the array
for (int i = 0; i < size; i++) {
int key = checked.keyAt(i);
boolean value = checked.get(key);
if (value) {
row = lstView.getChildAt(i);
row.setBackgroundColor(Color.parseColor("#33B5E5"));
} else {
row = lstView.getChildAt(i);
row.setBackgroundColor(Color.parseColor("#F0F0F0"));
}
}
}
});
Please help...
The error shows that you are putting android view.View.OnClickListener as the first argument.
I know you said you have tried, but you really need to use Mainactivity.this. If it is not working please post the code of the start of your java file.
Also is your activity named as Mainactivity? Remember it is case sensitive, should it be MainActivity? If so, you have to use MainActivity.this
I think it's happening because your class implements onclicklistener. So can you try cast this to Activity? Like the code below:
listAdapter = new ArrayAdapter((Activity)this, android.R.layout.simple_list_item_1, android.R.id.text1, value);
ArrayAdapter needs Context as the first argument. What you can do is to have a field reference to your Context, like the followings.
Added a field to your Activity, private Context mContext;
Inside the onCreate() of your Activity, mContext = this;
Use the mContext to construct ArrayAdapter, listAdapter = new ArrayAdapter(mContext, android.R.layout.simple_list_item_1, android.R.id.text1, value);
Maybe this will help you:
listAdapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1,
android.R.id.text1,
Collections.singletonList(value));

Error comming on maketext in toast

public void onClick(View v) {
{
if (db==null) db = new DB(AddStation.this);
if(v.getId()==R.id.ADD ) {
String code = Scode.getText().toString().trim();
String name = SName.getText().toString().trim();
String fac = SFac.getText().toString().trim();
if(name.equals("")){
Scode.setError("Invalid name");
return;
}
if (code.equals("")){ Scode.setError("Invalid email");
return;
}
if (db.addStudent(code, name, fac))
Toast.makeText(AddStation.this, "Student added", Toast.LENGTH_SHORT).show();
else if (v.getId()==R.id.See) {
Toast.makeText(AddStation.this, db.getAllStudents(), Toast.LENGTH_LONG).show();
//Log.v("EditText", db.getAllStudents().toString());
}
}
}
db.close();
Toast.makeText(AddStation.this, db.getAllStudents(), Toast.LENGTH_SHORT).show();
}
}
AddStation is my Fragment name. how to solve this ?
this toast is retriving database and can u guys tell me how to bring data into a dropdown box or gridview instead of a toast. thanks!
Look at the last two lines. First you called db.close();, then called db.getAllStudents(), so ARE YOU KIDDING?
But if not this caused error, then post you logcat trace
PS:check your AddStation, is it extended from Activity or its descendants? If not, extend your AddStation from Activity or its descendants.
You can display this data in List/Spinner, for this you had to add these widgets in your layout. You can populate this data as
1. ListView
ListView listView = (ListView) findViewById(R.id.mylist);
List<String> listRecords = db.getAllStudents();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item, listRecords);
listView.setAdapter(arrayAdapter);
2. Spinner
Spinner spinner = (Spinner) findViewById(R.id.spinner);
List<String> listRecords = db.getAllStudents();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, listRecords);
spinner.setAdapter(arrayAdapter);

Categories

Resources