ArrayList not updating - android

I try to update the ArrayList to display it in the Listview from my SQLite database but the list shows up empty. The SQLite works fine because the data shows up in the logs but is not added in the list.
One thing I want to add is that I have also linked this list with Parse to get data online and save it in my Database for offline availability.
The list updates fine when it fetches data from Parse.
public void listUpdater () {
Cursor c = myDB.rawQuery("SELECT * FROM user", null);
int titleIndex = c.getColumnIndex("title");
titles.clear();
if (c.moveToFirst()){
do {
Log.i("RESULT: ",c.getString(titleIndex));
titles.add(c.getString(titleIndex));
} while (c.moveToNext());
adapter.notifyDataSetChanged();
}
}
Here is the method call for the data
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logged_in);
myDB = openOrCreateDatabase("Users", MODE_PRIVATE, null);
myDB.execSQL("CREATE TABLE IF NOT EXISTS user(title VARCHAR)");
adapter = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, titles);
listView = (ListView) findViewById(R.id.listUsers);
listView.setAdapter(adapter);
listUpdater();
titles.clear();
// After this the list is updated from Parse
}

I recommend to use AsyncTask for this problem. Fetch the data from your database in doInBackground() and update the UI/list in onPostExecute().
For more information or examples check this

first of all.. why would you need to set the adapter before you fetch the data. You could do something like this.
show a loading dialog.
fetch the data from db or online/json
parse it.
initialize the adapter
set the adapter to the view.
in case you need to update the list. do a notifyItemChanged(fromPos, list.size());
hope that helps

Related

Update listView and Adapter after update Database

