i want to retrieve id from database where name = saqib into the EditText(textbox) in android, i have tried different ways but can't achieve my desired output instead of that the given output will be shown every time. output
onButtonClick:
final EditText i=(EditText)findViewById(R.id.id_etxt);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res= mydatabase.fet();
i.setText(res.toString());
}
});
Database.java class
public Cursor fet(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res=db.rawQuery("select ID from record where Name=?",new String[] {"saqib"});
return res;
}
Cursor res = mydatabase.fet();
if (res.getCount() > 0) {
res.moveToFirst();
i.setText(res.getString(0));
} else {
throw new SQLiteException("e");
}
Currently you set the whole Cursor as String in EditText, which is not right way to set ID.
You have to extract the ID from Cursor like below to use it in EditText:
public void onClick(View v) {
Cursor res = mydatabase.fet();
if(res != null && res.moveToFirst()) {
String id = Integer.toString(res.getInt(res.getColumnIndex("ID")));
i.setText(id);
}
}
Related
I'm trying to create something like favorite thing in my app
I have made activity with restaurant which can be set as favorite, I've made imagebutton for making restaurant favorite and it's working, cause I have second activity where list is getting info from database and everything is ok. Titles match, adresses match cities too, so database should match too.
I have problem with changing OnClickListener, I want to use info from database to check if String called "database_name" is matching with any string from database.
There is code for it :
mDbHelper = new FeedReaderDbHelper(getApplicationContext());
final SQLiteDatabase db = mDbHelper.getWritableDatabase();
String[] selection = {FeedReaderContract.FeedEntry.COLUMN_NAME_DATABASE};
favoriteButton = (ImageButton) findViewById(R.id.favoriteRestaurant);
Cursor cursor = db.query(FeedReaderContract.FeedEntry.TABLE_NAME, selection,
null, null, null, null, null);
if(cursor.getCount() != 0) {
cursor.moveToFirst();
do {
if(cursor.getString(0).toLowerCase() == database_name.toLowerCase()){
favoriteButton.setBackground(getResources().getDrawable(R.drawable.favoritet));
isFavorite = 1;
}
} while (cursor.moveToNext());
}
It's changing background of this favorite button to filled heart, at least it's supposed to do so. In default it's not filled.
Then I'm changing onClickListener, code for it looks like this :
if(isFavorite == 0) {
favoriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isntFavorite();
}
});
} else {
favoriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isFavorite();
}
});
}
isFavorite look like this :
private void isFavorite() {
favoriteButton.setBackground(getResources().getDrawable(R.drawable.favoriteu));
String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_DATABASE + " LIKE ?";
mDbHelper = new FeedReaderDbHelper(getApplicationContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
String[] selectionArgs = new String[] { database_name };
db.delete(FeedReaderContract.FeedEntry.TABLE_NAME, selection, selectionArgs);
favoriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isntFavorite();
}
});
}
And code for isntFavorite looks like this:
private void isntFavorite() {
favoriteButton.setBackground(getResources().getDrawable(R.drawable.favoritet));
mDbHelper = new FeedReaderDbHelper(getApplicationContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, restaurantName);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_ADRESS, restaurantAdress);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CITY, restaurantCity);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_DATABASE, database_name);
long newRowId;
newRowId = db.insert(FeedReaderContract.FeedEntry.TABLE_NAME,
null, values);
favoriteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isFavorite();
}
});
}
The thing is that it's always changing onClickListener to isntFavorite and it's not changing image background to filled heart, even if there is matching data in database. I was trying to change matching title from database to title from activity, and I was sure that they're matching cause there was in list title with the same String as title from activity where I was trying to match them.
You don't need to change OnclickListener just create a boolean to save the state:
final boolean state = isFavorite == 0;
favoriteButton.setOnClickListener(new View.OnClickListener() {
boolean mState = state;
#Override
public void onClick(View v) {
if(mState)isntFavorite();
else isFavorite();
mState=!mState;
}
});
private void isFavorite() {
favoriteButton.setBackground(getResources().getDrawable(R.drawable.favoriteu));
String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_DATABASE + " LIKE ?";
mDbHelper = new FeedReaderDbHelper(getApplicationContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
String[] selectionArgs = new String[] { database_name };
db.delete(FeedReaderContract.FeedEntry.TABLE_NAME, selection, selectionArgs);
}
private void isntFavorite() {
favoriteButton.setBackground(getResources().getDrawable(R.drawable.favoritet));
mDbHelper = new FeedReaderDbHelper(getApplicationContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, restaurantName);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_ADRESS, restaurantAdress);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CITY, restaurantCity);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_DATABASE, database_name);
long newRowId;
newRowId = db.insert(FeedReaderContract.FeedEntry.TABLE_NAME,
null, values);
}
how to Display the particular field details in editext by giving id here i write code in database handler but i dont know what to do in MainActivity
i have fields when i gave id and click show button the details in database for that particular id want to be load in edittext
My database Handler class
Try this.
set editText as number only
android:inputType="number|numberDecimal"
public void show()
{
bshow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(uid.getText().toString().equals(""))
return;
int id = Integer.parseInt(uid.getText().toString());
Cursor res=myDB.getData(id);//i got an error Here and i dont know what to do
String NAME = res.getString(res.getColumnIndex("NAME"));
String SURNAME = res.getString(res.getColumnIndex("SURNAME"));
String MARKS = res.getString(res.getColumnIndex("MARKS"));
editname.setText(NAME);
editsurname.setText(SURNAME);
editmark.setText(MARKS);
}
});
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from student_details where id="+id+"", null );
if(res != null && res.moveToFirst()) {
return res;
}
return res;
}
In your activity initialize your Db class.
Now you can get value like below code ; -
Cursor mCur = myDb.getData(some integer value);
Now you can fetch value from cursor by ;-
mCur .getString(mCur .getColumnIndex("column name");
I am completely stuck. been banging my head against a brick wall all day!
I have a class:
public class Main extends Activity.
This has several buttons.
On 2 of the buttons I want to get the result of a boolean function that checks if a database table exists or not so that I can choose the next action.
final Button reminderButton = (Button) findViewById(R.id.reminders);
reminderButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
//This is where I want to get the result from the boolean function
// and then either provide a toast msg OR start a new activity
}
});
Below is the boolean function
public boolean isTableExists(SQLiteDatabase db, String tableName) {
if (tableName == null || db == null || !db.isOpen())
{
return false;
}
Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM sqlite_master WHERE type = ?
AND name = ?",new String[] { "table", tableName });
if (!cursor.moveToFirst())
{
return false;
}
int count = cursor.getInt(0);
cursor.close();
return count > 0;
}
For the life of me I cannot work out the syntax to put in my onclick (View v){}
I had tried
public void onClick(View v)
{
isTableExists(null, null);
}
but I dont think the null,null is correct, but what arguments go in there?
or am I on the wrong track completely?
Thanks for any advice
From your post i understand that you want to check whether Table exists or not.
This code will help you.
public boolean isTableExists(String tableName, boolean openDb) {
if(openDb) {
if(mDatabase == null || !mDatabase.isOpen()) {
mDatabase = getReadableDatabase();
}
if(!mDatabase.isReadOnly()) {
mDatabase.close();
mDatabase = getReadableDatabase();
}
}
Cursor cursor = mDatabase.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+tableName+"'", null);
if(cursor!=null) {
if(cursor.getCount()>0) {
cursor.close();
return true;
}
cursor.close();
}
return false;
}
Based on this boolean value You can do your action.
I have two buttons inside of my application, one for next and one for prev. I want the next button to get the next record inside of my database and display it inside of my view, and the prev button to get the previous record and display it inside of my view. How would I call the next or previous record? I have looked for tutorials and stuff but didn't find any. I anyone has a tutorial please share with me. Thanks for any help. I wish I had some code to provide but I really don't know where to start.
I use an int to pull the record from the dbase.
From my ContactView class
static long record = 1;
public void getData() {
DBase db = new DBase(this);
db.open();
lastRecord = db.lRec();
firstRecord = db.fRec();
rRec = db.getRec(record);
db.close();
}
then my query is from my Dbase class
public String[] getRec(long record) {
record = ContactView.record;
String[] columns = new String[] { KEY_ROWID, KEY_ONE, KEY_TWO,
KEY_THREE, KEY_FOUR, KEY_FIVE, KEY_SIX };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
+ record, null, null, null, null);
if (c != null && c.moveToFirst()) {
String rRec = c.getString(0);
String rOne = c.getString(1);
String rTwo = c.getString(2);
String rThree = c.getString(3);
String rFour = c.getString(4);
String rFive = c.getString(5);
String rSix = c.getString(6);
String[] rData = { rRec, rOne, rTwo, rThree, rFour,
rFive, rSix };
return rData;
}
return null;
}
and the next few are from my ContactView class
my buttons
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bSQLvPrev:
recordMinus();
display();
break;
case R.id.bSQLvNext:
recordPlus();
display();
break;
}
}
and the methods they call
public void display() {
etSQLvRec.setText(rRec[0]);
etSQLvOne.setText(rRec[1]);
etSQLvTwo.setText(rRec[2]);
etSQLvThree.setText(rRec[3]);
etSQLvFour.setText(rRec[4]);
etSQLvFive.setText(rRec[5]);
etSQLvSix.setText(rRec[6]);
}
public void recordPlus() {
record++;
}
public void recordMinus() {
record--;
}
That will get the record from the database based on the "record" variable, and the buttons increment it, or decrement it, it also skips any "empty" records.
EDIT OK, I had changed some stuff around since I lasted used my db, so use the next recordPlus() and recordMinus() code instead
public void recordPlus() {
if (record < lastRecord) {
record++;
} else {
record = firstRecord;
}
getData();
do {
if (record < lastRecord) {
record++;
} else {
record = firstRecord;
}
getData();
} while (rRec == null);
}
public void recordMinus() {
if (record == 1) {
record = lastRecord;
} else {
record--;
}
getData();
do {
if (record == 1) {
record = lastRecord;
} else {
record--;
}
getData();
} while (rRec == null);
}
And you'll need my fRec() and lRec() which find the first and last records in the DB
public long fRec() {
Cursor c = ourDatabase.query(DATABASE_TABLE, new String[] { "min(" +
KEY_ROWID
+ ")" }, null, null, null, null, null);
c.moveToFirst();
long rowID = c.getInt(0);
return rowID;
}
}
public long lRec() {
long lastRec = 0;
String query = "SELECT ROWID from Table order by ROWID DESC limit 1";
Cursor c = ourDatabase.rawQuery(query, null);
if (c != null && c.moveToFirst()) {
lastRec = c.getLong(0);
}
return lastRec;
}
In onCreate(), I define a cursor and move down in the results using a button :
final Cursor cursor = (Cursor) WoordData.fetchset(USERCHOICE);
btnVolgende.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tv.setText(cursor.getString(0));
cursor.moveToNext();
if (cursor.isAfterLast()){
cursor.moveToFirst();
}}});
In a seperate activity (through Preferences) I allow the user to change the value of USERCHOICE.
Question : How to I re-load the cursor with the new query (new value of USERCHOICE) when the user returns to the main activity?
thnx!
Thanks to Christian, I solved it. I'm not sure this is the cleanest solution, though..
I created a boolean called resetneeded.
In the clickbutton code I do :
btnVolgende.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (resetneeded) {
cursor = (Cursor) WoordData.fetchset(kernset);
resetneeded = false;
}
startManagingCursor(cursor);
tvFlitswoord.setText(cursor.getString(0));
cursor.moveToNext();
if (cursor.isAfterLast()){
cursor.moveToFirst();
}}
}
And then, in the onStart(), I set the boolean resetneeded to true.
// EDIT - 2nd Solution
In the end, I decided to use an ArrayList for passing the words to the TextView (and cycling through it with the button). An ArrayList seems easier to handle and less fragile..
The code :
public void onStart(){
super.onStart();
getPrefs();
wordlistarray.clear();
cursor = (Cursor) WoordData.fetchset(kernset);
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
String wordtoadd = cursor.getString(0);
wordlistarray.add(wordtoadd);
cursor.moveToNext();
}
for(int i = 0; i < wordlistarray.size();
i++){ Log.d("word in array", "" + wordlistarray.get(i)); }