SQLite Database not getting updated - java

So Ive created an app where the user can input details about the movies he has watched such as name,cast,rating...ect and the details are stored in a database inside a table names which is initialized in the DataBaseHelper class as
public static final String TABLE_NAME = "table1";
in the below segment of code Ive created a list view and displayed the names of the movies with a checkbox in front of each name. where the check box if ticked mean that its a favorite else not a favorite...initially the column in the table which holds if the movie is a favorite is set to "no"
when ticked and button pressed I want all the movie names with the tick on to update to "yes" in the database.
DisplayActivity class with the list view
public class DisplayActivity extends AppCompatActivity {
DataBaseHelper myDb;
ListView movieNList;
Button addFavoritesB,button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
movieNList =(ListView) findViewById(R.id.moviesLV);
myDb=new DataBaseHelper(this);
addFavoritesB=(Button) findViewById(R.id.addButton);
button=(Button) findViewById(R.id.button);
ArrayList<String> theList=new ArrayList<>();
Cursor data=myDb.getData();
if (data.getCount()==0){
Toast.makeText(DisplayActivity.this,"The Database is empty",Toast.LENGTH_SHORT).show();
}else{
//Adds data to the list view
while(data.moveToNext()){
theList.add(data.getString(1));
Collections.sort(theList);
ListAdapter listAdapter=new ArrayAdapter<>(this, android.R.layout.simple_list_item_multiple_choice,theList);
movieNList.setAdapter(listAdapter);
}
}
buttonAction();
}
public void buttonAction(){
myDb.getWritableDatabase();
addFavoritesB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String itemSelected="Selected items : \n";
for (int i=0;i<movieNList.getCount();i++){
if (movieNList.isItemChecked(i)){
itemSelected += movieNList.getItemAtPosition(i)+"\n";
System.out.println(itemSelected);
myDb.updateFavorites(itemSelected,"yes");
}
}
}
});
}
Method in DataBaseHelper class to update the favorites column
public boolean updateFavorites(String name,String favorites) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("FAVORITES", favorites);
Cursor res = db.rawQuery("select * from table1 where name=? ", new String[]{name});
if (res.getCount() > 0) {
long result = db.update(TABLE_NAME, contentValues, "name=?", new String[]{name});
if (result == -1) {
return false;
} else {
return true;
}
} else {
return false;
}
}
when I try it like this, the columns wont update....Please help

Assuming that itemSelected is created correctly inside the onClick() listener, I suggest that you use a char like "|" as a delimiter instead of "\n" for the movie titles and remove "Selected items : \n" from the start of itemSelected.
Also move myDb.updateFavorites(itemSelected,"yes"); out of the for loop, so that the updateFavorites() is called only once for all selected movies:
public void buttonAction(){
myDb.getWritableDatabase();
addFavoritesB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String itemSelected="|";
for (int i=0;i<movieNList.getCount();i++){
if (movieNList.isItemChecked(i)){
itemSelected += movieNList.getItemAtPosition(i)+"|";
}
}
itemSelected += "|";
myDb.updateFavorites(itemSelected,"yes");
}
});
}
Then use the update() method to update the table with the operator LIKE in the WHERE clause:
public int updateFavorites(String name, String favorites) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("FAVORITES", favorites);
return db.update(TABLE_NAME, contentValues, "? LIKE '%|' || name || '|%'", new String[] {name});
}
Note that I changed the return type of updateFavorites() from boolean to int() because db.update() returns the number of updated rows.

Related

Deleting an item from a listview with SQLite

