In my app i am storing data to SQLite, and now i am trying to fetch that data from SQLite to activity.
as per requirement i just have to store single data at a time and my table will contain only single data row not more than one row.
so I want if table has data row then fetch data and show in form in onCreate(..) of LoginActivity.java
Getting:
The method SelectData(String) in the type myDBClass is not applicable for the arguments ()
myDBClass.java:
// Select Data
public String[] SelectData(String strOperatorID) {
// TODO Auto-generated method stub
try {
String arrData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
Cursor cursor = db.query(TABLE_NAME, new String[] { "*" },
"OperatorID=?",
new String[] { String.valueOf(strOperatorID) }, null, null, null, null);
if(cursor != null)
{
if (cursor.moveToFirst()) {
arrData = new String[cursor.getColumnCount()];
arrData[0] = cursor.getString(0); // DeviceID
arrData[1] = cursor.getString(1); // EmailID
arrData[2] = cursor.getString(2); // Event
arrData[3] = cursor.getString(3); // Operator
arrData[4] = cursor.getString(4); // EventOperator
}
}
cursor.close();
db.close();
return arrData;
} catch (Exception e) {
return null;
}
}
LoginActivity.java:-
public class LoginActivity extends Activity {
.................
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_login);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnCamera = (Button) findViewById(R.id.btnCamera);
btnGallery = (Button) findViewById(R.id.btnGallery);
txtDeviceID = (TextView) findViewById(R.id.txtDeviceID);
txtEmailID = (TextView) findViewById(R.id.txtEmailID);
txtEvent = (TextView) findViewById(R.id.txtEvent);
txtOperative = (TextView) findViewById(R.id.txtOperative);
txtEventOperator = (TextView) findViewById(R.id.txtEventOperator);
Intent intent = getIntent();
deviceID = intent.getStringExtra("deviceID");
emailID = intent.getStringExtra("emailID");
event = intent.getStringExtra("name");
operative = intent.getStringExtra("firstName");
txtDeviceID.setText(deviceID);
txtEmailID.setText(emailID);
txtEvent.setText(event);
txtOperative.setText(operative);
txtEventOperator.setText(event + " " + operative);
strEvent = txtEvent.getText().toString();
strOperative = txtOperative.getText().toString();
// Dialog
final AlertDialog.Builder adb = new AlertDialog.Builder(this);
AlertDialog ad = adb.create();
// new Class DB
final myDBClass myDb = new myDBClass(this);
// Save Data
long saveStatus = myDb.InsertData(
txtDeviceID.getText().toString(),
txtEmailID.getText().toString(),
txtEvent.getText().toString(),
txtOperative.getText().toString(),
txtEventOperator.getText().toString()
);
if(saveStatus <= 0)
{
ad.setMessage("Error!! ");
ad.show();
return;
}
// Show Data
String arrData[] = myDb.SelectData();
if(arrData != null)
{
txtDeviceID.setText(arrData[1]);
txtEmailID.setText(arrData[2]);
txtEvent.setText(arrData[3]);
txtOperative.setText(arrData[4]);
txtEventOperator.setText(arrData[5]);
}
if(txtEvent.getText().toString().equals("") && txtOperative.getText().toString().equals(""))
{
Intent intentCall = new Intent(LoginActivity.this, LicenseListActivity.class);
startActivity(intentCall);
}
}
From the op requirement..
change your method like this..
public String[] SelectData() {
// TODO Auto-generated method stub
try {
String arrData[] = new String[5];
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
Cursor cursor = db.query(TABLE_NAME, null, null, null, null,
null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
arrData[0] = cursor.getString(0); // DeviceID
arrData[1] = cursor.getString(1); // EmailID
arrData[2] = cursor.getString(2); // Event
arrData[3] = cursor.getString(3); // Operator
arrData[4] = cursor.getString(4); // EventOperator
}
}
cursor.close();
db.close();
return arrData;
} catch (Exception e) {
return null;
}
}
Your SelectData method takes a String argument (strOperatorID) but you are calling it with no argument, so obviously it cannot be found.
By the way you should respect Java naming conventions for your methods (i.e. not starting with upper case character)
public String[] SelectData() {
// TODO Auto-generated method stub
try {
String arrData[] = new String[5];
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
Cursor cursor = db.query(TABLE_NAME, null, null, null, null,
null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do{
arrData[0] = cursor.getString(0); // DeviceID
arrData[1] = cursor.getString(1); // EmailID
arrData[2] = cursor.getString(2); // Event
arrData[3] = cursor.getString(3); // Operator
arrData[4] = cursor.getString(4); // EventOperator
} while (cur.moveToNext());
}
}
return arrData;
} catch (Exception e) {
return null;
}finally{
cursor.close();
db.close();
}
Related
public class SignIn extends Activity implements OnClickListener {
Button SignInbtn;
EditText Email,Password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in_screen);
Email = (EditText) findViewById(R.id.etEmail);
Password = (EditText) findViewById(R.id.etPass);
SignInbtn = (Button) findViewById(R.id.btnSignIn);
SignInbtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId())
{
case R.id.btnSignIn:
boolean didItWork = true;
try{
String email = Email.getText().toString();
String password = Password.getText().toString();
PackageITDB SignIn = new PackageITDB(this);
SignIn.open();
String verifyEmail = SignIn.verifyEmail(email);
String verifyPassword = SignIn.verifyPassword(password);
SignIn.close();
if(verifyEmail == email && verifyPassword == password){
Intent intent = new Intent(SignIn.this,UpdateProfile.class);
startActivity(intent);
}
else{
Intent intent = new Intent(SignIn.this,SQLiteExample.class);
startActivity(intent);
}
}catch (Exception e){
didItWork = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Dang it!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}finally{
if(didItWork){
Dialog d = new Dialog(this);
d.setTitle("Heck Yea!");
TextView tv = new TextView(this);
tv.setText("Success");
d.setContentView(tv);
d.show();
}
}
break;
}
}
This is my activity class, it is suppose to get an email and a password, den will authenticate with the sqldatabase and then go to the updateprofile class, but I do not know why when I enter the email and password that is in the database, it still goes to the SQLiteExample class.
public String verifyEmail(String email) throws SQLException {
// TODO Auto-generated method stub
String [] columns = new String[]{ KEY_ROWID, KEY_EMAIL, KEY_USERNAME, KEY_PASSWORD};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String results;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
results = c.getString(1);
if (results == email)
return results;
}
return null;
}
public String verifyPassword(String password) throws SQLException {
// TODO Auto-generated method stub
String [] columns = new String[]{ KEY_ROWID, KEY_EMAIL, KEY_USERNAME, KEY_PASSWORD};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String results;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
results = c.getString(3);
if (results == password)
return results;
}
return null;
}
This is my code for the database class.
public boolean verifyEmail(String email) throws SQLException {
...
results = c.getString(1);
if (results != null && results.equals(email))
return true;
}
return false;
}
public boolean verifyPassword(String password) throws SQLException {
....
results = c.getString(3);
if (results != null && results.equals(password))
return true;
}
return false;
}
public void onClick(View v) {
...
SignIn.open();
boolean verifyEmail = SignIn.verifyEmail(email);
boolean verifyPassword = SignIn.verifyPassword(password);
SignIn.close();
if(verifyEmail && verifyPassword) {
Intent intent = new Intent(SignIn.this,UpdateProfile.class);
startActivity(intent);
}
...
By the way, are you sure you close your connection properly?
You are comparing strings in-correctly. You have to compare it this way
if( verifyEmail.equals(email) && verifyPassword.equals(password) )
EDIT:
You are pretty new to java? You are doing a wrong string comparison everywhere.
In methods verifyPassword and verifyEmail you are comparing strings using == while you should do it via equals method.
Change if (results == email) to if (results.equals(email)) and if(results == password) to if(results.equals(password). Also both methods returns null when no match found so it would obviously make a null pointer exception in onClick method. You should consider returning a boolean and based on the boolean you should start the appropiate Intent :-/
I'm currently developing an app. What it does, the user would input some sentences and then the app will get the ambiguous word and then display it meaning. In my table I have fields like _id, word, meaning, definition_number.
Sample data:
_id word meaning definition_number
1 Break to pause from something 1
2 Break to cut into pieces 2
If the user would input: My break was very fast.
The intended output would be:
Ambiguous word: Break
Meaning: To pause from something
I want to display the it randomly. This is a snippet of code from my DBHelper.class:
public Cursor getAllWords()
{
Cursor localCursor =
//this.myDataBase.query(DB_TABLE, new String[] {
// KEY_ID, KEY_WORD, KEY_MEANING }, null, null, null, null, null);//"RANDOM()");
//this.myDataBase.query(DB_TABLE, new String[] {
// KEY_ID, KEY_WORD, KEY_MEANING }, null, null, null, null, "RANDOM()", " 1");
this.myDataBase.query(DB_TABLE, new String[] {
KEY_ID, KEY_WORD, KEY_MEANING },
null, null, null, null, "RANDOM()");
if (localCursor != null){
localCursor.moveToFirst();
}
return localCursor;
}
MainActivity.class:
ArrayList<String> colWords = new ArrayList<String>();
ArrayList<String> colMeanings = new ArrayList<String>();
String[] words;
String[] meanings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initControls();
}
private void initControls() {
// TODO Auto-generated method stub
text = (EditText) findViewById (R.id.editText1);
view = (TextView) findViewById (R.id.textView1);
clear = (Button) findViewById (R.id.button2);
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
text.setText("");
view.setText("");
}
});
connectDB();
ok = (Button) findViewById (R.id.button1);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Log.d(strWord, strWord);
strWord = text.getText().toString();
if(strWord.isEmpty()){
Toast.makeText(MainActivity.this, "Please input some data", Toast.LENGTH_SHORT).show();
} else {
checkAmbiguousWord();
}
}
});
}
private void connectDB(){
dbHelper = new DBHelper(MainActivity.this);
try {
dbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
dbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
cursor = dbHelper.getAllWords();
/*strWord = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_WORD))
+ cursor.getString(cursor.getColumnIndex(DBHelper.KEY_MEANING)); */
colWords.clear();///added code
colMeanings.clear();///added code
/*
for(cursor.moveToFirst(); cursor.moveToNext(); cursor.isAfterLast()) {
colWords.add(cursor.getString(1));
colMeanings.add(cursor.getString(2));
String records = cursor.getString(0);
Log.d("Records", records);
} */
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
colWords.add(cursor.getString(1));
colMeanings.add(cursor.getString(2));
String records = cursor.getString(0);
Log.d("Records", records);
} while (cursor.moveToNext());
}
}
}
private void checkAmbiguousWord(){
final String textToCheck = text.getText().toString();
List<Integer> ambiguousIndexes = findAmbiguousWordIndexes(textToCheck);
view.setText(!ambiguousIndexes.isEmpty() ?
ambigousIndexesToMessage(ambiguousIndexes) : "No ambiguous word/s found.");
}
/**
* #param text checked for ambiguous words
* #return the list of indexes of the ambiguous words in the {#code words} array
*/
private List<Integer> findAmbiguousWordIndexes(String text) {
final String lowerCasedText = text.toLowerCase();
final List<Integer> ambiguousWordIndexList = new ArrayList<Integer>();
words = (String[]) colWords.toArray(new String[colWords.size()]);
meanings = (String[]) colMeanings.toArray(new String[colMeanings.size()]);
for (int i = 0; i < words.length; i++) {
if (lowerCasedText.contains(words[i].toLowerCase())) {
ambiguousWordIndexList.add(i);
}
}
return ambiguousWordIndexList;
}
public String ambigousIndexesToMessage(List<Integer> ambiguousIndexes) {
// create the text using the indexes
// this is an example implementation
StringBuilder sb = new StringBuilder();
for (Integer index : ambiguousIndexes) {
sb.append("Ambiguous words: ");
sb.append(words[index] + "\nMeaning: " + meanings[index] + "\n");
sb.append("");
}
return sb.toString();
}
But all it does is displaying the two records. Both id 1 and id 2. I just want to display only one record randomly. I really need help regarding this. Any ideas? I would gladly appreciate it.
You have RANDOM() ordering but you also need to add a LIMIT 1 to only return one result row. There's an overload of SQLiteDatabase.query() that takes in a limit parameter:
this.myDataBase.query(DB_TABLE, new String[] {
KEY_ID, KEY_WORD, KEY_MEANING },
null, null, null, null, "RANDOM()", "1");
i have developed an app for 'bank simulation' which uses sqlite to create databases...
when i run the app on my mobile it stops unexpectedly....do i need to install any server to run sqlite based apps on mobile?
Thanks in advance!
DbHelper.java
private static final String DATABASE_NAME = "saket.db";
private static final int DATABASE_VERSION = 1;
public static final String SUBH_TABLE_NAME = "login";
public static final String SUBH_TABLE_DATA = "TBL_Transaction";
public static final String KEY_ROWID = "_id";
private static final String SUBH_TABLE_CREATE =
"CREATE TABLE " + SUBH_TABLE_NAME + "(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+
"username TEXT NOT NULL, password TEXT NOT NULL, email TEXT NOT NULL, balance INTEGER);";
private static final String SUBH_TABLE_DATA_CREATE =
"CREATE TABLE " + SUBH_TABLE_DATA + "(" +
"trans_id INTEGER PRIMARY KEY AUTOINCREMENT, "+
"user_id INTEGER, " +
"trans TEXT NOT NULL);";
private static final String SAKET_DB_ADMIN = "INSERT INTO "+ SUBH_TABLE_NAME +" values(1, admin, password, admin#gmail.com);";
//private static final String SAKET_DB_ADMIN_Trans = "INSERT INTO "+ SUBH_TABLE_DATA +" values(1, asdf);";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
System.out.println("In constructor");
}
/* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
*/
#Override
public void onCreate(SQLiteDatabase db) {
try{
//Create Database
db.execSQL(SUBH_TABLE_CREATE);
//create transaction account
db.execSQL(SUBH_TABLE_DATA_CREATE);
//create admin account
db.execSQL(SAKET_DB_ADMIN);
//db.execSQL(SAKET_DB_ADMIN_Trans);
System.out.println("In onCreate");
}catch(Exception e){
e.printStackTrace();
}
}
DatabaseActivity.java
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mNewUser = (Button) findViewById(R.id.buttonNewUser);
mNewUser.setOnClickListener(this);
mLogin = (Button) findViewById(R.id.buttonLogin);
mLogin.setOnClickListener(this);
mShowAll = (Button) findViewById(R.id.buttonShowAll);
mShowAll.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonLogin:
mUsername = (EditText) findViewById(R.id.editUsername);
mPassword = (EditText) findViewById(R.id.editPassword);
String uname = mUsername.getText().toString();
String pass = mPassword.getText().toString();
if (uname.equals("") || uname == null) {
Toast.makeText(getApplicationContext(), "Username Empty",
Toast.LENGTH_SHORT).show();
} else if (pass.equals("") || pass == null) {
Toast.makeText(getApplicationContext(), "Password Empty",
Toast.LENGTH_SHORT).show();
} else {
boolean validLogin = false;
try {
validLogin = validateLogin(uname, pass,
DatabaseActivity.this);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (validLogin) {
System.out.println("In Valid");
Intent i_login = new Intent(DatabaseActivity.this,
UserLoggedInPage.class);
try {
id = getID(uname, pass, DatabaseActivity.this);
Ubal = getBAL(uname, pass, DatabaseActivity.this);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d(TAG, "putting the extra " + id);
i_login.putExtra("key", id);
i_login.putExtra("bkey", Ubal);
startActivity(i_login);
finish();
}
}
break;
case R.id.buttonNewUser:
Intent i = new Intent(DatabaseActivity.this, NewUserActivity.class);
startActivity(i);
finish();
break;
case R.id.buttonShowAll:
Intent i_admin = new Intent(DatabaseActivity.this, AdminPage.class);
startActivity(i_admin);
finish();
break;
}
}
public boolean validateLogin(String uname, String pass, Context context)
throws Exception {
myDb = new DbHelper(context);
SQLiteDatabase db = myDb.getReadableDatabase();
// SELECT
String[] columns = { "_id" };
// WHERE clause
String selection = "username=? AND password=?";
// WHERE clause arguments
String[] selectionArgs = { uname, pass };
Cursor cursor = null;
try {
// SELECT _id FROM login WHERE username = uname AND password=pass
cursor = db.query(DbHelper.SUBH_TABLE_NAME, columns, selection,
selectionArgs, null, null, null);
startManagingCursor(cursor);
} catch (Exception e) {
e.printStackTrace();
}
int numberOfRows = cursor.getCount();
if (numberOfRows <= 0) {
Toast.makeText(getApplicationContext(),
"Login Failed..\nTry Again", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
// get rowid
// public int getID(String uname, String pass, Context context)
// throws Exception {
//
// myDb = new DbHelper(context);
// SQLiteDatabase db = myDb.getReadableDatabase();
// cursor = db.rawQuery("select * from " + DbHelper.SUBH_TABLE_NAME +
// " where username = " + uname + "&" + "password = " + pass + ";)", null);
// if (cursor != null) {
// if(cursor.moveToFirst()){
// int id = cursor.getInt(cursor.getColumnIndex(DbHelper.KEY_ROWID));
// }
//
// }
//
// return id;
//
// }
public String getID(String uname, String pass, Context context) {
try {
String idddd = null;
SQLiteDatabase db = myDb.getReadableDatabase();
String[] columns = { "_id" };
// WHERE clause
String selection = "username=? AND password=?";
// WHERE clause arguments
String[] selectionArgs = { uname, pass };
Cursor cursor = db.query(DbHelper.SUBH_TABLE_NAME, columns,
selection, selectionArgs, null, null, null);
if (cursor != null) {
startManagingCursor(cursor);
while (cursor.moveToNext()) {
idddd = cursor.getString(0);
}
return idddd;
}
System.out.println("Cursor NuLL");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private String getBAL(String uname, String pass,
DatabaseActivity databaseActivity) {
try {
String ballll = null;
SQLiteDatabase db = myDb.getReadableDatabase();
String[] columns = { "balance" };
// WHERE clause
String selection = "username=? AND password=?";
// WHERE clause arguments
String[] selectionArgs = { uname, pass };
Cursor cursor = db.query(DbHelper.SUBH_TABLE_NAME, columns,
selection, selectionArgs, null, null, null);
if (cursor != null) {
startManagingCursor(cursor);
while (cursor.moveToNext()) {
ballll = cursor.getString(0);
}
return ballll;
}
System.out.println("Cursor NuLL");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onDestroy() {
super.onDestroy();
if (myDb != null && cursor != null ) {
cursor.close();
myDb.close();
}
}
}
So I have a ListView on which I click to start new Activity called MerchantView.
Between the activities I am passing the uid which is a unique identifier of a merchant.
Im then extracting merchant data from DB and want to view this data in this view.
Everything works (while debugging i can see that data is taken from DB and passed properly to setText methods) but the data does not show, am I doing this right?
public class MerchantView extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.merchant);
String desc = "";
String name = "";
Bundle extras = getIntent().getExtras();
String uid = "0";
if(extras !=null) {
uid = extras.getString("uid");
}
// get merchant from database
if(Integer.valueOf(uid) > 0){
Cursor c = Utilities.db.query(mydb.TABLE_MERCHANT,
null,
"uid=?", new String[] {uid}, null, null, null);
if(c.moveToFirst() != false){
name = c.getString(c.getColumnIndex(MerchantsColumns.COLname));
desc = c.getString(c.getColumnIndex(MerchantsColumns.COLdesc));
}
// set values to UI
TextView descUI = (TextView) findViewById(R.id.merchantDescription);
descUI.setText(desc);
TextView nameUI = (TextView) findViewById(R.id.merchantName);
nameUI.setText(name);
}
else{
}
Button buttonMerchants = (Button) findViewById(R.id.buttonMerchants);
buttonMerchants.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
}
Data was set properly. The problem was in layout. The header (LinearLayout) at the top had two buttons and it was set to android:layout_height="fill_parent" which was taking whole space. After fixing that, data is showing properly.
Try Below code hope it helps
SQLiteDatabase myDB = this.openOrCreateDatabase("databasename.db", SQLiteDatabase.OPEN_READWRITE, null);
try{
Cursor c = myDB.rawQuery("select name, desc from abctable where uid="+uid, null);
int Column1 = c.getColumnIndex("name");
int Column2 = c.getColumnIndex("desc");
// Check if our result was valid.
c.moveToFirst();
if (c != null) {
int i = 0;
// Loop through all Results
do {
i++;
String name = c.getString(Column1);
String desc = c.getString(Column2);
TextView descUI = (TextView) findViewById(R.id.merchantDescription);
descUI.setText(desc);
TextView nameUI = (TextView) findViewById(R.id.merchantName);
nameUI.setText(name);
} while (c.moveToNext());
}
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
if (myDB != null)
myDB.close();
}
I have a page with a number edit texts, i want to populate these with columns of a raw with the row id equaling a textview value... this is what i have so far in the edit text page.
public class CBCreate extends Activity {
EditText EditRecipe,EditRecipe2,EditRecipe3;
Button Rname;
CBDataBaseHelper entry;
TextView RowIDText;
Cursor c;
String name;
String category;
String description;
//final String SQL_STATEMENT = "SELECT Recipe_Name, Recipe_Category, Recipe_Description FROM RecipeData WHERE _id = " + RowIDText ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create); // sets the content view to main
EditRecipe = (EditText) findViewById(R.id.editText1);
EditRecipe2 = (EditText) findViewById(R.id.editText2);
EditRecipe3 = (EditText) findViewById(R.id.editText3);
RowIDText = (TextView) findViewById(R.id.RowID);
Rname = (Button) findViewById(R.id.RecipeName);
String RowID;
try{
Bundle extras = getIntent().getExtras();
if (extras != null) {
RowID = extras.getString("SELECTED");
RowIDText.setText(RowID);
}
if (RowIDText != null){
entry = new CBDataBaseHelper(this);
String s = RowIDText.getText().toString();
int ID = Integer.parseInt(s);
entry.open();
Cursor cursor = entry.fetchRow(ID);
if (cursor.moveToFirst()){ // data?
name = cursor.getString(cursor.getColumnIndex(CBDataBaseHelper.KEY_NAME));
}
entry.close();
EditRecipe.setText(name);
EditRecipe2.setText(category);
EditRecipe3.setText(description);
}
}catch (Exception e){
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("darn");
TextView tv = new TextView(this);
tv.setText(name);
d.setContentView(tv);
d.show();
}
}
public void doIt(View view) {
String Name = EditRecipe.getText().toString();
String description = EditRecipe.getText().toString();
String category = EditRecipe.getText().toString();
entry = new CBDataBaseHelper(CBCreate.this);
entry.open();
entry.createEntry(Name, description, category);
entry.close();
EditRecipe.setText("");
EditRecipe2.setText("");
EditRecipe3.setText("");
}
public void goBack(View view){
Intent myIntent = new Intent(this, CBFilter.class);
startActivity(myIntent);
}
}
and then this is what i have within the database helper class... i think i want to call this method?
public Cursor fetchRow(long rowId) throws SQLException {
Cursor mCursor = mydatabase.query(true, DATABASE_TABLE, new String[] { KEY_ROWID,
KEY_CATEGORY, KEY_DESCRIPTION }, KEY_ROWID + "="
+ rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
I would use mydatabase.rawquery(QUERY) instead of the cursors query method. Its easier for SQL developers I think. Anyways, once you have your values in the cursor, you can do this
EditRecipe.setText(cursor.getString(0));
EditRecipe2.setText(cursor.getString(1));
Where 0 represents the first column in your returned table. You would put that code after your mCursor.moveToFirst();