I have external Database and I have to update database from activity with method of update `
public long updateInfo(ModelInsertInfo modelInsertInfo)
{
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID,modelInsertInfo.getId());
values.put(KEY_yearWater, modelInsertInfo.getYearWater());
values.put(KEY_MonthWater, modelInsertInfo.getMonthWater());
values.put(KEY_DayWater, modelInsertInfo.getDayWater());
values.put(KEY_HourWater, modelInsertInfo.getHourWater());
values.put(KEY_MinWater, modelInsertInfo.getMinWater());
return db.update(TABLE_Insert_Info, values, "" + KEY_ID + "= " +
modelInsertInfo.getId() + "", null);
}
database updated but nothing change in list or in activity.
My Inner activity get id from click on listview item and I updated database from inner activity.
I used this
#Override
protected void onResume()
{
super.onResume();
adapterListView.notifyDataSetChanged();
listView.deferNotifyDataSetChanged();
listView.invalidateViews();
clearPref();
}
And this in the onCreate()
adapterListView.notifyDataSetChanged();
adapterListView.notifyDataSetInvalidated();
listView.invalidateViews();
Firstly I recommend using RecyclerView instead of ListView.
Secondly you may delete updating methods from onCreate() and onResume() callbacks, and just do setting updating items to RecyclerView adapter and notifyDataSetChanged. Use getter from databese after database updating for updating RecyclerView items.
RecyclerView documentation: https://developer.android.com/guide/topics/ui/layout/recyclerview
After updating database either update list by adding new value or clear list and get value from database to the list. and then give adapterListView.notifyDataSetChanged();

Sequence of data from SQLite changed while displaying data in RecyclerView

I have stored data in SQLite database. I need to display that data from database in RecyclerView.But first time when Data is retrieved and displayed in RecyclerView it is retrieved in Sequence as stored in database and set on Recyclerview.When I am trying to get the same data from Database and set on RecyclerView its changing the sequence automatically.
This is code to retrieve the data from SQLite database
public ArrayList<ReservationEntry> getDbReservation(){
SQLiteDatabase db = this.getWritableDatabase();
String query="SELECT * FROM "+ RESERVATIONS;
Cursor c=db.rawQuery(query,null,null);
ArrayList<ReservationEntry> reserveList=new ArrayList<>();
if(c.moveToFirst()){
do{
ReservationEntry entry=new ReservationEntry();
entry.setName(c.getString(0));
entry.setNoOfPeople(c.getString(1));
entry.setTime(c.getString(2));
entry.setDate(c.getString(3));
entry.setBirthday(c.getString(4));
entry.setAniversary(c.getString(5));
reserveList.add(entry);
}while (c.moveToNext());
}
return reserveList;
}
This is the code to set RecyclerViewAdapter
private void readDatabaseReservation(final ArrayList<ReservationEntry> dbList) {
adapter=newReservationAdapter(dbList,getActivity().getApplicationContext());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
How to resolve this ?
You must add your adapter this function to change data and call notifyDataSetChanged.
So add this to your adapter
public void setData(ArrayList<ReservationEntry> dbList){
this.yourListData = dbList;
notifyDataSetChanged();
}
And use it like this
private void readDatabaseReservation(final ArrayList<ReservationEntry> dbList) {
adapter.setData(dbList);
}
Hope it's help . for more add your adapter code

android studio ListView is Not populating existing listView items, which are saved in SQlite

updated my code. My issue happens when i back out of the activity. Listview items are lost. I checked the Sqlite database and all items are saved, just not showing up again on listView when I reStart-Activity.
MainActivity
private ListView lst;
private CustomeAdapter cv;
private EditText nameEd, middleEd, lastEd;
private ArrayList<People> peopleArrayList;
private DataHelper myData;
peopleArrayList = new ArrayList<>();
OnCreate.....
public void addPerosn(View view) {
String myName = nameed.getText().toString();
String myMiddle = middleed.getText().toString();
String myLast = lasted.getText().toString();
boolean insert = myData.addData(myName, myMiddle, myLast);
if (insert == true) {
peopleArrayList.add(new People(myName, myMiddle, myLast));
cv = new CustomeAdapter(this, peopleArrayList);
lst.setAdapter(cv);
nameed.setText("");
middleed.setText("");
lasted.setText("");
} else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
}
My DataHelper method i want to call to Show All
public Cursor showData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
Any suggestions are appreciated . Thanks
Make sure you have overridden getCount and it returns proper count.
#Override
public int getCount() {
return items.length;
}
Apart from above solution, I would recomment you to do it in proper way
a) Create a model/pojo class say Person which will have firstName,lastName and middleName
b) create a data set of Person, i.e list of person
c) create a method addPerson in adapter class, and call whenever you want to add new Person data into the list. addPerson method will also refresh the adapter by calling notifyDataSetChanged
d) In activity create adapter object only once, later on just use method of it say adapter.addPerson(person)

Update the Arraylist automatically when the data of the list is updated

While inserting my listview gets refreshed automatically but not update when the item in the listview is updated. It only updates on database. I can see the listview is updated when I close the application and open again, or come back from previous activity.
I found some discussion related to my problem. Like: Refresh ListView with ArrayAdapter after editing an Item . Her I found that make a new method to populate the Listview and call it in the onResume method of your activity.
And the problem has been solved using this. But I do not get how to make new method mentioned like there. Could anybody help me to make it understandable?
My code in activity class:
personNamesListView = (ListView) findViewById(R.id.traineeslist);
traineeListAdapter = new ArrayAdapter<Trainee>(this,
android.R.layout.simple_list_item_1,
currentTraining.getTraineeArrayList());
personNamesListView.setAdapter(traineeListAdapter);
protected void onResume() {
super.onResume();
}
And this way I populated my personNamesListView using method stringToString() in model class;
public void loadTraineeList() {
DatabaseHelper db = DatabaseHelper.getInstance();
this.traineeArrayList = new ArrayList <Trainee>();
Cursor cursor = db.select("SELECT * FROM person p JOIN attendance a ON p._id = a.person_id WHERE training_id="+Integer.toString(this.getId())+";");
while (cursor.moveToNext()) {
Trainee trainee = new Trainee();
trainee.setID(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.PERSON_ID)));
trainee.setFirstname(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_FIRSTNAME)));
trainee.setLastname(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_LASTNAME)));
trainee.setJobTitle(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_JOBTITLE)));
trainee.setEmail(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_EMAIL)));
trainee.setCompany(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_COMPANY)));
trainee.setDepartment(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_DEPARTMENT)));
trainee.setBadgeNumber(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PERSON_BADGE)));
// Pass to the arraylist
this.traineeArrayList.add(trainee);
}
}
public ArrayList<Trainee> getTraineeArrayList() {
return traineeArrayList;
}
public void setTraineeArrayList(ArrayList<Trainee> traineeArrayList) {
this.traineeArrayList = traineeArrayList;
}
I insert and Update data into database into one method:
public void storeToDB() {
DatabaseHelper db = DatabaseHelper.getInstance();
db.getWritableDatabase();
if (this.id == -1) {
// Person not yet stored into Db => SQL INSERT
// ContentValues class is used to store a set of values that the
// ContentResolver can process.
ContentValues contentValues = new ContentValues();
// Get values from the Person class and passing them to the
// ContentValues class
contentValues.put(DatabaseHelper.PERSON_FIRSTNAME, this
.getFirstname().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_LASTNAME, this
.getLastname().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_JOBTITLE, this
.getJobTitle().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_EMAIL, this.getEmail());
contentValues.put(DatabaseHelper.PERSON_COMPANY, this.getCompany()
.trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_DEPARTMENT, this
.getDepartment().trim().toUpperCase());
contentValues.put(DatabaseHelper.PERSON_BADGE, this
.getBadgeNumber().trim().toUpperCase());
// here we insert the data we have put in values
this.setID((int) db.insert(DatabaseHelper.TABLE_PERSON,
contentValues));
} else {
// Person already existing into Db => SQL UPDATE
ContentValues updateTrainee = new ContentValues();
updateTrainee.put(DatabaseHelper.PERSON_FIRSTNAME, this
.getFirstname().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_LASTNAME, this
.getLastname().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_JOBTITLE, this
.getJobTitle().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_EMAIL, this.getEmail());
updateTrainee.put(DatabaseHelper.PERSON_COMPANY, this.getCompany()
.trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_DEPARTMENT, this
.getDepartment().trim().toUpperCase());
updateTrainee.put(DatabaseHelper.PERSON_BADGE, this
.getBadgeNumber().trim().toUpperCase());
db.update(DatabaseHelper.TABLE_PERSON, updateTrainee,
DatabaseHelper.PERSON_ID+"= ?", new String[]{Integer.toString(this.getId())});
System.out.println("Data updated");
}
}
You should call traineeListAdapter.notifyDataSetChanged() whenever you update your ArrayList representing the items in the ListView.
There's a similar question here that can give you some help.
Although I've accomplished something similar using
yourlistview.invalidateViews()
after changing the data to show in the listview
when notifyDataSetChanged() didn't work.
EDIT:
After making all the operations in the data that I want to show i just set the adapter and try to refresh my listview by calling invalidateViews().
selectedStrings = new ArrayList<String>(typeFilterStrings);
adapter.setArrayResultados(selectedStrings);
listTypeFilter.invalidateViews();
It's not obligatory to set the adapter again in my case worked.
use like this:
Create an instance of your custom adapter, so you can use it anywhere you like...
public class ScoreList extends SherlockFragmentActivity {
private ListView listViewScore;
private ScoreListAdapter adapter;
static List<Score> listScore = new ArrayList<Score>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.score_list);
ctx = this;
listScore = dbh.getAllScores();
listViewScore = (ListView) findViewById(R.id.score_list);
adapter = new ScoreListAdapter(ctx, R.layout.score_row_item, listScore);
listViewScore.setAdapter(adapter);
((BaseAdapter) listViewScore.getAdapter()).notifyDataSetChanged();
}
}
By the way, if your listScore array is already loaded, then you do not need to use
adapter.notifyDatasetChanged();

How to get EditText value into Database in Android?

I want to get edit text value into database in Andorid, right now it is giving blank and in list it is printing my project path and string value #4100dd00.
here is my code.
public class Add_Task_List extends Activity {
EditText edt_addtasklist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_task_list);
SaveTaskList();
}
public void SaveTaskList(){
edt_addtasklist = (EditText)findViewById(R.id.edt_addtasklist);
String taskliststitle = edt_addtasklist.getText().toString();
//how to get edittext value and store in database. right now it is creating field in db but not showing any value when I am checking in data/data/project path/database/.
edt_addtasklist.setText(taskliststitle);
System.out.println(taskliststitle);
TaskManager_Database db = new TaskManager_Database(this);
db.AddTaskLists(taskliststitle); //database method
}
}
List Adapter:
ListView list_tasklistname = (ListView)findViewById(R.id.list_tasklistname);
TaskManager_Database db = new TaskManager_Database(getApplicationContext());
list = db.GetAddTaskLists();
ArrayAdapter<TaskDetailsActivity> adapter = new ArrayAdapter<TaskDetailsActivity>(getApplicationContext(), android.R.layout.simple_list_item_1, list);
list_tasklistname.setAdapter(adapter);
//it is showing list on task added in database but value is like this in one row "com.android.todotask.taskdetailsActivity#4100dee86".
I want when user enter edit text value then it store in sql database table db.AddTaskLists(taskliststitle); and show in a list where I will call db.GetAddTaskLists(); method from database.
Please let me know how to store value in sqlite db, thanks

Categories

Resources