I have a problem with deleting items from my database in listview. This is my code from my helper to delete data:
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + DB_TABLE + " WHERE " + COL1 + " = '" + id +"'" + " AND "
+ COL2 + " = '" + name +"'";
db.execSQL(query);
}
It views the data with this code
private void viewData() {
Cursor cursor = bh.viewData();
if (cursor.getCount() == 0) {
Toast.makeText(this, "Nothing to show", Toast.LENGTH_SHORT).show();
} else {
while (cursor.moveToNext()) {
listItem.add(cursor.getString(1));
}
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, listItem);
lv.setAdapter(adapter);
}
But the problem is I have no idea how to delete it from database
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//It supposed to be deleted
}
});
Thank you in advance
In short you are presneting a list that is a single string extracted from the database.
Your delete is expecting two values. The id and the name (the listed value). Both values are not available from the single string that is listed.
If COL2 were UNIQUE (i.e. the same value would never be used) then you could easily just delete based upon this value but frequently names are not unique in which case it would be impossible to derive the id from the name. You would either have to use an ArrayList of objects (such an object containing both the id and the name) or have another array containing the id's that is in sync with the array of names.
I'd suggest using a CursorAdapter which :-
caters for Cursors and most especially provides the id as the 4th parameter to the onItemClick (for other adapters it is the same as the 3rd parameter i.e. the position).
NOTE the id column MUST be named _id.
Has all the rows in the Cursor used as the source available.
Has the Cursor appropriately positioned when onItemClick (and also onItemLongClick) is called.
Example
The following is an example based upon your code.
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String DB_TABLE = "mytable";
public static final String COL1 = BaseColumns._ID; //<<<<<<<<<IMPORTANT uses the _id column
public static final String COL2 = "mynamecolumn";
public DatabaseHelper(#Nullable Context context) {
super(context, DBNAME, null, DBVERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + DB_TABLE +
"(" +
COL1 + " INTEGER PRIMARY KEY," +
COL2 + " TEXT " +
")"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long insert(String name) {
ContentValues cv = new ContentValues();
cv.put(COL2,name);
return this.getWritableDatabase().insert(DB_TABLE,null,cv);
}
public int delete(long id) {
SQLiteDatabase db = this.getWritableDatabase();
// ID WILL BE UNIQUE so that's enough to IDentify a row
return db.delete(DB_TABLE,COL1 + "=?", new String[]{String.valueOf(id)});
}
public Cursor viewData() {
SQLiteDatabase db = this.getWritableDatabase();
return db.query(DB_TABLE,null,null,null,null,null,null);
}
}
The above should be similar to what you have BUT note the name _id (obtained via the constant BaseColumns._ID) for COL1.
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper bh;
Cursor csr;
ListView lv;
SimpleCursorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = this.findViewById(R.id.myListView);
bh = new DatabaseHelper(this);
addSomeDataIfNone(); //<<<<< Add some testing data
manageListView(); //<<<<< Manage the LIstView
}
private void manageListView() {
csr = bh.viewData();
if (adapter == null) {
adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
csr,
new String[]{DatabaseHelper.COL2},
new int[]{android.R.id.text1},
0
);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bh.delete(id); //<<<<< uses the 4th parameter
manageListView(); //<<<<< refresh the ListView as the data has changed
}
});
} else {
adapter.swapCursor(csr);
}
}
private void addSomeDataIfNone() {
if(DatabaseUtils.queryNumEntries(bh.getWritableDatabase(),DatabaseHelper.DB_TABLE) > 0) return;
bh.insert("Name 1");
bh.insert("Name 2");
bh.insert("Name 3");
}
#Override
protected void onDestroy() {
csr.close(); // Done with the Cursor so close it
bh.close(); // Done with the Database as this is the Main Activity
super.onDestroy();
}
}
Note how this is also quite similar BUT
uses the SimpleCursorAdapter as the source for the ListView. It iself uses a Cursor as the source for the data.
does not create a new Adapter each time the data is viewed
automatically refreshes the ListView when an item is clicked and thus deleted.
uses the id to delete the clicked item as that is all that is needed to unqiuely identify a row.
Results
When first run :-
When clicking Name 2 :-

Values are not inserted properly in the SQLite database

