I have a sqlite database which I want to query and retrieve some values if they exist, in case they don't exist make a toast.
For this porpoise I have the next code which will call a function to create the cursor and in case this is not empty it will retrieve the information in the edittext otherwise it will make a toast:
private String lookforelementID() {
// TODO Auto-generated method stub
int ElementRequest=0;
ElementRequest = Integer.parseInt(eTElementNumb.getText().toString());
try{
database db = new database(this);
db.open();
String passedReg = getIntent().getStringExtra(MainActivity.ID_STUDY);
String returnedInfo1 = db.elementID(ElementRequest, passedReg, 0);
if (returnedInfo1.matches("")){
Toast.makeText(getApplicationContext(), "No Exist this Element", Toast.LENGTH_SHORT).show();
}else{
eTIDElement.setText(returnedInfo1);
String returnedInfo2 = db.elementID(ElementRequest, passedReg, 2);
eTElementCode.setText(returnedInfo2);
String returnedInfo3 = db.elementID(ElementRequest, passedReg, 3);
eTElementDecription.setText(returnedInfo3);
}
db.close();
}catch(ClassCastException e){
e.printStackTrace();
}
eTElementNumb.setText("");
return null;
}
The function with the cursor is as follows:
public String elementID(int elementRequest, String idStudy, int i) {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWELEMENTID, KEY_STUDYID, KEY_ELEMENTCODE, KEY_ELEMENTNAME};
Cursor c = ourDatabase.query(DATABASE_TABLEELEMENTS, columns, KEY_ELEMENTCODE + "=" + elementRequest + " AND " + KEY_STUDYID + "=" + idStudy, null, null, null, null);
String ElementInformation = null;
if(c != null){
c.moveToFirst();
ElementInformation = c.getString(i);
}
return ElementInformation;
}
Related
After the record iteration, the list key value is mismatching/wrongly shown ! what could be the reason.
Correct data in the database like this is saved (which is correct)
Problem: You can see in this screenshot link, record is a mismatch with columns, e.g the key dayName has wrong value showing , key MenuIcon value is shown on dayName key
the sql lite DAO
/*
* Get the all the exercises by ID asecending order
*/
public LinkedList<ExerciseDetails> getAllExerciseInfo() {
LinkedList<ExerciseDetails> listCompanies = new LinkedList<ExerciseDetails>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_EXERCISE_DETAILS, mAllColumns,
"",
new String[]{}, "order_id", null, "order_id ASC");
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ExerciseDetails company = cursorToExerciseDetails(cursor);
listCompanies.add(company);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listCompanies;
}
Full code of DAO for insertion,create table, list object . Please let me know any code you want to see, i will post
public class ExercisesDAO {
public static final String TAG = "ExercisesDAO";
// Database fields
private SQLiteDatabase mDatabase;
private DBHelper mDbHelper;
private Context mContext;
private String[] mAllColumns = {DBHelper.COLUMN_EX_DETAILS_ID,
DBHelper.COLUMN_ROUTINE_ID,
DBHelper.COLUMN_DAY_ID,
DBHelper.COLUMN_EXERCISE_ID,
DBHelper.COLUMN_REPS,
DBHelper.COLUMN_SETS,
DBHelper.COLUMN_TIME_PERSET,
DBHelper.COLUMN_CALORIE_BURN,
DBHelper.COLUMN_RESTTIME_PERSET,
DBHelper.COLUMN_RESTTIME_POST_SET,
DBHelper.COLUMN_ORDER_ID,
DBHelper.COLUMN_EXERCISE_NAME,
DBHelper.COLUMN_TIPS,
DBHelper.COLUMN_YOUTUBE_URL,
DBHelper.COLUMN_WARNINGS,
DBHelper.COLUMN_DISPLAY_ID,
DBHelper.COLUMN_VISIBILITY,
DBHelper.COLUMN_FOR_DATE,
DBHelper.COLUMN_GIF,
DBHelper.COLUMN_DAYNAME
};
public ExercisesDAO(Context context) {
this.mContext = context;
mDbHelper = new DBHelper(context);
// open the database
try {
open();
} catch (SQLException e) {
Log.e(TAG, "SQLException on openning database " + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDbHelper.getWritableDatabase();
}
public void close() {
mDbHelper.close();
}
public ExerciseDetails createExerciseDetail(String routineId,String dayId,
String exerciseId, String reps,String sets, String timePerset,
String calorieBurn, String resttimePerset, String resttimeAfterex,String order,
String menuName, String tips, String youtubeUrl, String warnings, String displayId,
String visibility, String forDate, String menuIcon, String dayName) {
ExerciseDetails newCompany = null;
try {
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_ROUTINE_ID, routineId);
values.put(DBHelper.COLUMN_DAY_ID, dayId);
values.put(DBHelper.COLUMN_EXERCISE_ID, exerciseId);
values.put(DBHelper.COLUMN_REPS, reps);
values.put(DBHelper.COLUMN_SETS, sets);
values.put(DBHelper.COLUMN_TIME_PERSET, timePerset);
values.put(DBHelper.COLUMN_CALORIE_BURN, calorieBurn);
values.put(DBHelper.COLUMN_RESTTIME_PERSET, resttimePerset);
values.put(DBHelper.COLUMN_RESTTIME_POST_SET, resttimeAfterex);
values.put(DBHelper.COLUMN_ORDER_ID, order);
values.put(DBHelper.COLUMN_EXERCISE_NAME, menuName);
values.put(DBHelper.COLUMN_TIPS, tips);
values.put(DBHelper.COLUMN_YOUTUBE_URL, youtubeUrl);
values.put(DBHelper.COLUMN_WARNINGS, warnings);
values.put(DBHelper.COLUMN_DISPLAY_ID, displayId);
values.put(DBHelper.COLUMN_VISIBILITY, visibility);
values.put(DBHelper.COLUMN_FOR_DATE, forDate);
values.put(DBHelper.COLUMN_GIF, menuIcon);
values.put(DBHelper.COLUMN_DAYNAME, dayName);
long insertId = mDatabase
.insert(DBHelper.TABLE_EXERCISE_DETAILS, null, values);
Cursor cursor = mDatabase.query(DBHelper.TABLE_EXERCISE_DETAILS, mAllColumns,
DBHelper.COLUMN_EX_DETAILS_ID + " = " + insertId, null, null,
null, null);
cursor.moveToFirst();
newCompany = cursorToExerciseDetails(cursor);
cursor.close();
} catch (Exception e) {
Log.e("exception", "exception in CreateFollowing class - " + e);
}
return newCompany;
}
public void executeSqlOnExerciseDetail(String sql) {
mDatabase.execSQL(sql);
}
public Long getTotalCountExerciseDetail() {
return DatabaseUtils.queryNumEntries(mDatabase, DBHelper.TABLE_EXERCISE_DETAILS);
}
/*
* Get the all the exercises by ID asecending order
*/
public LinkedList<ExerciseDetails> getAllExerciseInfo() {
LinkedList<ExerciseDetails> listCompanies = new LinkedList<ExerciseDetails>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_EXERCISE_DETAILS, mAllColumns,
"",
new String[]{}, "order_id", null, "order_id ASC");
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ExerciseDetails company = cursorToExerciseDetails(cursor);
listCompanies.add(company);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listCompanies;
}
/*
* Check whether the exercise data present or not in the db before executing statement
*/
public boolean CheckIfRecordExists(String rid, String did) {
String Query = "Select * from " + DBHelper.TABLE_EXERCISE_DETAILS + " where " + DBHelper.COLUMN_ROUTINE_ID + " = " + rid + " AND " + DBHelper.COLUMN_DAY_ID + " = " + did;
Cursor cursor = mDatabase.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
protected ExerciseDetails cursorToExerciseDetails(Cursor cursor) {
try{
ExerciseDetails exerciseDetails = new ExerciseDetails();
exerciseDetails.setExDetailsId(cursor.getLong(0));
exerciseDetails.setRoutineId(cursor.getString(1));
exerciseDetails.setDayId(cursor.getString(2));
exerciseDetails.setExerciseId(cursor.getString(3));
exerciseDetails.setReps(cursor.getString(4));
exerciseDetails.setSets(cursor.getString(5));
exerciseDetails.setTimePerset(cursor.getString(6));
exerciseDetails.setCalorieBurn(cursor.getString(7));
exerciseDetails.setResttimePerset(cursor.getString(8));
exerciseDetails.setOrder(cursor.getString(9));
exerciseDetails.setMenuName(cursor.getString(10));
exerciseDetails.setTips(cursor.getString(11));
exerciseDetails.setYoutubeUrl(cursor.getString(12));
exerciseDetails.setWarnings(cursor.getString(13));
exerciseDetails.setDisplayId(cursor.getString(14));
exerciseDetails.setVisibility(cursor.getString(15));
exerciseDetails.setForDate(cursor.getString(16));
exerciseDetails.setMenuIcon(cursor.getString(17));
exerciseDetails.setDayName(cursor.getString(18));
return exerciseDetails;
} catch (Exception e){
System.out.println("error------------"+e);
return null;
}
}
}
FUll json value which i inserted Into sqllite
https://pastebin.com/DmAkPkXg
In cursorToExerciseDetails() instead of explicitly setting the index of a column:
exerciseDetails.setExDetailsId(cursor.getLong(0));
exerciseDetails.setRoutineId(cursor.getString(1));
....................................................
use getColumnIndex() with he name of the column to return the index:
exerciseDetails.setExDetailsId(cursor.getLong(cursor.getColumnIndex(DBHelper.COLUMN_EX_DETAILS_ID)));
exerciseDetails.setRoutineId(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_ROUTINE_ID))));
....................................................
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();
}
}
}
I write a simple application to get phone number in Contacts. However, the phone number return "null".
Here is my code:
private void queryContactPhoneNumber() {
// TODO Auto-generated method stub
String[] cols = new String[] {People.NAME, People.NUMBER};
Uri myContacts = People.CONTENT_URI;
Cursor mqCur = managedQuery(myContacts, cols, null, null, null);
if(mqCur.moveToFirst())
{
String myname = null;
String mynumber = null;
do
{
myname = mqCur.getString(mqCur.getColumnIndex(People.NAME));
mynumber = mqCur.getString(mqCur.getColumnIndex(People.NUMBER));
Toast.makeText(this, myname + " " + mynumber, Toast.LENGTH_SHORT).show();
}
while(mqCur.moveToNext());
}
}
Try this,
Uri myContacts = ContactsContract.CommonDataKinds.Phone.CONTENT_URI ;//People.CONTENT_URI;
Cursor mqCur = managedQuery(myContacts, null, null, null, null);
if(mqCur.moveToFirst())
{
String myname = null;
String mynumber = null;
do
{
myname = mqCur.getString(mqCur.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
mynumber = mqCur.getString(mqCur
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
Toast.makeText(this, myname + " " + mynumber, Toast.LENGTH_SHORT).show();
}
while(mqCur.moveToNext());
}
I think this will help you.
i have a issue making a SQLite edition, basicly, the error is java.lang.NumberFormatException, im making Long.parseLong in my data, but i dont know why the program continues sending me that error , the code of my first class is next:
public class SQLiteActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText ecoursename, etopic, ecourse_description, elength, erating, esearch;
Button insert, view, search, edit, delete;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ecoursename = (EditText) findViewById(R.id.cName);
etopic = (EditText) findViewById(R.id.cTopic);
ecourse_description= (EditText) findViewById(R.id.cDescription);
elength= (EditText) findViewById(R.id.cLength);
erating= (EditText) findViewById(R.id.cRating);
esearch = (EditText) findViewById(R.id.etSearch);
insert = (Button) findViewById(R.id.btInsert);
view = (Button) findViewById(R.id.btView);
search = (Button) findViewById(R.id.btSearch);
edit = (Button) findViewById(R.id.btEdit);
delete = (Button) findViewById(R.id.btDelete);
search.setOnClickListener(this);
edit.setOnClickListener(this);
delete.setOnClickListener(this);
insert.setOnClickListener(this);
view.setOnClickListener(this);
}
public void onClick(View v) {
//TODO Auto-generated method stub
switch (v.getId()){
case R.id.btInsert:
boolean works = true;
try{
String course_name = ecoursename.getText().toString();
String topic = etopic.getText().toString();
String course_description = ecourse_description.getText().toString();
String length = elength.getText().toString();
String rating = erating.getText().toString();
ecoursename.setText("");
etopic.setText("");
ecourse_description.setText("");
elength.setText("");
erating.setText("");
DBAdapter entry = new DBAdapter (SQLiteActivity.this);
entry.open();
entry.createEntry(course_name, topic, course_description, length, rating);
entry.close();
}catch(Exception e){
works = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Dont Works");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}finally{
if(works){
// make click says inserted text
Dialog d = new Dialog(this);
d.setTitle("Works?");
TextView tv = new TextView(this);
tv.setText("is Working");
d.setContentView(tv);
d.show();
}
}
break;
case R.id.btView:
Intent i = new Intent("com.sqlite.base.data.SQLVista");
startActivity(i);
break;
case R.id.btSearch:
String s = esearch.getText().toString();
Long ls = Long.parseLong(s);
DBAdapter dbase= new DBAdapter(this);
try{
dbase.open();
}catch(Exception e){
e.printStackTrace();
}
String bN = dbase.getN(ls);
String bT = dbase.getT(ls);
String bD = dbase.getD(ls);
String bL = dbase.getL(ls);
String bR = dbase.getR(ls);
dbase.close();
ecoursename.setText(bN);
etopic.setText(bT);
ecourse_description.setText(bD);
elength.setText(bL);
erating.setText(bR);
break;
case R.id.btEdit:
try{
String eCo = ecoursename.getText().toString();
String eTo = etopic.getText().toString();
String eDe = ecourse_description.getText().toString();
String eLe = elength.getText().toString();
String eRa = erating.getText().toString();
String eRow = esearch.getText().toString();
long eRowl = Long.parseLong(eRow);
DBAdapter edit = new DBAdapter(this);
edit.open();
edit.edit(eRowl, eCo, eTo, eDe, eLe, eRa);
edit.close();
}catch(Exception e) {
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Dont Works!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
break;
case R.id.btDelete:
break;
}
}
}
my DBAdapter class:
public class DBAdapter {
public static final String ID_ROW = "_id";
public static final String ID_COURSENAME = "course_name";
public static final String ID_TOPIC = "topic";
public static final String ID_DESCRIPTION = "course_description";
public static final String ID_LENGTH = "length";
public static final String ID_RATING = "rating";
private static final String N_DB = "Clases";
private static final String N_TABLE = "Courses";
private static final int VERSION_DB = 1;
private DBHelper nHelper;
private final Context nContext;
private SQLiteDatabase nDB;
private static class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context) {
super(context, N_DB, null, VERSION_DB);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(" CREATE TABLE " + N_TABLE + "(" + ID_ROW + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ID_COURSENAME + " TEXT NOT NULL, " + ID_TOPIC + " TEXT NOT NULL, " + ID_DESCRIPTION + " TEXT NOT NULL, " + ID_LENGTH + " TEXT NOT NULL, " + ID_RATING + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + N_TABLE);
onCreate(db);
}
}
public DBAdapter (Context c){
nContext = c;
}
public DBAdapter open() throws SQLException{
nHelper = new DBHelper(nContext);
nDB = nHelper.getWritableDatabase();
return this;
}
public void close() {
// TODO Auto-generated method stub
nHelper.close();
}
public long createEntry(String course_name, String topic, String course_description, String length, String rating ) {
// TODO Auto-generated method stub
//insert data
ContentValues cv = new ContentValues();
cv.put(ID_COURSENAME, course_name);
cv.put(ID_TOPIC, topic);
cv.put(ID_DESCRIPTION, course_description);
cv.put(ID_LENGTH, length);
cv.put(ID_RATING, rating);
//return content in table
return nDB.insert(N_TABLE, null, cv);
}
public String receive() {
// TODO Auto-generated method stub
String[] columns = new String[]{ID_ROW, ID_COURSENAME, ID_TOPIC, ID_DESCRIPTION, ID_LENGTH, ID_RATING};
Cursor c = nDB.query(N_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(ID_ROW);
int cName = c.getColumnIndex(ID_COURSENAME);
int cTopic = c.getColumnIndex(ID_TOPIC);
int cDescription = c.getColumnIndex(ID_DESCRIPTION);
int cLength = c.getColumnIndex(ID_LENGTH);
int cRating = c.getColumnIndex(ID_RATING);
//loop
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(cName) + " " + c.getString(cTopic) + " " + c.getString(cDescription) + " " + c.getString(cLength) + " " + c.getString(cRating) + "\n ";
}
return result;
}
public String getN(Long ls) {
// TODO Auto-generated method stub
String[] columns = new String[]{ID_ROW, ID_COURSENAME, ID_TOPIC, ID_DESCRIPTION, ID_LENGTH, ID_RATING};
Cursor c =nDB.query(N_TABLE, columns, ID_ROW + "=" + ls, null, null, null, null);
if(c != null){
c.moveToFirst();
String ns = c.getString(1);
return ns;
}
return null;
}
public String getT(Long ls) {
// TODO Auto-generated method stub
String[] columns = new String[]{ID_ROW, ID_COURSENAME, ID_TOPIC, ID_DESCRIPTION, ID_LENGTH, ID_RATING};
Cursor c =nDB.query(N_TABLE, columns, ID_ROW + "=" + ls, null, null, null, null);
if(c != null){
c.moveToFirst();
String ts = c.getString(2);
return ts;
}
return null;
}
public String getD(Long ls) {
// TODO Auto-generated method stub
String[] columns = new String[]{ID_ROW, ID_COURSENAME, ID_TOPIC, ID_DESCRIPTION, ID_LENGTH, ID_RATING};
Cursor c =nDB.query(N_TABLE, columns, ID_ROW + "=" + ls, null, null, null, null);
if(c != null){
c.moveToFirst();
String nd = c.getString(3);
return nd;
}
return null;
}
public String getL(Long ls) {
// TODO Auto-generated method stub
String[] columns = new String[]{ID_ROW, ID_COURSENAME, ID_TOPIC, ID_DESCRIPTION, ID_LENGTH, ID_RATING};
Cursor c =nDB.query(N_TABLE, columns, ID_ROW + "=" + ls, null, null, null, null);
if(c != null){
c.moveToFirst();
String nl = c.getString(4);
return nl;
}
return null;
}
public String getR(Long ls) {
// TODO Auto-generated method stub
String[] columns = new String[]{ID_ROW, ID_COURSENAME, ID_TOPIC, ID_DESCRIPTION, ID_LENGTH, ID_RATING};
Cursor c =nDB.query(N_TABLE, columns, ID_ROW + "=" + ls, null, null, null, null);
if(c != null){
c.moveToFirst();
String nr = c.getString(5);
return nr;
}
return null;
}
public void edit(long eRowl, String eCo, String eTo, String eDe,
String eLe, String eRa) throws SQLException {
// TODO Auto-generated method stub
ContentValues cvEdit = new ContentValues();
cvEdit.put(ID_COURSENAME, eCo);
cvEdit.put(ID_TOPIC, eTo);
cvEdit.put(ID_DESCRIPTION, eDe);
cvEdit.put(ID_LENGTH, eLe);
cvEdit.put(ID_RATING, eRa);
nDB.update(N_TABLE, cvEdit, ID_ROW + "=" + eRowl, null);
}}
really would appreciate your help
Thanks for your screenshot.Could you please improve your code to this:
}catch(Exception e) {
String error = e.getMessage(); //instead of String error = e.toString();
...
So we can see the actual cause.
Can you please make the "don't works" dialog large? I think some text is being trimmed.
I believe you are trying to parse an empty string "".
Any one help me. I want to print some suggestion if Cursor value return as null.
This is method of helper class for display data for corresponding ID
public Cursor display(int id) {
// TODO Auto-generated method stub
DBHelper=new DatabaseHelper(context);
db=DBHelper.getReadableDatabase();
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_ISBN}, KEY_ROWID + "=" + id, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
and this is my activity class from where iam calling display()
public void onClick(View v) {
// TODO Auto-generated method stub
int id=Integer.parseInt(inputid.getText().toString());
DBAdapter dbadapter = new DBAdapter(v.getContext());
Cursor c=dbadapter.display(id);
if(c!=null)
Toast.makeText(this, "Name: " + c.getString(1) , Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "Enter Valid ID", Toast.LENGTH_LONG).show();
}
Simply use this rawQuery :
public Cursor getSubDirectory(String parentId, String orderby, String order){
String sql = "SELECT * FROM "+DOCUMENTS+ " where "+DatabaseConstant.key_DOCUMENT_PARENT_ID +" = "+parentId+" ORDER BY "+orderby +" "+ order ;
return myDataBase.rawQuery(sql, null);
}