Im trying to figure out how I can delete one user at a time by typing in the edittext the users username and clicking deleting which I then want all the users information (username, usernum, password, birthdate, phone, address) to be deleted from the database. Below is my code and for some reason it isnt working can any one please please help me!! Im very desperate and ive been trying to figure out the problem for hours.
DatabaseHelperUser class:
public class DatabaseHelperUser extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "User.db";
public static final String TABLE_NAME = "User_table";
public static final String COL1 = "ID";
public static final String COL2 = "UserNum";
public static final String COL3 = "UserName";
public static final String COL4 = "Password";
public static final String COL5 = "BirthDate";
public static final String COL6 = "Phone";
public static final String COL7 = "Address";
public DatabaseHelperUser(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, UserNum TEXT,UserName Text,Password Text,BirthDate Text,Phone Text,Address Text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
public boolean deleteData(String UserName) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "UserName" + "=?" + UserName, null) > 0;
}
}
RemoveUser class:
public class RemoveUser extends AppCompatActivity {
Button btdelete;
EditText txtUser;
DatabaseHelperUser myDb;
private String selectedName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remove_user);
btdelete = (Button) findViewById(R.id.butRemove);
txtUser = (EditText) findViewById(R.id.etxtUserName);
myDb = new DatabaseHelperUser(this);
btdelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean delete = myDb.deleteData(txtUser.getText().toString());
if(delete == true)
Toast.makeText(RemoveUser.this,"User has been deleted", Toast.LENGTH_LONG).show();
else
Toast.makeText(RemoveUser.this,"User has not been deleted", Toast.LENGTH_LONG).show();
}
});
}
}
You must pass the variable UserName as the 3d argument of the method delete(), so it will replace the placeholder ? when the statement is executed:
public boolean deleteData(String UserName) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "UserName = ?", new String[] {UserName}) > 0;
}
Related
I want to save name in the SQLite Database and later in another activity I want to retrieve that name as a String Value. But I am not being able to get data from the database. Help me please. My code is given below,
Database Helper:
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "user";
private static final String COL1 = "ID";
private static final String COL2 = "name";
public void onCreate(SQLiteDatabase db) {String createTable =
"CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY
AUTOINCREMENT, " + COL2 +" TEXT)";
db.execSQL(createTable);}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
MainActivity:
mDatabaseHelper=new DatabaseHelper(this);
Username=(EditText)findViewById(R.id.user);
saveBtn=(Button)findViewById(R.id.button);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String newEntry = Username.getText().toString();
AddData(newEntry);
Username.setText("");
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
}
}
HomeActivity:
public class HomeActivity extends AppCompatActivity {
DatabaseHelper mDatabaseHelper;
String Username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDatabaseHelper = new DatabaseHelper(this);
}
}
Here, in this home activity i want to get the username as a string but I don't know how to do that. Help me please...
To retrieve data, you run a query that extracts the data into a Cursor. The Cursor will consist of 0-n rows and will have as many columns as defined in the query. You then move through the rows and use the appropriate Cursor get????? methods to get the actual data.
As an example you could add the following method to your DatabaseHelper :-
public String getName(long id) {
String rv = "not found";
SqliteDatabase db = this.getWritableDatabase();
String whereclause = "ID=?";
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = db.query(TABLE_NAME,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getString(csr.getColumnIndex(COL2));
}
return rv;
}
The above can then be used by String name = mDatabaseHelper.getName(1);.
Note that this assumes that a row with an ID of 1 exists.
Your Database Helper:
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "user";
private static final String COL1 = "ID";
private static final String COL2 = "name";
private static final String createTable = "CREATE TABLE " + TABLE_NAME + " (" + COL1 +" INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 +" TEXT)"; // You have written ID inplace of COL1
public DatabaseHelper(Context context)
{
super(context,DB_NAME,null,1);
}
public void onCreate(SQLiteDatabase db)
{
db.execSQL(createTable);
}
public boolean insertData(String name) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues1 = new ContentValues();
contentValues1.put(COL2,name);
long result1 = sqLiteDatabase.insert(TABLE_NAME,null,contentValues1);
return result1 != -1;
}
public Cursor viewData()
{
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor ;
String query = "Select * from " +TABLE_NAME;
cursor= sqLiteDatabase.rawQuery(query, null);
return cursor;
}
Your Main Activity:
mDatabaseHelper=new DatabaseHelper(this);
Username=(EditText)findViewById(R.id.user);
saveBtn=(Button)findViewById(R.id.button);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String newEntry = Username.getText().toString();
mDatabaseHelper.insertData(newEntry);
Username.setText("");
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
}
});
}
}
Your Home Activity:
public class HomeActivity extends AppCompatActivity {
DatabaseHelper mDatabaseHelper;
String Username;
ArrayList<String> listItem;
ArrayAdapter adapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDatabaseHelper = new DatabaseHelper(this);
listView = (ListView) findViewById(R.id.listView);
listItem = new ArrayList<>();
viewData1();
}
private void viewData1() {
Cursor cursor = mDatabaseHelper.viewData();
if (cursor.getCount() == 0) {
Toast.makeText(this, "No data to show", Toast.LENGTH_SHORT).show();
} else {
while (cursor.moveToNext()) {
Log.i("message","Data got");
listItem.add(cursor.getString(1)); // Adding data received to a Listview
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItem);
listView.setAdapter(adapter);
}
}
}
check it out this library
it is very easy to implement
https://github.com/wisdomrider/SqliteClosedHelper
I am currently working on an android quiz application with the questions linking to the database, however, I was be able to create the database created but somehow the values such as list of questions won't be inserted manually. As I have opened the database, it has organized the columns I have wanted but no values will be display such as the 'example question' Have I been missing some line of code?
Many Thanks
public class DatabaseHelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "Questions.db";
public static final String TABLE_NAME = "Questions";
public static final String QUESTION_NUMBER = "Question_Number";
public static final String QUESTION = "Question";
public static final String ANSWER_ONE = "Answer_ONE";
public static final String ANSWER_TWO = "Answer_THREE";
public static final String ANSWER_THREE = "Answer_FOUR";
private SQLiteDatabase db;
public DatabaseHelper(Context context)
{
super(context,DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db)
{
this.db = db;
final String SQL_CREATE_QUESTIONS_TABLE = "CREATE TABLE " +
TABLE_NAME + " ( " +
QUESTION_NUMBER + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
QUESTION + " TEXT, " +
ANSWER_ONE + " TEXT, " +
ANSWER_TWO + " TEXT, " +
ANSWER_THREE + " TEXT " +
")";
db.execSQL(SQL_CREATE_QUESTIONS_TABLE);
fillQuestionTable();
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1)
{
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
onCreate(db);
}
private void fillQuestionTable()
{
Question q1 = new Question(1,"Example Question?","Yes","Sometimes","No");
addQuestion(q1);
}
private void addQuestion (Question question)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(QUESTION_NUMBER, question.getQuestionNum());
cv.put(QUESTION, question.getQuestion());
cv.put(ANSWER_ONE, question.getOption1());
cv.put(ANSWER_TWO, question.getOption2());
cv.put(ANSWER_THREE, question.getOption3());
db.insert(TABLE_NAME,null,cv);
}
}
This is the activity Class
public class MainActivity extends Activity implements View.OnClickListener
{
Button screenOneButton;
Button screenTwoButton;
Button screenThreeButton;
Button quitButton;
DatabaseHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHelper mydb = new DatabaseHelper(this);
}
This is programmed under Intellij software and was able to open the database under DB SQL software FYI!
Many thanks
I am not getting the add string returned back.
The android app takes input as food item and prints its respective calories.
here is the code for creating table:
public class dietclass extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "diet7.db";
public static final String TABLE_NAME = "Cal_val";
public static final String COL1 = "ID";
public static final String COL2 = "ITEM";
public static final String COL3 = "QUANTITY";
public static final String COL4 = "CALORIES";
public dietclass(Context context) {
super(context,DATABASE_NAME,null,1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,ITEM TEXT,QUANTITY VARCHAR,CALORIES INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
onCreate(db);
}
}
And here is the code for retrieving data from my activity which is taking item and calories as input.
public class foodcal extends AppCompatActivity {
EditText item;
EditText quantity;
TextView calories;
Button calculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foodcal);
item = (EditText)findViewById(R.id.etitem);
quantity = (EditText)findViewById(R.id.etquantity);
calories = (TextView)findViewById(R.id.calories);
calculate = (Button)findViewById(R.id.calculate);
calculate.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String itemstr = item.getText().toString();
printDatabase(itemstr);
//String dbstring = dietclass.databaseToString(itemstr);
//calories.setText(String.valueOf(dbstring));
}
});
}
public void printDatabase(String item){
String dbstring = dietclass.databaseToString(this,item);
//String label;
//label = dbstring + "calories";
calories.setText(String.valueOf(dbstring));
}
private static class dietclass extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/com.example.janhvik.dietapp/databases/";
private static String DB_NAME = "diet7.db";
private static String TABLE_NAME = "Cal_val";
private static SQLiteDatabase myDataBase;
private Context myContext;
public dietclass(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
private static String databaseToString(Context ctx, String item_name) {
String myDbPath;
int cal = 0 ;
String add="";
myDbPath = DB_PATH+DB_NAME;
myDataBase = SQLiteDatabase.openOrCreateDatabase(myDbPath, null);
String query = "SELECT * FROM "+TABLE_NAME+" WHERE ITEM='"+item_name+"'";
Cursor c = myDataBase.rawQuery(query,null);
if(c!= null && c.moveToFirst()){
add = c.getString(c.getColumnIndex("CALORIES"));
c.close();
}
add = add + " calories";
//Toast.makeText(ctx,add, Toast.LENGTH_LONG).show();
return add;
}
I am not getting any error but the code is not taking the value from the select query, can anyone help in this.
I think you've got rather mixed up and complicated matters by appearing to use multiple database helpers/methods to open the same database when you only need to use the database helper. I'm unsure what the exact issue was, there was insufficient code to build an exact replica.
Instead a created simplified working code.
Here's a rewrite/simplification based upon your code :-
First ONE databasehelper class namely dietclass :-
public class dietclass extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "diet7.db";
public static final String TABLE_NAME = "Cal_val";
public static final String COL1 = "ID";
public static final String COL2 = "ITEM";
public static final String COL3 = "QUANTITY";
public static final String COL4 = "CALORIES";
//private static String DB_PATH = "/data/data/com.example.janhvik.dietapp/databases/";
//private static String DB_NAME = "diet7.db";
SQLiteDatabase myDataBase;
private Context myContext;
public dietclass(Context context) {
super(context,DATABASE_NAME,null,1);
myDataBase = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,ITEM TEXT,QUANTITY VARCHAR,CALORIES INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
onCreate(db);
}
public long insertCal_ValEntry(String item, String quantity, int calories) {
ContentValues cv = new ContentValues();
cv.put(COL2,item);
cv.put(COL3,quantity);
cv.put(COL4,calories);
return myDataBase.insert(TABLE_NAME,null,cv);
}
public String databaseToString(String item_name) {
//String myDbPath;
int cal = 0 ;
String add="";
//myDbPath = DB_PATH+DB_NAME;
//myDataBase = SQLiteDatabase.openOrCreateDatabase(myDbPath, null);
String query = "SELECT * FROM "+TABLE_NAME+" WHERE ITEM='"+item_name+"'";
Cursor c = myDataBase.rawQuery(query,null);
if(c.moveToFirst()){
add = c.getString(c.getColumnIndex("CALORIES"));
c.close();
}
add = add + " calories";
//Toast.makeText(ctx,add, Toast.LENGTH_LONG).show();
return add;
}
}
Notes
For testing purposes, method insertCal_ValEntry has been added.
Done away with any attempt to open Database rather this is done by the helper.
The check to see if the cursor is null has been removed, it is basically useless as SQLite will not return a null, it will always return a cursor, which may be empty. the Cursor move??? methods, such as moveToFirst return false if the move cannot be made.
Context isn't required by the databaseToString method so removed it.
databaseToString method made to be an instance method rather than class method (i.e not static) and made it public.
The activity in this case I've used MainActivity
public class MainActivity extends AppCompatActivity {
EditText item;
EditText quantity;
TextView calories;
Button calculate;
dietclass dbhelper; //<<<< we want an instance of the database helper
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foodcal);
item = (EditText)findViewById(R.id.etitem);
quantity = (EditText)findViewById(R.id.etquantity);
calories = (TextView)findViewById(R.id.calories);
calculate = (Button)findViewById(R.id.calculate);
dbhelper = new dietclass(this); //<<<< get the instance of the database helper
dbhelper.insertCal_ValEntry("Porridge", "100g",5000); //<<<< For testing
dbhelper.insertCal_ValEntry("Cake","500g", 20000); //<<<< For testing
calculate.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String itemstr = item.getText().toString();
printDatabase(itemstr);
//String dbstring = dietclass.databaseToString(itemstr);
//calories.setText(String.valueOf(dbstring));
}
});
}
public void printDatabase(String item){
String dbstring = dbhelper.databaseToString(item); //<<<<
//String label;wr
//label = dbstring + "calories";
calories.setText(String.valueOf(dbstring));
}
}
Notes
The principle used above could be used in any activity. That is get an instance of the database helper and then invoked methods within the helper to get/add/alter data in the database.
Results from the above:-
1) When App is started:-
2) Clicking without input (or inputting item not in table) :-
3) Clicking after inputting valid item :-
Additional Info
If you really want to get the database path the following is less prone to errors:-
String databasepath = getDatabasePath(dietclass.DATABASE_NAME).getPath();
((TextView) findViewById(R.id.dbpath)).setText(databasepath);
With the dbpath TextView (note run on 7.0.0 device):-
On a 4.1.1 device :-
I created an SQLite Database in my app, and I insert the data into it. And now I want to retrieve data from it but I want just insert one data and retrieve it then display it into a TextView.
public class Db_sqlit extends SQLiteOpenHelper{
String TABLE_NAME = "BallsTable";
public final static String name = "db_data";
public Db_sqlit(Context context) {
super(context, name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+TABLE_NAME+" (id INTEGER PRIMARY KEY AUTOINCREMENT, ball TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String balls){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("ball",balls);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1){
return false;
}
else
return true;
}
public void list_balls(TextView textView) {
Cursor res = this.getReadableDatabase().rawQuery("select ball from "+TABLE_NAME+"",null);
textView.setText("");
while (res.moveToNext()){
textView.append(res.getString(1));
}
}
}
Here is an example of how I achieved this.
In this example I will store, retrieve, update and delete a students name and age.
First create a class, I called mine
DBManager.java
public class DBManager {
private Context context;
private SQLiteDatabase database;
private SQLiteHelper dbHelper;
public DBManager(Context c) {
this.context = c;
}
public DBManager open() throws SQLException {
this.dbHelper = new SQLiteHelper(this.context);
this.database = this.dbHelper.getWritableDatabase();
return this;
}
public void close() {
this.dbHelper.close();
}
public void insert(String name, String desc) {
ContentValues contentValue = new ContentValues();
contentValue.put(SQLiteHelper.NAME, name);
contentValue.put(SQLiteHelper.AGE, desc);
this.database.insert(SQLiteHelper.TABLE_NAME_STUDENT, null, contentValue);
}
public Cursor fetch() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_STUDENT, new String[]{SQLiteHelper._ID, SQLiteHelper.NAME, SQLiteHelper.AGE}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public int update(long _id, String name, String desc) {
ContentValues contentValues = new ContentValues();
contentValues.put(SQLiteHelper.NAME, name);
contentValues.put(SQLiteHelper.AGE, desc);
return this.database.update(SQLiteHelper.TABLE_NAME_STUDENT, contentValues, "_id = " + _id, null);
}
public void delete(long _id) {
this.database.delete(SQLiteHelper.TABLE_NAME_STUDENT, "_id=" + _id, null);
}
}
Then create a SQLiteOpenHelper I called mine
SQLiteHelper.java
public class SQLiteHelper extends SQLiteOpenHelper {
public static final String AGE = "age";
private static final String CREATE_TABLE_STUDENT = " create table STUDENTS ( _id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL , age TEXT );";
private static final String DB_NAME = "STUDENTS.DB";
private static final int DB_VERSION = 1;
public static final String NAME = "name";
public static final String TABLE_NAME_STUDENT = "STUDENTS";
public static final String _ID = "_id";
public SQLiteHelper(Context context) {
super(context, DB_NAME, null, 1);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_STUDENT);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS STUDENTS");
onCreate(db);
}
}
TO ADD:
In this example I take the text from EditText and when the button is clicked I check if the EditText is empty or not. If it is not empty and the student doesn't already exist I insert the students name and age into the database. I display a Toast, letting the user know of the status:
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (edtName.getText().toString().trim().length() == 0) {
Toast.makeText(getApplicationContext(), "Please provide your students name", Toast.LENGTH_SHORT).show();
} else{
try {
if (edtAge.getText().toString().trim().length() != 0) {
String name = edtName.getText().toString().trim();
String age = edtAge.getText().toString().trim();
String query = "Select * From STUDENTS where name = '"+name+"'";
if(dbManager.fetch().getCount()>0){
Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
}else{
dbManager.insert(name, age);
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "please provide student age!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
TO UPDATE:
Here I take the Text in EditText and update the student when the button is clicked. You can also place the following in a try/catch to make sure it is updated successfully.
btnupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = nameText.getText().toString();
String age = ageText.getText().toString();
dbManager.update(_id, name, age);
Toast.makeText(getApplicationContext(), "Updated successfully!", Toast.LENGTH_SHORT).show();
}
});
TO DELETE:
dbManager.delete(_id);
Toast.makeText(getApplicationContext(), "Deleted successfully!", Toast.LENGTH_SHORT).show();
TO GET:
Here I get the name of the student and display it in a TextView
DBManager dbManager = new DBManager(getActivity());
dbManager.open();
Cursor cursor = dbManager.fetch();
cursor.moveToFirst();
final TextView studentName = (TextView) getActivity().findViewById(R.id.nameOfStudent);
studentName.settext(cursor.getString(0));
Then I have implement the code in main java class where I want to show using cursor.moveToNext()
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor result = databaseSQLite2.searchData(searchET.getText().toString());
while (result.moveToNext()){
searchresultTV.setText(result.getString(2));
}
}
});
For fetching data from sqlite I have done this method in DatabaseHelper class
public Cursor searchData(String id){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
//String qry = "SELECT * FROM "+TABLE_NAME+" WHERE ID="+id;
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE ID="+id,null);
return cursor;
}
I am making a small app and therefore i need to use a small SQLite-database.
Please help me, i dont know how to fix this error:
At the line "SQLiteDatabase db = this.getReadableDatabase();" in the database
, (Main: int teams = db.countAllTeams())
Error: W/System.errīš Invalid int: ""
Database:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "database";
private static final String TABLE_TEAM = "team";
private static final String KEY_TEAM_FULLNAME = "full_name";
private static final String KEY_TEAM_SHORTNAME = "short_name";
private static final String KEY_TEAM_STADIUM = "stadium";
private static final String KEY_TEAM_LOGO = "logo";
private static final String CREATE_TABLE_TEAM = "CREATE TABLE "
+ TABLE_TEAM + "(" + KEY_TEAM_FULLNAME + " TEXT PRIMARY KEY," +
KEY_TEAM_SHORTNAME + " TEXT," +
KEY_TEAM_STADIUM + " TEXT," +
KEY_TEAM_LOGO + " INTEGER" + ")";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_TEAM);
}
#Override
public void onUpgrade(SQLiteDatabase db, int old, int neW) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEAM);
onCreate(db);
}
public void closeDB() {
SQLiteDatabase db = this.getReadableDatabase();
if (db != null && db.isOpen()) db.close();
}
public long createTeam(Team team) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TEAM_FULLNAME, team.getFullName());
values.put(KEY_TEAM_SHORTNAME, team.getShortName());
values.put(KEY_TEAM_LOGO, team.getLogo());
values.put(KEY_TEAM_STADIUM, team.getStadium());
return db.insert(TABLE_TEAM, null, values);
}
public int countAllTeams(){
SQLiteDatabase db = this.getReadableDatabase();
List<Team> teams = new ArrayList<Team>();
return Integer.getInteger(db.compileStatement("SELECT COUNT(*) FROM " + TABLE_TEAM).simpleQueryForString());
}
}
Main
DatabaseHelper db;
TextView tvText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_home);
tvText = (TextView)findViewById(R.id.tvText);
String text = "";
db = new DatabaseHelper(getApplicationContext());
int teams = db.countAllTeams();
tvText.setText(teams);
}
}
Integer.getInteger does not convert a string to an integer.
The easiest way to get a single number from a query is to use DatabaseUtils:
long count = DatabaseUtils.longForQuery(db,
"SELECT COUNT(*) FROM " + TABLE_TEAM, null);
But to get the number of rows in the table, there's an even simpler function:
long count = DatabaseUtils.queryNumEntries(db, TABLE_TEAM);
Furthermore, when you give an integer to TextView.setText, it expects a resource ID.
You have to convert your count into a string manually:
tvText.setText(Integer.toString(teams));
I'd use rawQuery() instead of simpleQueryForString():
public int countAllTeams(){
SQLiteDatabase db = this.getReadableDatabase();
List<Team> teams = new ArrayList<Team>();
Cursor c = db.rawQuery("SELECT COUNT(*) FROM " + TABLE_TEAM, new String[]{});
c.moveToFirst();
return c.getInt(0);
}
.setText doesn't take in integers directly, instead try:
tvText.setText(String.valueOf(teams));
Integer value in TextView