I'm setting SQLite to my app signup page and I want to use my mobile number instead of email for signing up. My app shows no error but the toast ("Registered Successfully") never appears and activity mainWindow never starts.
My Database file is below
public class DatabaseHelp extends SQLiteOpenHelper {
public DatabaseHelp( Context context) {
super(context,"Login.db",null,1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table user(First_NAME text ,Last_NAME text,mobile number primary key ,password text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists user");
}
//inserting in database
public boolean insert(String First_NAME,String Last_NAME,String mobile,String password){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("Fisrt Name",First_NAME);
contentValues.put("Last Name",Last_NAME);
contentValues.put("Mobile Number",mobile);
contentValues.put("Password",password);
long ins=db.insert("user",null,contentValues);
if(ins==-1) {return false;}
else{ return true;}
}
// if number exists
public Boolean chkemail(String mobile){
SQLiteDatabase db= this.getWritableDatabase();
Cursor cursor=db.rawQuery("Select * from user where mobile=?",new String[]{mobile});
if(cursor.getCount()>0) return false;
else return true;
}
}
My Signup page java file is below
public class signup extends AppCompatActivity {
DatabaseHelp db;
EditText e1,e2,e3,e4,e5;
Button b1;
public void onClick(View view){
Intent i1 = new Intent(this, forgotpass2.class);
startActivity(i1);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
db=new DatabaseHelp(this);
e1=(EditText)findViewById(R.id.editText5);
e2=(EditText)findViewById(R.id.editText6);
e3=(EditText)findViewById(R.id.editText);
e4=(EditText)findViewById(R.id.editText7);
e5=(EditText)findViewById(R.id.editText8);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1=e1.getText().toString();
String s2=e2.getText().toString();
String s3=e3.getText().toString();
String s4=e4.getText().toString();
String s5=e5.getText().toString();
if(s1.equals("")||s2.equals("")||s3.equals("")||s4.equals("")||s5.equals("")) {
Toast.makeText(getApplicationContext(), "Fields are empty", Toast.LENGTH_SHORT).show();
} else {
if(s4.equals(s5)){
Boolean chkemail=db.chkemail(s3);
if(chkemail == true) {
Boolean insert = db.insert(s1,s2,s3,s4);
if(insert == true) {
Toast.makeText(getApplicationContext(),"Registered Successfully",Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(),"Mobile Number already exits",Toast.LENGTH_SHORT).show();
}
}
Toast.makeText(getApplicationContext(),"Passwords do not match",Toast.LENGTH_SHORT).show();
}
}
});
}
}
What should I do to make the code work properly?
There are several things in your code which need to be pointed out. First, about the insert function, the column names have spaces and I think you should get rid of those spaces for SQLite column names. Modify your insert function like the following.
public boolean insert(String First_NAME,String Last_NAME,String mobile,String password){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("first_name",First_NAME);
contentValues.put("last_name",Last_NAME);
contentValues.put("mobile",mobile);
contentValues.put("password",password);
long ins=db.insert("user",null,contentValues);
if(ins==-1) return false;
else return true;
}
Now, once you are done with this, I think your chkemail function now works correctly. Because, previously the field mobile was not found in the database table as the column name was different (i.e. the column name in your code was Mobile Number, which I have changed in the insert function to match with the query).
public boolean chkemail(String mobile){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("Select * from user where mobile=?",new String[]{mobile});
if(cursor.getCount()>0) return false;
else return true;
}
Please note that I have changed the return type of the chkemail function from Boolean to boolean.
And finally, in the signup activity, you need to modify the part mentioned below as well.
// Changed from Boolean to boolean
boolean insert = db.insert(s1,s2,s3,s4);
if(insert == true) {
Toast.makeText(getApplicationContext(),"Registered Successfully",Toast.LENGTH_SHORT).show();
// Start the new activity here
Intent newIntent = new Intent(this, mainWindow.class);
startActivity(newIntent);
}
Hope that helps!

How implementation SQLite Join using spinner at Android Studio to get id from tables

