cursor adapter getview problem at position 0 - java

I'm working o a calendar app with events and I save them in MyDatabaseHelpe, the events are shown in a listview by day, my problem is that in onitemclicked, I want the data of the event to be shown in an AlertDialog, I use a CursorAdapter class and when i am trying to show the data, the data that are position 0, arent shown and show the data that are in position 1.
I've tried many approches of the way the position could fit in function, and i search many StackOverFlows(and more sites) subjects to find a solution.
**The delete row function works perfectly without problem.
Any ideas or approches would be helpuful!!
`
Method for listview onitemclicked
`private void DialogClickedItemAndDelete()
{
monthListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
View view1 = getLayoutInflater().inflate(R.layout.show_event_from_listview, null);
Object listItem = monthListView.getItemAtPosition(position).toString();
EventCursorAdapter EC = new EventCursorAdapter(MainActivity.this, myDB.readAllData());
Cursor cursor = EC.getCursor();
cursor.moveToPosition(position);
View view2 = EC.getView(position,view1,parent);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setView(view2).
setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String id_row = hourAdapter.getItem(position).getEvents().get(0).getId();
myDB.deleteOneRow(id_row);
AllEventsList.reloadActivity(MainActivity.this);
}
}).setNegativeButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
AllEventsList.reloadActivity(MainActivity.this);
}
});
builder.show();
}
});
}
`
``
``
#CursorAdapter Class
package com.example.calendarcapital;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
public class EventCursorAdapter extends CursorAdapter {
public EventCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
c.moveToFirst();
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.show_event_from_listview, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView id_lv_tv = (TextView) view.findViewById(R.id.id_lv_tv);
TextView title_lv_tv = (TextView) view.findViewById(R.id.title_lv_tv);
TextView comment_lv_tv = (TextView) view.findViewById(R.id.comment_lv_tv);
TextView date_lv_tv = (TextView) view.findViewById(R.id.date_lv_tv);
TextView time_lv_tv = (TextView) view.findViewById(R.id.time_lv_tv);
String id_row = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
String title = cursor.getString(cursor.getColumnIndexOrThrow("event_title"));
String comment = cursor.getString(cursor.getColumnIndexOrThrow("event_comment"));
String date = cursor.getString(cursor.getColumnIndexOrThrow("event_date"));
String time = cursor.getString(cursor.getColumnIndexOrThrow("event_time"));
id_lv_tv.setText(id_row);
title_lv_tv.setText(title);
comment_lv_tv.setText(comment);
date_lv_tv.setText(date);
time_lv_tv.setText(time);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return super.getView(position, convertView, parent);
}
}
#MyDatabaseHelper Class
public class MyDatabaseHelper extends SQLiteOpenHelper {
private Context context;
private static final String DATABASE_NAME = "CalendarCapital.db";
private static final int DATABASE_VERSION =1;
private static final String TABLE_NAME ="my_events_db";
public static final String COLUMN_ID ="_id";
private static final String COLUMN_TITLE = "event_title";
private static final String COLUMN_COMMENT = "event_comment";
private static final String COLUMN_DATE = "event_date";
private static final String COLUMN_TIME = "event_time";
MyDatabaseHelper(#Nullable Context context)
{
super(context,DATABASE_NAME,null,DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db)
{
String query = "CREATE TABLE " + TABLE_NAME +
" (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_TITLE + " TEXT, " +
COLUMN_COMMENT + " TEXT, " +
COLUMN_DATE + " TEXT, " +
COLUMN_TIME + " TEXT);";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
void addEvent(String title, String comment, LocalDate date, LocalTime time)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_TITLE, title);
cv.put(COLUMN_COMMENT, comment);
cv.put(COLUMN_DATE, String.valueOf(date));
cv.put(COLUMN_TIME, String.valueOf(time));
long result = db.insert(TABLE_NAME, null, cv);
if (result== -1)
{
Toast.makeText(context, "Data Failed", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(context, "Data Added Successfully", Toast.LENGTH_SHORT).show();
}
}
Cursor readAllData(){
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if (db != null)
{
cursor = db.rawQuery(query, null);
}
return cursor;
}
void updateData(String row_id, String title, String comments, String date, String time)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_TITLE,title);
cv.put(COLUMN_COMMENT,comments);
cv.put(COLUMN_DATE, String.valueOf(date));
cv.put(COLUMN_TIME, String.valueOf(time));
long result = db.update(TABLE_NAME,cv,"_id=?",new String[]{row_id});
if (result == -1)
{
Toast.makeText(context, "Failed to Update", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(context, "Successfully Update", Toast.LENGTH_SHORT).show();
}
}
void deleteOneRow(String row_id)
{
SQLiteDatabase db = this.getWritableDatabase();
long result = db.delete(TABLE_NAME, "_id=?", new String[]{row_id});
if (result == -1)
{
Toast.makeText(context, "Failed to Delete.", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(context, "Deleted Successfully.", Toast.LENGTH_SHORT).show();
}
}
void deleteAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME);
}
}
Another approch I tried is this
View view2 = EC.getView(position,view1,parent);
View view3 = monthListView.getChildAt(position - monthListView.getFirstVisiblePosition());
View view4 = EC.newView(EC.mContext,EC.mCursor,parent);
View view5=hourAdapter.getView(position,view1,parent);
UPDATE: 27/12/2022
I noticed that my problem is maybe because i sort my list.
private void setMonthAdapter() {
hourAdapter = new HourAdapter(getApplicationContext(), AllEventsList.hourEventListFromDatabase(getApplicationContext(), myDB));
hourAdapter.sort((o1, o2) -> o1.events.get(0).getDate().compareTo(o2.events.get(0).getDate()));
hourAdapter.sort((o1, o2) -> o1.events.get(0).getTime().compareTo(o2.events.get(0).getTime()));
monthListView.setAdapter(hourAdapter);
}
I can retrieve the values but with the wrong order, in my listview my events are sorted by time and date, when i click item in position 0 it show me the item in position 1 and versa.
**SOLUTION: **
The problem was that after sorting list i didn't called notifyDataChanged();
Furthermore I made in my CursorAdapter Class a method to retrieve fields via cursor.
So in cursor adapter i made this:
public View setAllFields(View view,String id, String title, String comment, String date, String time)
{
TextView id_lv_tv = (TextView) view.findViewById(R.id.id_lv_tv);
TextView title_lv_tv = (TextView) view.findViewById(R.id.title_lv_tv);
TextView comment_lv_tv = (TextView) view.findViewById(R.id.comment_lv_tv);
TextView date_lv_tv = (TextView) view.findViewById(R.id.date_lv_tv);
TextView time_lv_tv = (TextView) view.findViewById(R.id.time_lv_tv);
id_lv_tv.setText(id);
title_lv_tv.setText(title);
comment_lv_tv.setText(comment);
date_lv_tv.setText(date);
time_lv_tv.setText(time);
return view;
}
And my main onitemclick now is like this:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
View view1 = getLayoutInflater().inflate(R.layout.show_event_from_listview, null);
// private ArrayList MlaDats = new ArrayList();
HourEvent myEvent = (HourEvent) monthListView.getAdapter().getItem(position);
String myEventId= myEvent.getEvents().get(0).getId();
String myTitle = myEvent.getEvents().get(0).getName();
String myComment = myEvent.getEvents().get(0).getComment();
String myDate = String.valueOf(myEvent.getEvents().get(0).getDate());
String myTime = String.valueOf(myEvent.getEvents().get(0).getTime());
View viewFinal;
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
viewFinal = CA.setAllFields(view1,myEventId,myTitle,myComment,myDate,myTime);
// viewFinal = SD.getView(position, view1, parent);
builder.setView(viewFinal).
CLOSED

I'm working o a calendar app with events and I save them in MyDatabaseHelpe, the events are shown in a listview by day, my problem is that in onitemclicked, I want the data of the event to be shown in an AlertDialog, I use a CursorAdapter class and when i am trying to show the data, the data that are in position 0, arent shown and show the data that are in position 1.
cursor adapter getview problem at position 0
I've tried many approches of the way the position could fit in function, and i search many StackOverFlows(and more sites) subjects to find a solution.
**The delete row function works perfectly without problem.
Any ideas or approches would be helpuful!!
**SOLUTION: **
The problem was that after sorting list i didn't called notifyDataChanged();
Furthermore I made in my CursorAdapter Class a method to retrieve fields via cursor.
So in cursor adapter i made this:
public View setAllFields(View view,String id, String title, String comment, String date, String time)
{
TextView id_lv_tv = (TextView) view.findViewById(R.id.id_lv_tv);
TextView title_lv_tv = (TextView) view.findViewById(R.id.title_lv_tv);
TextView comment_lv_tv = (TextView) view.findViewById(R.id.comment_lv_tv);
TextView date_lv_tv = (TextView) view.findViewById(R.id.date_lv_tv);
TextView time_lv_tv = (TextView) view.findViewById(R.id.time_lv_tv);
id_lv_tv.setText(id);
title_lv_tv.setText(title);
comment_lv_tv.setText(comment);
date_lv_tv.setText(date);
time_lv_tv.setText(time);
return view;
}
And my main onitemclick now is like this:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { View view1 = getLayoutInflater().inflate(R.layout.show_event_from_listview, null); // private ArrayList MlaDats = new ArrayList(); HourEvent myEvent = (HourEvent) monthListView.getAdapter().getItem(position);
String myEventId= myEvent.getEvents().get(0).getId();
String myTitle = myEvent.getEvents().get(0).getName();
String myComment = myEvent.getEvents().get(0).getComment();
String myDate = String.valueOf(myEvent.getEvents().get(0).getDate());
String myTime = String.valueOf(myEvent.getEvents().get(0).getTime());
View viewFinal;
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
viewFinal = CA.setAllFields(view1,myEventId,myTitle,myComment,myDate,myTime);
// viewFinal = SD.getView(position, view1, parent);
builder.setView(viewFinal).

Related

Delete Both row of list items on recyclerView and SQLite database

I am a beginner at programming, I want to make a delete button on every items list on recyclerView. I got some references from stack overflow, and its work for the deleted item only at the activity (layout), but when i run the activity again the The selected item showed again.
I found some related articles on stackoverflow and make the method to delete from the SQLite. But my app crushed "unfortunetly app has stopped" every time I call the delete function.
I hope someone can help me to figure it out.
here is my databasehelper class
public class DatabaseHelperClass extends SQLiteOpenHelper {
Log cat Database
public static String log = "DatabaseHelper";
//Databse version
public static final int DATABASE_VERSION = 1;
//Database name
public static final String DATABSE_NAME = "dbPig";
//Tables Name
public static final String TABLE_PIGINFO = "tb_pigInfo";
//Common and PigInfo Column Names
public static final String KEY_ID = "id";
public static final String KEY_NAMA = "nama";
public static final String KEY_TANGGAL_PENDAFTARAN = "tanggal_pendaftaran";
//table create statement
//table pig Info
public static final String CREATE_TABLE_PIGINFO = "CREATE TABLE "
+ TABLE_PIGINFO + "(" + KEY_ID + " INTEGER," + KEY_NAMA
+ " TEXT," + KEY_TANGGAL_PENDAFTARAN
+ " TEXT" + ")";
public DatabaseHelperClass(Context context) {
super(context, DATABSE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//creating requaired table
db.execSQL(CREATE_TABLE_PIGINFO);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PIGINFO);
// create new tables
onCreate(db);
}
public void insertdata(String nama, String tanggal_pendaftaran) {
System.out.print("Tersimpan" + TABLE_PIGINFO);
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_NAMA, nama);
contentValues.put(KEY_TANGGAL_PENDAFTARAN, tanggal_pendaftaran);
db.insert(TABLE_PIGINFO, null, contentValues);
}
public List<PigInfoTable> getdata() {
List<PigInfoTable> data = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from " + TABLE_PIGINFO + " ;", null);
StringBuffer stringBuffer = new StringBuffer();
PigInfoTable pigInfoTable = null;
while (cursor.moveToNext()) {
pigInfoTable = new PigInfoTable();
String nama = cursor.getString(cursor.getColumnIndexOrThrow("nama"));
String tanggal_pendaftaran = cursor.getString(cursor.getColumnIndexOrThrow("tanggal_pendaftaran"));
pigInfoTable.setNama(nama);
pigInfoTable.setTanggal_pendaftaran(tanggal_pendaftaran);
stringBuffer.append(pigInfoTable);
data.add(0, pigInfoTable);
}
for (PigInfoTable mo : data) {
Log.i("Hellomo", "" + mo.getNama());
}
return data;
}
public void delete(int position) {
SQLiteDatabase db = this.getWritableDatabase();
String table = TABLE_PIGINFO;
String whereClause = KEY_ID;
String [] whereArgs = new String[] {String.valueOf(position)};
db.delete (table, whereClause, whereArgs);
}
and here my adapter
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.Myholder> {
DatabaseHelperClass databaseHelper;
List <PigInfoTable> pigInfoTablesArrayList;
public RecycleAdapter(List <PigInfoTable> pigInfoTablesArrayList) {
this.pigInfoTablesArrayList = pigInfoTablesArrayList;
}
class Myholder extends RecyclerView.ViewHolder{
private TextView nama, tanggal_pendaftaran;
private Button delete;
public Myholder(View itemView) {
super(itemView);
nama = (TextView) itemView.findViewById(R.id.nama1);
tanggal_pendaftaran = (TextView) itemView.findViewById(R.id.tanggal1);
delete = (Button) itemView.findViewById(R.id.delete);
}
}
#Override
public Myholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_itempigview,null);
return new Myholder(view);
}
#Override
public void onBindViewHolder(Myholder holder, final int position) {
PigInfoTable pigInfoTable= pigInfoTablesArrayList.get(position);
holder.nama.setText(pigInfoTable.getNama());
holder.tanggal_pendaftaran.setText(pigInfoTable.getTanggal_pendaftaran());
holder.itemView.setClickable(true);
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseHelper.delete(position);
pigInfoTablesArrayList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, pigInfoTablesArrayList.size());
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return pigInfoTablesArrayList.size();
}
I am trying some other solution but the same error occurred which's
null object references on
Position
error
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.newbreedy.DatabaseHelperClass.delete(int)' on a null object reference
at com.example.newbreedy.RecycleAdapter$1.onClick(RecycleAdapter.java:66)
thank you
com.example.newbreedy.DatabaseHelperClass.delete(int)' on a null object reference
because you have not initialized the reference of
DatabaseHelperClass databaseHelper;
So Add.
databaseHelper =new DatabaseHelperClass (context);
in your recycler adapter
In your code you are sending adapter position so in place of position send KEY_ID.
databaseHelper.delete(position);
pigInfoTablesArrayList.remove(position);
notifyDataSetChanged();
First you have to initialize your DatabaseHelperClass in your adapter like this,
databaseHelper =new DatabaseHelperClass (context);
Than you need to call the delete function and inform the adapter about the removed item like this,
databaseHelper.delete(position);
pigInfoTablesArrayList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, pigInfoTablesArrayList.size());

Delete A Row In customAdapter extends BaseAdapter using SQLite - Android

I am trying to get a row in my SQLite database to delete on button click. I was successful in getting a row to delete in the ListView, but every time when I try delete from sqlite app crashes.
dba.removeData(position);
mModel.remove(position);
notifyDataSetChanged();
That just delete the item in ListView and not the row in the database.
public class CustomAdapter extends BaseAdapter {
private int custom_adapter;
private Context context;
private ArrayList<Model> mModel;
DatabaseHelper dba = new DatabaseHelper(this.context);
public CustomAdapter(Context context, int custom_adapter, ArrayList<Model> mModel) {
this.context = context;
this.mModel = mModel;
this.custom_adapter = custom_adapter;
}
#Override
public int getCount() {
return mModel.size();
}
#Override
public Object getItem(int position) {
return mModel.get(position);
}
#Override
public long getItemId(int position) {
return mModel.get(position).getId();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = View.inflate(context, R.layout.custom_adapter, null);
final TextView ID = (TextView) v.findViewById(R.id.textViewID);
TextView przejechane = (TextView) v.findViewById(R.id.textViewPrzejechane);
TextView spalone = (TextView) v.findViewById(R.id.textViewSpalanie);
TextView zuzytePaliwo = (TextView) v.findViewById(R.id.textViewUzytepaliwo);
final TextView dataView = (TextView) v.findViewById(R.id.textViewData);
final Button btnDelete = (Button) v.findViewById(R.id.btnDelete);
final ListView listView = (ListView) v.findViewById(R.id.listview);
ID.setText(String.valueOf( mModel.get(position).getId()));
przejechane.setText(String.valueOf( mModel.get(position).getAmount_km()));
spalone.setText(String.valueOf( mModel.get(position).getAvg()));
zuzytePaliwo.setText(String.valueOf( mModel.get(position).getAmount_fuel()));
dataView.setText(String.valueOf( mModel.get(position).getData()));
btnDelete.setTag(position);
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dba.removeData(position);
mModel.remove(position);
notifyDataSetChanged();
}
});
return v;
}
here is my DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper {
private SQLiteDatabase mDatabase;
public static final String DATABASE_NAME = "AvgFuel.db";
public static final String TABLE_NAME = "avgFuel_table";
public static final String ID = "ID";
public static final String AMOUNT_FUEL = "AMOUNT_FUEL";
public static final String AMOUNT_KM = "AMOUNT_KM";
public static final String AVG = "AVG";
public static final String DATA = "DATA";
private static final String SELECT_PEOPLE = "SELECT * FROM " + TABLE_NAME;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + "(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
AMOUNT_FUEL + " REAL, " + AMOUNT_KM + " REAL, " + AVG + " REAL, " + DATA + " TEXT" + ");");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String amount_fuel, String amount_km, double avg){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(AMOUNT_FUEL,amount_fuel);
contentValues.put(AMOUNT_KM,amount_km);
contentValues.put(AVG,avg);
contentValues.put(DATA,getNow());
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public void removeData(int id){
SQLiteDatabase db = this.getReadableDatabase();
db.delete(TABLE_NAME, ID + "=" + id , null);
db.close();
}
public ArrayList<Model> getModels() {
ArrayList<Model> model = new ArrayList<Model>();
mDatabase = this.getReadableDatabase();
Cursor cursor = mDatabase.rawQuery(SELECT_PEOPLE, null);
cursor.moveToNext();
for (int i = 0; i <cursor.getCount() ; i++) {
model.add(new Model(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4)));
cursor.moveToNext();
}
cursor.close();
mDatabase.close();
return model;
}
public Model getModel(int id){
mDatabase = this.getReadableDatabase();
String s = "SELECT * FROM" + TABLE_NAME + "WHERE " + ID + "=" + id;
Cursor cursor = mDatabase.rawQuery(s,null);
cursor.moveToFirst();
Model model = new Model(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4));
cursor.close () ;
mDatabase.close () ;
return model ;
}
private String getNow(){
// set the format to sql date time
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
I think the problem is dba creation. Here you just use this adapter context. This should be the context what you get from Activity.
DatabaseHelper dba = new DatabaseHelper(this.context);
Try to use this
public CustomAdapter(Context context, int custom_adapter, ArrayList<Model> mModel) {
this.context = context;
this.mModel = mModel;
this.custom_adapter = custom_adapter;
dba = new DatabaseHelper(context);
}
To get the actual position of recyclerView you can use getAdapterPosition(). Like this
dba.removeData(mModel.get(getAdapterPosition()).getId());
Hope this will help.
Try to change this ..mModel.get(position).getId()
dba.removeData(mModel.get(position).getId());

Why my custom cursor adapter is not working? Same code was working fine when used with ArrayAdapter

Aim of my program is to store data in SQLite database and then use that database in list view.
I have provided the codes ( deleted some unnecessary codes) below.
I have inserted successfully some dummy data in database.
Layout for custom adapter is also working properly.
My app is crashing when creating the object of Timetable adapted.
I have tried all the way which I can do, but not working.
If need some more information please let me know.
In MainActivity.java
TimeTableDBHelper timeTableDbHelper = new TimeTableDBHelper(this);
SQLiteDatabase db = timeTableDbHelper.getWritableDatabase();
db = timeTableDbHelper.getReadableDatabase();
String[] columns = {TimeTableContract.COLUMN_NAME_START_TIME,TimeTableContract.COLUMN_NAME_END_TIME,
TimeTableContract.COLUMN_NAME_DATE,
TimeTableContract.COLUMN_NAME_MONTH
};
Cursor cursor = db.query(TimeTableContract.TABLE_NAME, columns, null, null, null, null, null);
//My app is crashing after this line only
TimeTableAdapter adapter = new TimeTableAdapter(this, cursor);
ListView listView = (ListView) findViewById(R.id.mainListView1);
listView.setAdapter(adapter);
cursor.close();
TimetableAdapter.java
public class TimeTableAdapter extends CursorAdapter
{
public TimeTableAdapter(Context context, Cursor cursor)
{
super(context,cursor,0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
return LayoutInflater.from(context).inflate(R.layout.table_list_view, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor)
{
int startColumnIndex = cursor.getColumnIndex(TimeTableContract.COLUMN_NAME_START_TIME);
String time1 = cursor.getString(startColumnIndex);
int endColumnIndex = cursor.getColumnIndex(TimeTableContract.COLUMN_NAME_END_TIME);
String time2 = cursor.getString(endColumnIndex);
int dateColumnIndex = cursor.getColumnIndex(TimeTableContract.COLUMN_NAME_DATE);
String date = cursor.getString(dateColumnIndex);
int monthColumnIndex = cursor.getColumnIndex(TimeTableContract.COLUMN_NAME_MONTH);
String month = cursor.getString(monthColumnIndex);
TextView startTime = (TextView) view.findViewById(R.id.start_time);
TextView endTime = (TextView) view.findViewById(R.id.end_time);
TextView tuitorName = (TextView) view.findViewById(R.id.tuitor_name);
TextView subject = (TextView) view.findViewById(R.id.subject);
TextView remarks = (TextView) view.findViewById(R.id.remarks);
TextView dateMonth = (TextView) view.findViewById(R.id.date);
startTime.setText(time1);
endTime.setText(time2);
tuitorName.setText("Tutor");
subject.setText("subject");
remarks.setText("remarks...");
dateMonth.setText(date+", " + month);
}
Contract class
public class TimeTableContract
{
// Make constructor private do that it does not initiatted accidently
private TimeTableContract()
{};
public static final String TABLE_NAME = "time_table";
public static final String COLUMN_NAME_START_TIME = "start_time";
public static final String COLUMN_NAME_END_TIME = "end_time";
public static final String COLUMN_NAME_DATE = "date";
public static final String COLUMN_NAME_MONTH = "month";
public static final String COLUMN_NAME_ID = "_id";
}
Creating table in database by following code ( by the way there is no problem with my database helper class)
"CREATE TABLE " + TimeTableContract.TABLE_NAME + " ( " +
TimeTableContract.COLUMN_NAME_ID + " INTEGER PRIMARY KEY," +
TimeTableContract.COLUMN_NAME_START_TIME + " TEXT," +
TimeTableContract.COLUMN_NAME_END_TIME + " TEXT,"+
TimeTableContract.COLUMN_NAME_DATE + " TEXT,"+
TimeTableContract.COLUMN_NAME_MONTH + " TEXT)";
You are missing the "_id" column in your cursor here:
String[] columns = {TimeTableContract.COLUMN_NAME_START_TIME,
TimeTableContract.COLUMN_NAME_END_TIME,
TimeTableContract.COLUMN_NAME_DATE,
TimeTableContract.COLUMN_NAME_MONTH
};
It's an android convention that you must include "_id" column in your cursor if you are working with CursorAdapters and ListViews or else they won't work.
When you implement onItemClick() method for your listview, you will get that same _id as an argument named long id
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, **long id**)

can't get to show data from a database sqlite with a requirement JAVA ANDROID STUDIO

i can't get my data to show on my ListView. i created database handler with a query that says: "SELECT * FROM TABLE_NAME WHERE COLUMN_USERNAME = '"+Username+"'". i want to show Data that have the username i want only. But i cant seem to get it work. here is the code.
ViewEvent class with the List View
public class ViewEvent extends Activity {
private static String z = "";
private static final int _EDIT = 0, _DELETE = 1; // constants to be used later
static int longClickedItemIndex;
static List<Event> events = new ArrayList<Event>();
ArrayAdapter<Event> eventsAdapter;
ListView listViewEvents;
static DatabaseHandlerEvent helper;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_event);
Typeface myTypeFace = Typeface.createFromAsset(getAssets(), "Type Keys Filled.ttf");
TextView myTextview = (TextView) findViewById(R.id.textViewHead4);
myTextview.setTypeface(myTypeFace);
helper = new DatabaseHandlerEvent(getApplicationContext());
listViewEvents = (ListView) findViewById(R.id.listView);
registerForContextMenu(listViewEvents);
listViewEvents.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemIndex = position;
return false;
}
}
);
populateList();
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Username = prfs.getString("Username", "");
if (helper.getEventCount() != 0 && events.size() == 0) {
events.addAll(helper.getAllEvent(Username));
}
}
public void registerForContextMenu(View view) {
view.setOnCreateContextMenuListener(this);
}
public void onButtonClick(View v){
if(v.getId() == R.id.bSignoutb){
Toast so = Toast.makeText(ViewEvent.this, "Signing out.. Redirecting to Login Page..." , Toast.LENGTH_SHORT);
so.show();
Intent i = new Intent(ViewEvent.this, MainActivity.class);
startActivity(i);
}
if(v.getId() == R.id.Bback){
Intent i = new Intent(ViewEvent.this, CreateEvent.class);
startActivity(i);
}
}
private void populateList() {
eventsAdapter = new eventListAdapter();
listViewEvents.setAdapter(eventsAdapter);
}
public class eventListAdapter extends ArrayAdapter<Event> {
public eventListAdapter() {
super(ViewEvent.this, R.layout.listview_event, events);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = getLayoutInflater().inflate(R.layout.listview_event, parent, false);
}
Event currentEvent = events.get(position);
TextView name = (TextView) view.findViewById(R.id.textViewEventName);
name.setText(currentEvent.getName());
TextView location = (TextView) view.findViewById(R.id.textViewLocation);
location.setText(currentEvent.getLocation());
TextView date = (TextView) view.findViewById(R.id.textViewDate);
date.setText(currentEvent.getDate());
TextView description = (TextView) view.findViewById(R.id.textViewDescription);
description.setText(currentEvent.getDescription());
TextView time = (TextView) view.findViewById(R.id.textViewTime);
time.setText(currentEvent.getTime());
TextView testnia = (TextView) view.findViewById(R.id.testnia);
testnia.setText(currentEvent.getUsername());
return view;
}
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderIcon(R.drawable.huhu);// find a suitable icon
menu.setHeaderTitle("Event options:");
menu.add(Menu.NONE, _EDIT, Menu.NONE, "Edit Event");
menu.add(Menu.NONE, _DELETE, Menu.NONE, "Delete Event");
}
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case _EDIT:
// editing a contact
Intent editContactIntent = new Intent(getApplicationContext(), EditEvent.class);
startActivityForResult(editContactIntent, 2); // reqcode=2
break;
case _DELETE:
helper.deleteEvent(events.get(longClickedItemIndex));
events.remove(longClickedItemIndex);
eventsAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
}
And this is my DataBaseHelperEvent class
public class DatabaseHandlerEvent extends SQLiteOpenHelper {
static DatabaseHelperUser helper;
Event event;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Events";
private static final String TABLE_NAME = "Events";
private static final String COLUMN_ID = "id",
COLUMN_NAME = "name", COLUMN_LOCATION = "location", COLUMN_DATE = "date",
COLUMN_TIME ="time", COLUMN_DESCRIPTION = "description", COLUMN_USERNAME = "username";
SQLiteDatabase db;
public DatabaseHandlerEvent(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " + COLUMN_LOCATION + " TEXT, " +
COLUMN_DATE + " TEXT, " + COLUMN_TIME + " TEXT, " +
COLUMN_DESCRIPTION + " TEXT, " + COLUMN_USERNAME + " TEXT)"
);
}
public long createEvent (Event event) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, event.getName());
values.put(COLUMN_LOCATION, event.getLocation());
values.put(COLUMN_DATE, event.getDate());
values.put(COLUMN_TIME, event.getTime());
values.put(COLUMN_DESCRIPTION, event.getDescription());
values.put(COLUMN_USERNAME, event.getUsername());
long result = db.insert(TABLE_NAME, null, values);
db.close();
return result;
}
public int updateEvent(Event event) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, event.getName());
values.put(COLUMN_LOCATION, event.getLocation());
values.put(COLUMN_DATE, event.getDate());
values.put(COLUMN_TIME, event.getTime());
values.put(COLUMN_DESCRIPTION, event.getDescription());
int rowsAffected = db.update(TABLE_NAME, values, COLUMN_ID + "=?",
new String[]{String.valueOf(event.getId())});
db.close();
return rowsAffected;
}
public List<Event> getAllEvent(String Username) {
List<Event> events = new ArrayList<Event>();
db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME +" WHERE "+COLUMN_USERNAME+" = "+ "'"+Username+"'", null);
if (cursor.moveToFirst()) {
do {
events.add(new Event(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4),
cursor.getString(5), cursor.getString(6)));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return events;
}
public int getEventCount() {
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
}
public int deleteEvent(Event event) {
db = this.getWritableDatabase();
int rowsAffected = db.delete(TABLE_NAME, COLUMN_ID + "=?",
new String[]{String.valueOf(event.getId())});
db.close();
return rowsAffected;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS "+TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
}
So whenever i show my ListView, it will show nothing. How can i show the data that only have a specific username i want? thanks! Sorry for my bad english

Android Listview not updating after delete item

I am working with sqllite. I have successfully create a database and I can input some values in my database. I can also show all values in listview and also i can remove item by listview's onitemclicklistener.i have one problem. when i delete item listview not updated,but this item is deleted in database.how i can solve this problem ?
DatabaseHandler .java code
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "lvstone_2";
private static final String TABLE_CONTACTS = "CardTable1";
private static final String KEY_ID = "id";
private static final String KEY_Tittle = "name";
private static final String KEY_Description = "description";
private static final String KEY_Price = "price";
private static final String KEY_Counter = "counter";
private static final String KEY_Image = "image";
private final ArrayList<Contact> contact_list = new ArrayList<Contact>();
public static SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_Tittle + " TEXT,"
+ KEY_Description + " TEXT,"
+ KEY_Price + " TEXT,"
+ KEY_Counter + " TEXT,"
+ KEY_Image + " TEXT"
+ ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void Add_Contact(Contact contact) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
if (!somethingExists(contact.getTitle())) {
values.put(KEY_Tittle, contact.getTitle()); // Contact title
values.put(KEY_Description, contact.getDescription()); // Contact//
// description
values.put(KEY_Price, contact.getPrice()); // Contact price
values.put(KEY_Counter, contact.getCounter()); // Contact image
values.put(KEY_Image, contact.getImage()); // Contact image
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
Log.e("Table Result isss", String.valueOf(values));
db.close(); // Closing database connection
}
}
public void deleteUser(String userName)
{
db = this.getWritableDatabase();
try
{
db.delete(TABLE_CONTACTS, "name = ?", new String[] { userName });
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
// Getting single contact
Contact Get_Contact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS,
new String[] { KEY_ID, KEY_Tittle, KEY_Description, KEY_Price,
KEY_Counter, KEY_Image }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(cursor.getString(0), cursor.getString(1),
cursor.getString(2), cursor.getString(4), cursor.getString(5));
// return contact
cursor.close();
db.close();
return contact;
}
public boolean somethingExists(String x) {
Cursor cursor = db.rawQuery("select * from " + TABLE_CONTACTS
+ " where name like '%" + x + "%'", null);
boolean exists = (cursor.getCount() > 0);
Log.e("Databaseeeeeeeee", String.valueOf(cursor));
cursor.close();
return exists;
}
public ArrayList<Contact> Get_Contacts() {
try {
contact_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setTitle(cursor.getString(1));
contact.setDescription(cursor.getString(2));
contact.setPrice(cursor.getString(3));
contact.setCounter(cursor.getString(4));
contact.setImage(cursor.getString(5));
contact_list.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return contact_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return contact_list;
}
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
}
SQLAdapter.java code
public class StradaSQLAdapter extends BaseAdapter {
Activity activity;
int layoutResourceId;
Contact user;
ArrayList<Contact> data = new ArrayList<Contact>();
public ImageLoader imageLoader;
UserHolder holder = null;
public int itemSelected = 0;
public StradaSQLAdapter(Activity act, int layoutResourceId,
ArrayList<Contact> data) {
this.layoutResourceId = layoutResourceId;
this.activity = act;
this.data = data;
imageLoader = new ImageLoader(act.getApplicationContext());
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(activity);
holder = new UserHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.Title = (TextView) row.findViewById(R.id.smalltitle1);
holder.counter = (TextView) row.findViewById(R.id.smallCounter1);
holder.dbcounter = (TextView) row
.findViewById(R.id.DBSliderCounter);
holder.Description = (TextView) row.findViewById(R.id.smallDesc1);
holder.layout = (RelativeLayout) row
.findViewById(R.id.DBSlideLayout);
holder.layoutmain = (RelativeLayout) row
.findViewById(R.id.DBSlideLayoutMain);
holder.Price = (TextView) row.findViewById(R.id.smallPrice1);
holder.pt = (ImageView) row.findViewById(R.id.smallthumb1);
holder.close = (ImageView) row.findViewById(R.id.DBSliderClose);
holder.c_minus = (ImageView) row.findViewById(R.id.counter_minus);
holder.c_plus = (ImageView) row.findViewById(R.id.counter_plus);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
user = data.get(position);
holder.Title.setText(user.getTitle());
holder.Description.setText(user.getDescription());
holder.Price.setText(user.getPrice() + " GEL");
holder.counter.setText(user.getCounter());
holder.dbcounter.setText(user.getCounter());
Log.e("image Url is........", data.get(position).toString());
imageLoader.DisplayImage(user.getImage(), holder.pt);
return row;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public class UserHolder {
public TextView Price, counter, Description, Title, dbcounter;
public ImageView pt,close,c_plus,c_minus;
public RelativeLayout layout, layoutmain;
}
}
and Main java code
public class StradaChartFragments extends Fragment {
public static ListView list;
ArrayList<Contact> contact_data = new ArrayList<Contact>();
StradaSQLAdapter cAdapter;
private DatabaseHandler dbHelper;
UserHolder holder;
private RelativeLayout.LayoutParams layoutParams;
private ArrayList<Contact> contact_array_from_db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_chart_fragment,
container, false);
dbHelper = new DatabaseHandler(getActivity());
list = (ListView) rootView.findViewById(R.id.chart_listview);
cAdapter = new StradaSQLAdapter(getActivity(),
R.layout.listview_row_db, contact_data);
contact_array_from_db = dbHelper.Get_Contacts();
Set_Referash_Data();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
holder = (UserHolder) view.getTag();
layoutParams = (RelativeLayout.LayoutParams) holder.layoutmain
.getLayoutParams();
if (holder.layout.getVisibility() != View.VISIBLE) {
ValueAnimator varl = ValueAnimator.ofInt(0, -170);
varl.setDuration(1000);
varl.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
layoutParams.setMargins(
(Integer) animation.getAnimatedValue(), 0,
0, 0);
holder.layoutmain.setLayoutParams(layoutParams);
}
});
varl.start();
holder.layout.setVisibility(View.VISIBLE);
}
holder.close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ValueAnimator var2 = ValueAnimator.ofInt(-170, 0);
var2.setDuration(1000);
var2.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(
ValueAnimator animation) {
dbHelper.deleteUser(contact_array_from_db.get(position).getTitle());
if (contact_data.size() > 0)
contact_data.remove(position);
layoutParams.setMargins(0, 0,
(Integer) animation.getAnimatedValue(),
0);
holder.layoutmain.setLayoutParams(layoutParams);
holder.layout.setVisibility(View.INVISIBLE);
}
});
var2.start();
}
});
}
});
return rootView;
}
public void Set_Referash_Data() {
contact_data.clear();
for (int i = 0; i < contact_array_from_db.size(); i++) {
String title = contact_array_from_db.get(i).getTitle();
String Description = contact_array_from_db.get(i).getDescription();
String Price = contact_array_from_db.get(i).getPrice();
String Counter = contact_array_from_db.get(i).getCounter();
String image = contact_array_from_db.get(i).getImage();
Contact cnt = new Contact();
cnt.setTitle(title);
cnt.setDescription(Description);
cnt.setPrice(Price);
cnt.setCounter(Counter);
cnt.setImage(image);
contact_data.add(cnt);
}
dbHelper.close();
list.setAdapter(cAdapter);
Log.e("Adapter issss ...", String.valueOf(cAdapter));
}
}
i can remove item in database ,but listview not updated . what am i doing wrong ? if anyone knows solution help me
thanks
Under your method dbHelper.deleteUser add this code:
contact_data.remove(position);
To function in addition to deleting it from the database also have to delete the array of objects that you sent to adapter.
EDIT:
Add one remove method in your adapter for you can remove object. Code:
Adapter:
public void removeObject (int position) {
this.data.remove(position);
}
Activity:
Change:
contact_data.remove(position);
to:
cAdapter.removeObject(position);
cAdapter.notifyDataSetChanged();
EDIT 2:
Just delete all the objects from ArrayList.
contact_data.clear();
or in your adapter
data.clear();

Categories

Resources