I have a delete all button and everytime it delete all item in a listview, the listview won't road but stay the same, they will reload only when I create a new item or restart this activity. I have print a log on my code and it seems that the list view reload before the delete method called. my code is this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DBHelper db = new DBHelper(this);
final ListView listView = (ListView) findViewById(R.id.listView);
TextView empty = (TextView) findViewById(R.id.empty);
ArrayList<Inventory> listArray = new ArrayList<>();
listArray.clear();
listArray = db.read();
if (listArray.size() == 0) {
empty.setText("No Items");
} else {
empty.setText("");
}
ListViewAdapter customAdapter = new ListViewAdapter(listArray);
customAdapter.notifyDataSetChanged();
listView.setAdapter(customAdapter);
Button add_button = (Button) findViewById(R.id.button);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addNewItem(view);
}
});
Button button_deleteAll = (Button) findViewById(R.id.button_deleteAll);
button_deleteAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deteleAll();
DBHelper db = new DBHelper(MainActivity.this);
final ListView listView = (ListView) findViewById(R.id.listView);
TextView empty = (TextView) findViewById(R.id.empty);
ArrayList<Inventory> listArray = new ArrayList<>();
listArray.clear();
listArray = db.read();
Log.v("arraysize:", String.valueOf(listArray.size()));
if (listArray.size() == 0) {
empty.setText("No Items");
} else {
empty.setText("");
}
ListViewAdapter customAdapter = new ListViewAdapter(listArray);
customAdapter.notifyDataSetChanged();
listView.setAdapter(customAdapter);
}
});
}
The method deleteAll() deletes all the data in SQLite.
I wish to know how to reload listview after this method called, rather than reload before this method.
add the delete all method in your adapter. call the deleteAll method of your adapter whenever button was clicked. the deleteAll method would be like below:
public void setListArray(ArrayList arrayList)
{
//assuming your adapter list is named "listArray"
this.listArray = arrayList;
notifyDataSetChanged();
}
and in your button click simply write this code:
button_deleteAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//assuming your list of itames here is named "mListArray"
mListArray.clear();
adapter.setListArray(mListArray);
}
}
I guess there is no need to initialize the customAdapter again in the button OnClick method. Also no need to setAdapter again.
Try to remove these lines in the onClick method.
Hope this fixes you issue.
Just add notifyDataSetChanged(); to your Adapter, inside a Listener. For example:
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> parent, android.view.View view, int position, long id) {
myArrayList.remove(position);
myArrayAdapter.notifyDataSetChanged();
}
});
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to populate a ListView using an ArrayAdapter that I am filling with input from an EditText. My program seems to compile fine but during app start up it immediately crashes. I suspect that it has something to do with me trying to set-up my list view. I am not sure what I am initializing wrong such that my app instantly crashes. Any and all tips would be greatly appreciated. Thanks in advance!
This is my global declarations for my ArrayList and Adapter.
ArrayList<scoreScreen> savedScores = new ArrayList<>();
ScoreAdapter adapter = new ScoreAdapter(this, savedScores);
ListView listView = (ListView) findViewById(R.id.dispScores);
listView.setAdapter(adapter);
My Adapter Class:
private class ScoreAdapter extends ArrayAdapter<scoreScreen> {
private ScoreAdapter(Context context, ArrayList<scoreScreen> scores) {
super(context, 0, scores);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
scoreScreen score1 = getItem(position);
if (convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_scores, parent, false);
}
TextView holeNum = (TextView) convertView.findViewById(R.id.holeNum);
holeNum.setText(score1.hole);
return convertView;
}
}
My ListView inside of my onCreate method.
ListView listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
I am assuming my problem is not inside my EditText inputs since they are inside of an OnClickListener method, but just incase I have attached it below.
public View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText input1 = (EditText) findViewById(R.id.scorePrompt);
TextView output1 = (TextView) findViewById(R.id.textTotal);
String blankCheck = input1.getText().toString(); //CHANGE INPUT IN scorePrompt TO STRING
switch (view.getId()) {
case R.id.buttTotal:
if (blankCheck.equals("")) {
Toast blankError = Toast.makeText(getApplicationContext(), "YOU CANT SKIP HOLES JERK", Toast.LENGTH_LONG);
blankError.show();
break;
} else {
int num1 = Integer.parseInt(input1.getText().toString()); //Get input from text box
int sum = num1 + score2;
score2 = sum;
output1.setText("Your score is : " + Integer.toString(sum));
//savedScores.add(input1.getText().toString());
scoreScreen addScore = new scoreScreen("Score is" + num1);
adapter.add(addScore);
j++;
input1.setText(""); //Clear input text box
break;
}
case R.id.allScores: //CHANGE THIS TO AN EDIT BUTTON, ADD A HOLE NUMBER COUNTER AT TOP OF SCREEN!!!!!
output1.setText("you messed up");
break;
case R.id.editScore: //Need to set up Save Array before we can edit
//CURRENTLY ONLY DISPLAYS THE LAST NUNMBER IN THE TEXTEDIT, NEED TO SET UP LISTVIEW!!!!!!
for (int i=0; i < j; i++){
// output1.setText(savedScores.get(i));
} break;
}
}
};
onCreate method added as requested:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Button scoresAct = (Button) findViewById(R.id.allScores); //THIS IS TO GO TO ALL SCORES ACTIVITY
scoresAct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent scoreScreen = new Intent(MainActivity.this, AllScoresAct.class);
startActivity(scoreScreen);
}
});*/
Button sumScores = (Button) findViewById(R.id.buttTotal);
Button saveScores = (Button) findViewById(R.id.allScores);
Button changeScores = (Button) findViewById(R.id.editScore);
sumScores.setOnClickListener(onClickListener);
saveScores.setOnClickListener(onClickListener);
changeScores.setOnClickListener(onClickListener);
ListView listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
}
After moving my adapter and ArrayList into my onCreate, I get a new error. I did some research on null pointers, but I have already initialized both of these. Below is my logcat, any ideas? Thanks
Make sure super.onCreate(savedInstanceState) is the first thing you are calling in your onCreate() and also not trying to access any view from the layout xml before setContentView().
EDIT:
Initialize the adapter in onCreate() method instead of doing it globally.
onCreate() {
.......
this.adapter = new ScoreAdapter(this, savedScores);
}
This is my global declarations for my ArrayList and Adapter.
ArrayList<scoreScreen> savedScores = new ArrayList<>();
ScoreAdapter adapter = new ScoreAdapter(this, savedScores);
You can declare those globally, but for the Adapter, the this parameter must be used within/after onCreate, as the error says
System services not available to Activities before onCreate()
For example
private ArrayList<ScoreScreen> savedScores = new ArrayList<>();
private ScoreAdapter adapter;
#Override
protected void onCreate(Bundle b) {
...
adapter = new ScoreAdapter(this, savedScores);
}
I call my specific ArrayAdapter from an Activity which shows a list of datasets from my database. If the user tap on an item of the ArrayAdapter it will open an extension of an AlertDialog. If the user taps on a button in this AlertDialog a dataset in the database will be deleted among others and the AlertDialog is dismiss(). Now I want to refresh the view of the ArrayAdapter.
I found solutions like
remove(position);
notifyDataSetChanged();
But where could I call this? Can I pass a boolean from the AlertDialog backwards to the ArrayAdapter if the user clicked on the specific button to say "hey adapter, please remove the current item in your list"?
here's some code:
Activity:
final ListView list = (ListView) findViewById(R.id.myList);
DBhandler db = new DBhandler (context);
list.setAdapter(new MyAdapter(context, db.getMyItems()))
MyAdapter:
public View getView(int position, View row, ViewGroup parent) {
if(row != null) {
row.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final MyDialog myDialog = new MyDialog(context, currentItem);
myDialog.show();
}
});
}
}
MyDialog:
protected void onCreate(Bundle savedInstanceState) {
Button btn_delete = (Button) findViewById(R.id.btn_delete);
btn_delete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DBhandler db = new DBhandler (context);
db.delete(currentItem);
Toast.makeText(context, "item is deleted", Toast.LENGTH_SHORT).show();
dismiss();
}
});
}
I found also Passing Events Back to the Dialog's Host, but I don't know how I can use that for my AlertDialog...
You may call function of your custom adapter before dismissing alert dialog as
if(adapter.remove(postion)){
adapter.refreshdata();
}
and the function like
public boolean removedata(int position){
boolean isremoved = false;
// loop array data and remove specific item
// and return isRemoved value.
}
public void refreshdata(){
notifyDataSetChanged();
}
so far i have an android app which can save data (Simple text) into a sqlite database and display it in to a list view. I would like to be able to add images as well but i dont know how.
here is the class which creates the rows everytime i add some text:
public class TestDatabaseActivity extends ListActivity {
private CommentsDataSource datasource;
int holanumero;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_database);
datasource = new CommentsDataSource(this);
datasource.open();
List<Comment> values = datasource.getAllComments();
// use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this, android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
final ListView listadeutiles = (ListView) findViewById(android.R.id.list);
//
listadeutiles.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
holanumero = position;
}});
}
// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
#SuppressWarnings("unchecked")
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
Comment comment = null;
switch (view.getId())
{
case R.id.add:
EditText texto1 = (EditText) findViewById(R.id.editText1);
String palabra1 = texto1.getText().toString();
EditText texto2 = (EditText) findViewById(R.id.editText2);
String palabra2 = texto2.getText().toString();
String palabra3 = palabra1 + palabra2;
comment = datasource.createComment(palabra3);
adapter.add(comment);
texto1.setText("");
texto2.setText("");
break;
case R.id.delete:
if (getListAdapter().getCount() > 0) {
comment = (Comment) getListAdapter().getItem(holanumero);
datasource.deleteComment(comment);
adapter.remove(comment);
}
break;
}
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
Saving images in the database is rarely I good idea. You should store the file path to the image in the sd card, and then load that image in your getView() method in the ListView's adapter.
I would like to select and deselect all the items in the listview using "SelectAll" and "DeselectAll" buttons. I wrote the code for SelectAll but it throws a NullPointException. I couldn't find the bug in my code. Can someone point out the error in my code.
final ListView list;
String[] listItems = { "Enabled" };
list = (ListView)findViewById(R.id.list);
list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, getResources().getStringArray(R.array.facilities)));
list.setItemsCanFocus(false);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
CheckedTextView ctv = (CheckedTextView)arg1;
//other functionality!
}
});
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(View view) {
int itemCount = getListView().getCount();
System.out.print(itemCount);
for (int i = 0; i < itemCount; i++){
list.setItemChecked(i, true);
//getListView().setItemChecked(i, chk.isChecked());
}
}
};
Button button = (Button) findViewById(R.id.selectAll);
button.setOnClickListener(clickListener);
try to use below code...
private OnClickListener checkAllCheckboxes = new OnClickListener()
{
public void onClick(View v)
{
ListView lv = getListView();
int size = getListAdapter().getCount();
if(lv.isItemChecked(0))
{
for(int i = 0; i<=size; i++)
{
lv.setItemChecked(i, false);
}
}
}
}
};
You Can create One ArrayList of data class
class data
{
boolean chekced=false
create setter and getter of this
}
Create ArrayList of Data Class intially Chekced is false in all arraylist items
When select is called set all items to true
Then moify adpater and call notifyDatasetChanged on listView
This is how you can do this
I've a list view with a header. There is a 'Go' button in the list header. And for its on click I need to call a custom method in the Custom Adapter. How can I get the Adapter reference in side onlick lister?
public class GroupListActivity extends ListActivity {
...
private void createGroupList() {
final ListView listView = getListView();
final View view = getLayoutInflater().inflate(R.layout.multi_list_groups_header, listView, false);
listView.addHeaderView(view, null, true);
TextView listHeader = (TextView) findViewById(R.id.groupsHeader);
Button goButton = (Button) findViewById(R.id.goButton);
this.gAdapter = new GroupAdapter(this, R.layout.multi_list_groups2, gStore, true);
this.setListAdapter(this.gAdapter);
//listView.setFocusable(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
goButton = (Button) findViewById(R.id.goButton);
goButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e(MY_DEBUG_TAG,"Manual Go!!");
// I need to call the adapters' getCheckedItems() method here
}
});
}
Custom Adapter
public class GroupAdapter extends ArrayAdapter<Group> {
...
public HashMap<String, String> getCheckedItems() {
return checkedItems;
}
}
Perhaps you want to create a custom Button that holds on to a reference of your GroupAdapter. That way, you can cast the passed in View object to your custom Button, and then get your GroupAdapter.
#Override
public void onClick(View v) {
Log.e(MY_DEBUG_TAG,"Manual Go!!");
Map<String, String> checkedItems = ((MyButton)v).getGroupAdapter().getCheckedItems();
}