I've created 2 tables within an SQLite database, stok and sales
at DatabaseHelper.java
Create table stok
String tbStok = "CREATE TABLE stok(id_stok INTEGER PRIMARY KEY AUTOINCREMENT, waktu_stok DATETIME, id_sales INTEGER, stok INTEGER, FOREIGN KEY id_sales REFERENCES sales(id_sales)";
Create table sales
String tbSales = "CREATE TABLE sales(id_sales INTEGER PRIMARY KEY AUTOINCREMENT, nama VARCHAR, kodesales VARCHAR, username VARCHAR, password VARCHAR, level INTEGER)";
Create List Data from SQLite
public List<String> getSpinnerSales(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + "sales";
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(0));
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
Display on Spinner
private void loadSpinnerSales() {
// database handler
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getSpinnerSales();
// 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
spsales.setAdapter(dataAdapter);
}
Test if spinner selected
spsales.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {
String label = parent.getItemAtPosition(position).toString();
Log.d("label:", label);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
I need id_sales to put values and save to other tables SQLite, but the spinner must display the name of sales.
the best way is to use custom adapter then
you can pass List of objects (in your case is"list of sales id and name" )to the adapter not just a List of strings,
then on item selected you will get the selected object
then you can get whatever you need id or name
you can follow this link to make custom adapter
https://abhiandroid.com/ui/custom-spinner-examples.html
I Solve this problems with edited the code
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(0)+cursor.getString(1));
} while (cursor.moveToNext());
}
And at spinner on item selected manipulate with substring
spsupir.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {
String label = parent.getItemAtPosition(position).toString();
String ids = String.valueOf(label).substring(0,1);
Log.d("label:", ids);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Code edited
String label = parent.getItemAtPosition(position).toString();
String ids = String.valueOf(label).substring(0,1);
Log.d("label:", ids);
Another Solve Problems
Step 1 Create the model class
public class Sales {
String id_sales,nama;
public Sales(String id_sales, String nama) {
this.id_sales = id_sales;
this.nama = nama;
}
public String getId_sales() {
return id_sales;
}
public void setId_sales(String id_sales) {
this.id_sales = id_sales;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
#Override
public String toString() {
return nama;
}
}
Step 2 Put all data from SQLite table sales
//Data spinner supir
public ArrayList<Sales> getSpinnerSales(){
ArrayList<Sales> salesList = new ArrayList<>();
// Select All Query
String selectQuery = "SELECT * FROM " + "sales";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
salesList.add(new Sales(cursor.getString(0), cursor.getString(1)));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return salesList;
}
Step 3 Generate void to consume data from sqlite aa Activity
private void loadSpinnerSales() {
// database handler
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
ArrayList<Sales> salesList = db.getSpinnerSales();
ArrayAdapter<Sales> adapter = new ArrayAdapter<Sales>(this, android.R.layout.simple_spinner_dropdown_item, salesList);
spsales.setAdapter(adapter);
}
Step 4 Load method at OnCreate
spsales = (Spinner) findViewById(R.id.spSales);
loadSpinnerSales();
spsales.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Sales sales = (Sales) parent.getSelectedItem();
Toast.makeText(getApplicationContext(),sales.getId_sales(),Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

Receive data from database based on user input in EditText

I have a quick question, I'm sure I'm just making a small mistake but I can't figure it out.I'm trying to get information from the database based on what the user inputs in an EditText. I'm getting error
"java.lang.IllegalStateException: Couldn't read row 0, col 1 from
CursorWindow. Make sure the Cursor is initialized correctly before
accessing data from it.".
Here's My Main Activity Class
public class MainActivity extends AppCompatActivity {
Button create;
Button retrieve;
Button save;
Button clear;
EditText listName;
EditText listDetails;
ToDoListDatabase myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new ToDoListDatabase(this);
create = (Button)findViewById(R.id.createButton);
retrieve = (Button)findViewById(R.id.retrieveButton);
save = (Button)findViewById(R.id.saveButton);
clear = (Button)findViewById(R.id.clearButton);
listName = (EditText)findViewById(R.id.listName);
listDetails = (EditText)findViewById(R.id.listDetails);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddList();
}
});
retrieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showList(listName.getText().toString());
}
});
}
//Method Resets EditText back to default
public void resetEditText(){
listName.setText("");
listDetails.setText("");
}
//Method Adds List Entered By User To DataBase
public void AddList(){
boolean isInserted = myDb.insertData(listName.getText().toString(), listDetails.getText().toString());
if(isInserted == true){
Toast.makeText(MainActivity.this,"List " + listName.getText().toString() + " successfully created", Toast.LENGTH_LONG).show();
resetEditText();
}
else
Toast.makeText(MainActivity.this,"Error creating list", Toast.LENGTH_LONG).show();
}
public void showList(String listName){
Cursor res = myDb.getList(listName);
if(res.getCount() == 0){
Toast.makeText(MainActivity.this,"Error finding list", Toast.LENGTH_LONG).show();
return;
}
StringBuffer buffer = new StringBuffer();
buffer.append(res.getString(2));
listDetails.setText(buffer); //Not working yet!!!!
}
}
Here's My DataBase Class
public class ToDoListDatabase extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "List_db";
public static final String TABLE_NAME = "List_Table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "LIST";
public ToDoListDatabase(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,NAME TEXT,LIST TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXITS" + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String list) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, name);
contentValues.put(COL_3, list);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) { //returns -1 if not inserted
return false;
} else
return true;
}
public Cursor getList(String listName) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT LIST FROM " + TABLE_NAME + " WHERE NAME = '" +listName+"'" , null);
return res;
}
}
Here's my Android Monitor
10-10 13:11:41.618 2643-2643/com.example.stephen.todolist E/AndroidRuntime: FATAL EXCEPTION: main
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 4
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:424)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at com.example.stephen.todolist.MainActivity.showList(MainActivity.java:79)
at com.example.stephen.todolist.MainActivity$2.onClick(MainActivity.java:47)
at android.view.View.performClick(View.java:4439)
at android.widget.Button.performClick(Button.java:139)
at android.view.View$PerformClick.run(View.java:18395)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5317)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Your ToDoListDatabase class does not contain any field with name listName on which you are calling getText(). Also you are not passing any parameter in your getList(). You should pass your EditText query in this getList() and then create query on this param.
Changes:
MainActivy.java
retrieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showList(listName.getText().toString());
}
});
public void showList(String listName){
Cursor res = myDb.getList(listName);
if(res.getCount() == 0){
Toast.makeText(MainActivity.this,"Error finding list", Toast.LENGTH_LONG).show();
//return;
}
}
StringBuffer buffer = new StringBuffer();
buffer.append(res.getString(2));
listDetails.setText(buffer); //Not working yet!!!!
}
ToDoListDatabase.java
public Cursor getList(String listName) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT LIST FROM " + TABLE_NAME + " WHERE NAME ='" + listName+"'" , null);
return res;
}
Update
Change your showList as
public void showList(String listName){
Cursor res = myDb.getList(listName);
if(res.getCount() == 0){
Toast.makeText(MainActivity.this,"Error finding list", Toast.LENGTH_LONG).show();
return;
}
res.moveToFirst();
StringBuffer buffer = new StringBuffer();
while (!res.isAfterLast()) {
buffer.append(res.getString(0));
res.moveToNext();
}
res.close();
listDetails.setText(buffer); //Not working yet!!!!
}
You are using listName (Edidtext) in your SQLiteOpenHelper class so u r getting error kindly pass the value of listName from your activity to method like.
//call and pass value like this.
showList(listName.getText().toString());
//or like this
String mListname = listName.getText().toString();
if(!TextUtils().isEmpty(mListname))//check if not empty
{
showList(mListname);
}else{
//handle error
}
// your method
public void showList(String listName)
{
//your implementation
}
SQLiteOpenHelper doesnt extends View so u cannot use view there.
but u can pass it to method parameter to access it.
showList(EditText listName)
{
String val = listName.getText().toString();
}
//and pass your editText
showList(listName);
Good programming practice for database and databesehelper to wrap them around another class, open database when needed not on every query and making queries with strings not with views themselves. Check this thread for creating a singleton DatabaseManager and execute queries with it.

