**Good day everyone ...
I badly need your help.
Can I ask on why my listview doesnt display and also my alert dialog?
here is my code
I've already inserted table values in the sqlite database and Im confused on why nothing displays on my listview and dialog.
the listview uses an adapter that i queried in the DBHelper
MainActivity
public class MainActivity extends AppCompatActivity {
private QuestionaireDB commandQuery;
private ListView showQuestion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
commandQuery = new QuestionaireDB(this);
ShowTables();
ArrayList getQuestion = commandQuery.getAllQuestions();
ArrayAdapter arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,getQuestion);
showQuestion = (ListView)findViewById(R.id.viewAll);
showQuestion.setAdapter(arrayAdapter);
}
private void ShowTables(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("You have "+commandQuery.numberOfRows()+"");
alertDialogBuilder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
}
}
QuestionaireDB
public class QuestionaireDB extends SQLiteOpenHelper{
//tblQuestion
public static final String DATABASE_NAME = "QuestionaireDB.db";
public static final String DATABASE_TABLE_tblQuestion = "tblQuestion";
public static final String DATABASE_TABLE_tblChoices = "tblChoices";
public static final String DATABASE_TABLE_tblAnswers = "tblAnswers";
public static final String DATABASE_TABLE_tblCategory = "tblCategory";
public QuestionaireDB(Context context) {
super(context, DATABASE_NAME , null, 3);
}
#Override
public void onCreate(SQLiteDatabase db) {
//tblQuestion
String CreatetblQueston="CREATE TABLE "+DATABASE_TABLE_tblQuestion +
"(questionID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,categoryID INTEGER,
questionName TEXT)";
//tblChoices
String CreatetblChoices="CREATE TABLE "+DATABASE_TABLE_tblChoices +
"(questionID INTEGER NOT NULL, ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
questionChoices TEXT)";
//tblAnswers
String CreatetblAnswers="CREATE TABLE "+DATABASE_TABLE_tblAnswers+
"(questionID INTEGER NOT NULL, questionCorrectAnswer TEXT, ID INTEGER PRIMARY KEY
AUTOINCREMENT NOT NULL)";
//tblCategory
String CreateCategory="CREATE TABLE "+DATABASE_TABLE_tblCategory+
" (categoryID INTEGER NOT NULL,categoryName TEXT, PRIMARY KEY (categoryID ASC))";
db.execSQL(CreatetblQueston);
db.execSQL(CreatetblChoices);
db.execSQL(CreatetblAnswers);
db.execSQL(CreateCategory);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String confirmationQuestion="DROP TABLE IF EXISTS "+DATABASE_TABLE_tblQuestion ;
String confirmationChoices="DROP TABLE IF EXISTS "+DATABASE_TABLE_tblChoices ;
String confirmationAnswers="DROP TABLE IF EXISTS "+DATABASE_TABLE_tblAnswers ;
String confirmationCategory="DROP TABLE IF EXISTS "+DATABASE_TABLE_tblCategory ;
db.execSQL(confirmationQuestion);
db.execSQL(confirmationChoices);
db.execSQL(confirmationAnswers);
db.execSQL(confirmationCategory);
}
public ArrayList<String> getAllQuestions() {
ArrayList<String> array_list = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from tblQuestion", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex("questionName")));
res.moveToNext();
}
return array_list;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, DATABASE_TABLE_tblQuestion);
return numRows;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="#+id/viewAll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
`
First of all you need to call show() method of dialog like written below,
alertDialogBuilder.show(); //add this line in your ShowTables()
Replace line
ArrayList getQuestion=commandQuery.getAllQuestions();
with
ArrayList<String> getQuestion=commandQuery.getAllQuestions();
And check whether you are getting atleast one data from your database(check list size)
Related
I want to delete a row in my Database via a ListView. I already managed to display the data in a listview. I am working with a OnItemLongClickListener which then opens up a Dialog to delete the clicked item. I can't get the actual delete method to work.
The OnCLickListener method:
public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int position, long id) {
build = new AlertDialog.Builder(ZeigeFaecherListe.this);
build.setTitle("Fach löschen?" + faecherListe.get(position));
build.setMessage("Willst du das Fach wirklich löschen?");
build.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
build.setPositiveButton("Löschen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
myDb.loescheFach(position);
Toast.makeText(getApplicationContext(), faecherListe.get(position) + " gelöscht.", Toast.LENGTH_LONG).show();
myDb.zeigeFaecher();
dialogInterface.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
return true;
}
});
The actual delete method:
public int loescheFach(int position){
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("Fach_table","FACHID=?", new String[]{String.valueOf(position)});
}
You are confusing your list position with id, they might not match.
Change your myDb.loescheFach(position); to myDb.loescheFach(id);
You're passing the position of ArrayList to SQLite to delete statement. You should pass FACHID (in your case) as an argument to delete statement.
As your posted code is incomplete I assume it as below.
....
....
build.setPositiveButton("Löschen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
// myDb.loescheFach(position);
// first get an id from ArrayList using position faecherListe.get(position)
// then pass that id to your method
myDb.loescheFach(id);
Toast.makeText(getApplicationContext(), faecherListe.get(position) + " gelöscht.", Toast.LENGTH_LONG).show();
myDb.zeigeFaecher();
dialogInterface.cancel();
}
});
....
....
First position will not equate to the rowid/id of the row in the table. Assuming that you have a id column defined as your_id_column INTEGER PRIMARY KEY (or with the AUTOINCREMENT keyword, that makes no real difference) and that you don't specify a value when inserting a row then the first id will likely be 1, then 2 then 3 ... etc.
However, position (3rd parameter passed to onItemClick/onItemLongClick) for the first item in the List will be 0, then 1 then 2 etc. So you will never actually delete correct row (clicking the first item will delete nothing, clicking the second item will delete the first) and when rows are deleted it gets even more out of sync.
The 4th parameter (long id) passed will be the rowid/id IF AND ONLY IF a CursorAdapter is used (i.e. a Cursor is the source data for the ListView). In which case the cursor MUST have a column named _id. However, it looks as though faecherListe is the source and as you use the get method that it is an ArrayList/List. As such the id passed will be the same value position except it is a long.
Now if faecherListe were an ArrayList<object_that_reflects_the_columns_of_the_table_including_id> then assuming a getter of getId you could use long retrieved_id = faecherListe.get(position).getId(). However, the comments :-
I guess you have ArrayList of String, that's why are getting String
value from ArrayList – Shashanth 10 hours ago
Ye
You simply have ArrayList and thus no means of ascertaining the id unless whatever data is held by the String is guaranteed to be unique.
Example
This is an example using object_that_reflects_the_columns_of_the_table_including_id in this case a Feacher class that just has a name and an id
Feacher.java
This is an entirely new class that allows you to have an ArrayList with all the relevant data/fields/columns (especially the id column).
i.e. you can an have ArrayList
public class Feacher {
private String name;
private long id;
public Feacher(String feacher_name) {
this(feacher_name,-1);
}
public Feacher(String feacher_name, long feacher_id) {
this.name = feacher_name;
this.id = feacher_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String toString() {
return name + " ID(" + String.valueOf(id) + ")";
}
}
DBHelper
This is the database helper (sub class of SQLiteOpenHelper) :-
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "feacher.db";
public static final int DBVERSION = 1;
public static final String TB_FEACHER = "feacher";
public static final String COL_FEACHER_ID = BaseColumns._ID;
public static final String COL_FEACHER_NAME = "feacher_name";
SQLiteDatabase mDB;
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String crtsql = "CREATE TABLE IF NOT EXISTS " + TB_FEACHER +
"(" +
COL_FEACHER_ID + " INTEGER PRIMARY KEY," +
COL_FEACHER_NAME + " TEXT" +
")";
db.execSQL(crtsql);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long addFeacher(String feacher_name) {
ContentValues cv = new ContentValues();
cv.put(COL_FEACHER_NAME,feacher_name);
return mDB.insert(TB_FEACHER,null,cv);
}
public ArrayList<Feacher> getAllAsFeacherArrayList() {
ArrayList<Feacher> rv = new ArrayList<>();
Cursor csr = mDB.query(
TB_FEACHER,
null,
null,
null,
null,
null,
null
);
while (csr.moveToNext()) {
rv.add(new Feacher(
csr.getString(csr.getColumnIndex(COL_FEACHER_NAME)),
csr.getLong(csr.getColumnIndex(COL_FEACHER_ID))
)
);
}
return rv;
}
public int deleteFeacher(long id) {
return mDB.delete(
TB_FEACHER,
COL_FEACHER_ID + "=?"
,new String[]{String.valueOf(id)}
);
}
}
the deleteFeacher method to delete a row according to it's id,
the addFeacher method allowing some test data to be added.
the getAllAsFeacherArrayList returns all data as an ArrayList (note uses the constructor that sets the id)
MainActivity.java
The activity that has the ListView.
public class MainActivity extends AppCompatActivity {
ListView mListView;
ArrayAdapter<Feacher> mAdapter;
DBHelper mDBHlpr;
ArrayList<Feacher> mFeacherList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = this.findViewById(R.id.listview);
mDBHlpr = new DBHelper(this);
addDataForTesting();
displayAdapter();
}
private void displayAdapter() {
if (mFeacherList == null) {
mFeacherList = mDBHlpr.getAllAsFeacherArrayList();
} else {
mFeacherList.clear();
for (Feacher f: mDBHlpr.getAllAsFeacherArrayList()) {
mFeacherList.add(f);
mAdapter.notifyDataSetChanged();
}
}
if (mAdapter == null) {
mAdapter = new ArrayAdapter<Feacher>(this,android.R.layout.simple_list_item_1,mFeacherList);
mListView.setAdapter(mAdapter);
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
mDBHlpr.deleteFeacher(mAdapter.getItem(i).getId());
displayAdapter();
return true;
}
});
}
}
private void addDataForTesting() {
mDBHlpr.addFeacher("Feacher 001");
mDBHlpr.addFeacher("Feacher 002");
mDBHlpr.addFeacher("Feacher 003");
}
}
Note for simplicity and also to avoid inadvertent deletion onItemLongClick has been used. The all important bit being mDBHlpr.deleteFeacher(mAdapter.getItem(i).getId()); which gets the id from the item (object, the Feacher) that was clicked according to the position.
activity_main.xml
A very basic layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<ListView
android:id="#+id/listview"
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFAAAAFF"
>
</ListView>
</LinearLayout>
Result
here's a screen shot after 3rd run so 9 rows have been added and 2 rows have been deleted (note id's 2 and 5 are missing). The list will refresh after a deletion so the row disappears almost immediately the long-click is completed.
This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 6 years ago.
So i'm having a little trouble with SQLite in Android. I followed a guide with which i created a table and wrote a working method to insert data. After i had a lot of data in it i wanted to delete it again so i wrote a method which dropped my table.
Now i have the problem that it won't create the table anymore. If i want to insert data it says "no such table".I don't really get why it won't create it anymore. Relevant code:
public class MeFragment extends Fragment implements View.OnClickListener {
private SQLiteDatabase newDB;
private DatabaseHelper dbHelper;
private String TABLE_NAME = DatabaseHelper.TABLE_NAME;
ArrayList<String> myCategoryList = new ArrayList<String>() {
};
ListView lv1;
ArrayAdapter<String> adapter1;
EditText editText;
Button addButton;
public MeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_me, container, false);
dbHelper = new DatabaseHelper(this.getActivity());
preFillCategories();
getCategories();
editText = (EditText) view.findViewById(R.id.addCategory);
addButton = (Button) view.findViewById(R.id.addCategoryButton);
addButton.setOnClickListener(this);
lv1 = (ListView) view.findViewById(R.id.listView1);
adapter1 = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, myCategoryList);
lv1.setAdapter(adapter1);
Utility.setDynamicHeight(lv1);
//dbHelper.removeAllData();
return view;
}
And my Database Helper Class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "categories.db";
public static final String TABLE_NAME = "categories_table";
public static final String COL = "CATEGORYNAME";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME +" (CATEGORYNAME TEXT PRIMARY KEY)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d("Hallo", "hallo");
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String CATEGORYNAME){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL, CATEGORYNAME);
long result = db.insert(TABLE_NAME, null, contentValues);
if(result == -1){
return false;
}
else{
return true;
}
}
public void removeAllData(){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DROP TABLE "+TABLE_NAME);
}
Any help would be very much appreciated
Can you add the removeAllData method to the dbhelper so we can see what you were doing?
Also, you're not doing anything to manage the db version number. If you're constantly using the same version number even after making changes, that could be a potential source of you problem.
Also, you should avoid calling any lifecycle methods directly (such as onCreate in your onUpgrade method). If you have code you want to invoke from multiple lifecycle methods, break that out into its own method so you don't run the risk of possibly introducing lifecycle issues on top of your current problem.
I am new to Android and SQLite database. I have been following online examples for storing and retrieving data from database but I get error when reading.
The code below is simple code for writing and reading data from database. When writing there is no error in application but when reading data, the application closes by displaying error. I am using Android studio 1.2.2 and testing it on Android version 5.0.1 Galaxy S4. Can any one tell me what is the problem here ?
/*********************activity_main.xml *************/
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView android:text="Hello Hello"
android:id="#+id/msg"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
<ListView android:id="#+id/contactListView"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_below="#+id/msg"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="48dp" />
</LinearLayout>
/*********************row.xml **************/
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent" android:layout_height="match_parent"
android:padding="10dip" >
<TextView android:id="#+id/Name"
android:layout_height="wrap_content" android:layout_width="match_parent"
android:layout_marginLeft="25dp" />
</LinearLayout>
/****************** Main Activity *****************/
public class MainActivity extends ActionBarActivity {
List<String> stringList = new ArrayList<String>();
ListAdapter adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listview = (ListView) findViewById(R.id.contactListView);
adapter = new ListAdapter(this, stringList);
listview.setAdapter(adapter);
NameDatabase db = null;
db = new NameDatabase(this);
db.addContact(1, "Sujan Raj Shrestha");
db.addContact(2, "Kim Sae Hyun");
db.addContact(3, "Kim Jong Kwon");
Cursor cr = db.getData(0);
adapter.add(cr.getString(1).toString());
}
public class ListAdapter extends ArrayAdapter<String>{
public ListAdapter(Context context, List<String> object){
super(context, R.layout.row, object);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
String nm = stringList.get(position);
if (row == null){
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.row, null);
}
((TextView) row.findViewById(R.id.Name)).setText(nm);
return row;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
/ *************** NameDatabase.java ****************/
public class NameDatabase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String NAMELIST = "nametable";
public NameDatabase (Context context){
super(context, NAMELIST, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db){
String CREATE_CONTACTS_TABLE = "CREATE TABLE contacts" +" (id INTEGER PRIMARY KEY, name TEXT NOT NULL )";
db.execSQL(CREATE_CONTACTS_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("Drop TABLE IF EXISTS" + NAMELIST);
onCreate(db);
}
public boolean addContact(int id, String name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("id", id);
values.put("name", name);
db.insert(NAMELIST, null, values);
db.close();
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from nametable where id=" + id + "", null);
return res;
}
}
I just figured out your issue the main issue is the table from where you are querying on is not correct, indeed it is your database name, They correct version of getData() is following:
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from contacts where id=" + id + "", null);
return res;
}
You are trying to access the content of table using database name. Try using table name as "contacts". Replace NAMELIST = "contacts" , also Pass the Database name in Constructor
like super(context, DATABASE_NAME, null, DATABASE_VERSION);
and add variable
String DATABASE_NAME = "someName";
For getting Cursor results add
res.moveToNext();
below of
Cursor res = db.rawQuery("select * from nametable where id=" + id + "", null);
Since you are querying the table but your cursor remains at -1 position by default. Therefore we have to move cursor to row 1 and so on.
Hope this works. :)
Peace V
try this to fetch the data from database
cur = db.query(true, "contacts", new String[] {
"id", "name"
}, "id = " + id, null, null, null, null, null);
I have a listview that contains some data which I got from the web. Now I can make changes in the list item and once I make changes to the item, I am storing the updated value in the db. When i login in next time to the app, I am downloading the content from net and showing it in the listview with the changes that I have done last time. So my approach here is, I am querying the db for each item in the getview method of the list adapter to check for changes. Is it a good practice to do a db query for each item's getview method of the adapter? If not could you please suggest me some alternative. Thanks.
Never, really, never do that.
If you put your data download code in the getView method of the adapter it will make a network call for each row of the list.
Even worst, it will call it anytime that row appears on the screen, not only one time for row.
You should get all your data first, then use the adapter only to draw it.
You can at anytime call the db to check for changes and, if needed, notify the adapter to redraw the list to show the changes.
Hope this helps.
In Android development, any time you want to show a vertical list of items you will want to use a ListView which is populated using an Adapter to a data source. When we want the data for the list to be sourced directly from a SQLite database query we can use a CursorAdapter.
The CursorAdapter fits in between a Cursor (data source from SQLite query) and the ListView (visual representation) and configures two aspects:
Which layout template to inflate for an item
Which fields of the cursor to bind to views in the template
Creating the View Template
When we want to display a series of items into a list using a custom representation of the items, we need to use our own custom XML layout template for each item. We can simply create an XML layout template in res/layout/item_todo.xml representing a particular cursor row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Study cursors"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvPriority"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="3"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Defining the Adapter
public class ViewAdapter extends BaseAdapter {
LayoutInflater mInflater;
public ViewAdapter() {
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return favoriteList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listitem,null);
}
final TextView nameText = (TextView) convertView.findViewById(R.id.nameText);
nameText.setText("Name : "+favoriteList.get(position).getName());
final TextView ageText = (TextView) convertView.findViewById(R.id.ageText);
ageText.setText("Age : "+favoriteList.get(position).getAge());
final Button edit = (Button) convertView.findViewById(R.id.edit);
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.row);
dialog.setTitle("Add Data to Database");
final EditText name = (EditText) dialog.findViewById(R.id.name);
final EditText age = (EditText) dialog.findViewById(R.id.age);
Button Add = (Button) dialog.findViewById(R.id.Add);
Add.setText("Add");
Add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(name.getText().toString() != null && name.getText().toString().length() >0 ){
if(age.getText().toString() != null && age.getText().toString().length() >0 ){
db.updateRow(favoriteList.get(position).getId(), name.getText().toString(), age.getText().toString());
favoriteList = db.getFavList();
listView.setAdapter(new ViewAdapter());
dialog.dismiss();
}else{
Toast.makeText(getApplicationContext(), "Please Enter the Age", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getApplicationContext(), "Please Enter the Name", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
});
final Button delete = (Button) convertView.findViewById(R.id.delete);
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
db.removeFav(favoriteList.get(position).getId());
notifyDataSetChanged();
favoriteList = db.getFavList();
listView.setAdapter(new ViewAdapter());
}
});
return convertView;
}
}
Create database
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
//Database Version
private static final int DATABASE_VERSION = 1;
//Database Name
private static final String DATABASE_NAME = "Test";
//Table Name
private static final String TABLE_TEST = "TestTable";
//Column Name
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_AGE = "age";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//Create Table
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_TEST + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_AGE + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEST);
onCreate(db);
}
//Insert Value
public void adddata(Context context,String movieId,String songId) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, movieId);
values.put(KEY_AGE, songId);
db.insert(TABLE_TEST, null, values);
db.close();
}
//Get Row Count
public int getCount() {
String countQuery = "SELECT * FROM " + TABLE_TEST;
int count = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
if(cursor != null && !cursor.isClosed()){
count = cursor.getCount();
cursor.close();
}
return count;
}
//Delete Query
public void removeFav(int id) {
String countQuery = "DELETE FROM " + TABLE_TEST + " where " + KEY_ID + "= " + id ;
SQLiteDatabase db = this.getReadableDatabase();
db.execSQL(countQuery);
}
//Get FavList
public List<FavoriteList> getFavList(){
String selectQuery = "SELECT * FROM " + TABLE_TEST;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
List<FavoriteList> FavList = new ArrayList<FavoriteList>();
if (cursor.moveToFirst()) {
do {
FavoriteList list = new FavoriteList();
list.setId(Integer.parseInt(cursor.getString(0)));
list.setName(cursor.getString(1));
list.setAge(cursor.getString(2));
FavList.add(list);
} while (cursor.moveToNext());
}
return FavList;
}
}
Enojoys.... :)
It is better to use cursor adapter to bind the list view.You can use Loader to get the list updated even if there is a change in the data base.
onLoadFinished (Loader loader, D data) of the Loader call back would be monitor for changes to the data, and report them to you through new calls. You should not monitor the data yourself.
I am using this code , but i ma getting a Runtime exception. I did all the required effort and work to remove this error. But it not work for me . i am using DatabaseHandler. java and AndroidSpinnerFromSQLiteActivity.java class, and my xml is activity_databse_handler.xml.
public class AndroidSpinnerFromSQLiteActivity extends Activity implements OnItemSelectedListener {
// Spinner element
Spinner spinner;
// Add button
utton btnAdd;
// Input text
EditText inputLabel;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database_handler);
// Spinner element
spinner = (Spinner) findViewById(R.id.spinner);
// add button
btnAdd = (Button) findViewById(R.id.btn_add);
// new label input field
inputLabel = (EditText) findViewById(R.id.input_label);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Loading spinner data from database
loadSpinnerData();
/**
* Add new label button click listener
* */
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String label = inputLabel.getText().toString();
if (label.trim().length() > 0) {
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// inserting new label into database
db.insertLabel(label);
// making input filed text to blank
inputLabel.setText("");
// Hiding the keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);
// loading spinner with newly added data
loadSpinnerData();
} else {
Toast.makeText(getApplicationContext(), "Please enter label name",
Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Function to load the spinner data from SQLite database
* */
public void loadSpinnerData() {
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
String label = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + label,
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
===========================================================================================
public class DatabaseHandler extends SQLiteOpenHelper {
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
try {
// Category table create query
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";
db.execSQL(CREATE_CATEGORIES_TABLE);
}
catch (Exception e) {
// TODO: handle exception
}
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
// Create tables again
onCreate(db);
}
/**
* Inserting new lable into lables table
* */
// Database Version
private static int DATABASE_VERSION = 1;
// Database Name
private static String DATABASE_NAME = "spinnerExample";
// Labels table name
private static String TABLE_LABELS = "labels";
// Labels Table Columns names
private static String KEY_ID = "id";
private static String KEY_NAME = "name";
public void insertLabel(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label);
// Inserting Row
db.insert(TABLE_LABELS, null, values);
db.close(); // Closing database connection
}
* Getting all labels
* returns list of labels
* */
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
}
===========================================================================================
<!-- Label -->
<!-- Input Text -->
<!-- Add Button -->
<!-- Select Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Select Label"
android:padding="8dip" />
<!-- Spinner Dropdown -->
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/spinner_title"
android:layout_marginTop="20dip"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip"
/>
</LinearLayout>
You don't want the application context for the db, you want the activity context, so your call should be:
DatabaseHandler db = new DatabaseHandler(this);