Android: How to display string on textview from console

I'm trying to display string on the textview. I'm succesfully able to print it on the console from database, but I'm not able to figure out how to print all the strings on different different textviews. Here is my code:
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
EditText search;
Button insert;
TextView txt1, txt2, txt3, txt4, txt5;
DatabaseHandler db;
List<History> history;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHandler(this);
search = (EditText) findViewById(R.id.search_word);
insert = (Button) findViewById(R.id.insert);
txt1 = (TextView) findViewById(R.id.txt1);
txt2 = (TextView) findViewById(R.id.txt2);
txt3 = (TextView) findViewById(R.id.txt3);
txt4 = (TextView) findViewById(R.id.txt4);
txt5 = (TextView) findViewById(R.id.txt5);
insert.setOnClickListener(this);
history = db.getAllHistory();
}
public void onClick(View v) {
db.addHistory(new History(search.getText().toString(), null));
Toast.makeText(getApplicationContext(),
"Inserted: " + search.getText().toString(), Toast.LENGTH_LONG)
.show();
}
#Override
protected void onStart() {
super.onStart();
List<History> history = db.getAllHistory();
for (History cn : history) {
String log = "Search Strings: " + cn.getName();
Log.d("Search Strings: ", log);
}
}
}
This is my activity in which I'm bringing my all database value on onStart() function. Now here I have to set all the data coming from database on the textview. Here is my DabaseHandler class in which I'm taking out each row.
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "historyManager";
private static final String TABLE_HISTORY = "histories";
private static final String KEY_NAME = "history";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_HISTORY_TABLE = "CREATE TABLE " + TABLE_HISTORY + "("
+ KEY_NAME + " TEXT" + ")";
db.execSQL(CREATE_HISTORY_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HISTORY);
onCreate(db);
}
void addHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, history.getName());
db.insert(TABLE_HISTORY, null, values);
db.close();
}
History getHistory(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_HISTORY, new String[] { KEY_NAME },
"=?", new String[] { String.valueOf(id) }, null, null, null,
null);
if (cursor != null)
cursor.moveToFirst();
History history = new History(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
return history;
}
public List<History> getAllHistory() {
List<History> historyList = new ArrayList<History>();
String selectQuery = "SELECT * FROM " + TABLE_HISTORY;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
History contact = new History();
contact.setName(cursor.getString(0));
historyList.add(contact);
} while (cursor.moveToNext());
}
return historyList;
}
public int updateHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, history.getName());
return db.update(TABLE_HISTORY, values, KEY_NAME + " = ?",
new String[] { String.valueOf(history.getName()) });
}
public void deleteHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_HISTORY, KEY_NAME + " = ?",
new String[] { String.valueOf(history.getName()) });
db.close();
}
public int getHistoryCount() {
String countQuery = "SELECT * FROM " + TABLE_HISTORY;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
}
Please help in getting data printed on the textview. On the Log.d I can see all my data coming, one after another. But I'm not able to print all the data.
It's answer for "Thank You for that. Can you tell me how to set the data which I have printed in MainActivity on onStart() method (Log.d("")). If you can give me the code for that, that will be much easier for me."
try this:
List<String> listNames = new ArrayList<String>();//global variable
List<History> history = db.getAllHistory();
for (History cn : history) {
listNames.add(cn.getName());
}
or, if have in History field date try is, after easy will sort:
Map<String, Date> historyMap = new HashMap<String, Date>();
List<History> history = db.getAllHistory();
for (History cn : history) {
historyMap.put(cn.getName, cn.getDate);
}
You need make ListView in which will show your data from DB.Because you have many items datas getting from db.
I suggest to the next version:
In xml file you creat:
<ListView
android:id="#+id/list_names"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
...>
You need create Adapter for your list with next xml resource:
<TextView
android:id="#+id/text_name"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
In java code:
in onCreate:
ListView list = (ListView) findViewById(R.id.list);
OurAdapter adapter = new OurAdapter(..., List<String> yourListWithName);
list.setAdapter(adapter);
if you want a more detailed description of the code tell me.
For add last item in top you need next, create spec. internal class :
class Holder implements Comparable<Holder> {
String key;
Double value;
public int compareTo(Holder another) {
return another.value.compareTo(value);
}
}
and use him how:
List<this.Holder> listSortforLastInTop = new ArrayList<this.Holder>();
and
for(...){
Holder holder = new Holder();
holder.key=...;
older.value=..;
listSortforLastInTop.add(holder);
}

Categories

Resources