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 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;
}
I am trying to query the Contacts database for contacts information, I have designed the program in a way that only contacts with Birth Day details are fetched:
projection = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Event.CONTACT_ID,
ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.CommonDataKinds.Email.DATA,
};
where = ContactsContract.Data.MIMETYPE + "= ? AND " +
ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
selectionArgs = new String[] { ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };
The Call:
getLoaderManager().initLoader(0, null, this);
And Finally I try to fetch the result:
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
CursorLoader loader = new CursorLoader(this, uri, projection, where,
selectionArgs, null);
return loader;
}
#SuppressWarnings("unchecked")
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
Map<Date,String> BD = new HashMap<Date,String>();
while (cursor.moveToNext()) {
String id = cursor.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Toast.makeText(getApplicationContext(), ""+id, 10000).show();
String displayBirthday = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
String name = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String DateStr=displayBirthday;
Date d = null;
try {
d = new SimpleDateFormat("yyyy-MM-dd", current).parse(DateStr);
} catch (ParseException e) {
e.printStackTrace();
}
java.sql.Date d1 = new java.sql.Date(d.getTime());
BD.put(d1, name);
}
TreeMap Sorted = new TreeMap<Date,String>(BD);
//new MagicCall().execute(Sorted);
}
However I do not get the phone number, it gives me the birth day field result in the toast message instead of the phone number, if I change it to email it still gives me the birthday detail. Please neglect the suppress warnings as this is a test project in which I have isolate the problem code.
try with this dude :) best of luck
<uses-permission android:name="android.permission.READ_CONTACTS" />
and this is code of class
public class ReadContacts extends AsyncTask<Void, Void, Void>{
private ListView contactsList;
private Context cntx;
private Constant constants;
static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
Contacts._ID, // 0
Contacts.DISPLAY_NAME, // 1
Contacts.STARRED, // 2
Contacts.TIMES_CONTACTED, // 3
Contacts.CONTACT_PRESENCE, // 4
Contacts.PHOTO_ID, // 5
Contacts.LOOKUP_KEY, // 6
Contacts.HAS_PHONE_NUMBER, // 7
};
private long contactId;
private String display_name;
private String phoneNumber;
private ArrayList<ContactsWrapper>contactWrap = new ArrayList<ContactsWrapper>();
private HashMap<Long, ArrayList<ContactsWrapper>>map = new HashMap<Long, ArrayList<ContactsWrapper>>();
private ContactsAdapter adapter;
private DataController controller;
public ReadContacts(Context cntx, ListView contactList) {
// TODO Auto-generated constructor stub
this.cntx = cntx;
constants = new Constant();
this.contactsList = contactList;
controller = DataController.getInstance();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if(!(controller.contactWrapper.size()>0))
constants.displayProgressDialog(cntx, "Loading Contacts...", "Please Wait");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if(!(controller.contactWrapper.size()>0))
{
try {
String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ Contacts.DISPLAY_NAME + " != '' ))";
Cursor c = cntx.getContentResolver().query(Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, select,
null, Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
int colorcounter = 0;
String[] colorcounter_array = { "#91A46B", "#8BB6B5", "#CAA973", "#8DA6C8","#D19B8D"};
int color_string;
for(int i=0;i<c.getCount();i++)
{
// contactWrap.clear();
try {
contactId = 0;
String hasPhone = "";
display_name = "";
phoneNumber = "";
c.moveToPosition(i);
contactId = c.getLong(0);
display_name = c.getString(1);
hasPhone = c.getString(7);
if (hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false" ;
if (Boolean.parseBoolean(hasPhone))
{
Cursor phones = cntx.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
while (phones.moveToNext())
{
int indexPhoneType = phones.getColumnIndexOrThrow(Phone.TYPE);
String phoneType = phones.getString(indexPhoneType);
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
if (colorcounter < 5)
{
color_string =Color.parseColor(colorcounter_array[colorcounter]);
colorcounter++;
} else {
colorcounter = 0;
color_string =Color.parseColor(colorcounter_array[colorcounter]);
colorcounter++;
}
contactWrap.add(new ContactsWrapper(contactId, display_name, phoneNumber,lookupKey,false,color_string));
}
// map.put(contactId, new ArrayList<ContactsWrapper>(contactWrap));
phones.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
controller.contactWrapper = contactWrap;
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
constants.dismissDialog();
adapter = new ContactsAdapter(cntx);
contactsList.setAdapter(adapter);
}
}
and this is my contact wrapper class
public class ContactsWrapper {
private long contactId;
private String displayName,displayNumber,lookUp;
public boolean checked = true;
int color_string;
public ContactsWrapper(long contactId, String displayName, String displayNumber, String lookUp, boolean checked,int color_string) {
// TODO Auto-generated constructor stub
this.contactId = contactId;
this.displayName = displayName;
this.displayNumber = displayNumber;
this.lookUp = lookUp;
this.checked = checked;
this.color_string =color_string;
}
public String getLookUp() {
return lookUp;
}
public int getColor_string() {
return color_string;
}
public boolean isChecked() {
return checked;
}
public long getContactId() {
return contactId;
}
public String getDisplayName() {
return displayName;
}
public String getDisplayNumber() {
return displayNumber;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
}
dont panic dude just match list with thar birthdate and take one temp arraylist and when any name match then add in that temp arraylist and then show that list view according to that temp arraylist :) here i give u code and hint i think it will help u to achieve whatever u want...:)
ArrayList<String> matchname = new ArrayList<String>();
for(int l =0;l<contactarraylist.size();l++)
{
String keyname = contactarraylist[k];
if((keyname.trim().equals("birthdate_string")))
{
matchname.add(keyname);
}
}
}
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 "".
I have jokes.db database. This database file imported from using this article., http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/. Now i have Jokes.db in to /data/data/a.b.c/database/Jokes.db. In this database , I have two table NepaliJokes and EnglishJokes. So Now I want to retrive this nepali and english jokes and display in to textview, But I have done following code but couldnot more idea behind How to retrieve data from database.
public class FunnyJokes extends Activity implements View.OnClickListener {
private SQLiteDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
Button back;
super.onCreate(savedInstanceState);
setContentView(R.layout.displayjoks1);
back = (Button) findViewById(R.id.back_btn);
back.setOnClickListener(this);
DataBaseHelper helper = new DataBaseHelper(this);
database = helper.getWritableDatabase();
loadJokes();
}
private void loadJokes() {
//jok=new ArrayList<String>();
/*Cursor c = database.query("SELECT title,body" +
" FROM " + 'tableName'
+ " WHERE category=1;",
null);*/
Cursor c = database.query("NepaliJokes",
null, null, null, null, null, null);
c.moveToPosition(0);
TextView tv= (TextView) findViewById(R.id.textView1);
tv.append(c.getString(1));
c.close();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.back_btn:
FunnyJokes.this.finish();
break;
default:
break;
}
}
}
I also use the database file import from in DDMS->fileExploer. I import database file Pull mobile icon from left of file explorer section.
To read values from the table:
Create a cursor to read data from the database.
Write the following function.
public Cursor retrieveRecords(int category)
{
Cursor c = null;
c = db.rawQuery("select title,body from tablename where category=" +category, null);
return c;
}
Now get the values from the cursor.
public void getDataFromDatabase()
{
try
{
Cursor cursor = null;
db.OpenDatabase();
cursor = db.retrieveRecords();
if (cursor.getCount() != 0)
{
if (cursor.moveToFirst())
{
do
{
titleArrayList.add(cursor.getString(cursor.getColumnIndex("title")));
bodyArrayList.add(cursor.getString(cursor.getColumnIndex("body")));
} while (cursor.moveToNext());
}
db.closeDatabase();
}
cursor.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
I an using the fallowing class for manage DataBase in my application.
public class PersonDbHelper {
public class Row_DocumentTable extends Object {
public int rwo_id;
public String dockey;
public String docid;
public String size;
public String status;
public String name;
public String product_discription;
public String type;
public String publisher;
public String version;
public String filepathurl;
public String basepage;
public String copypaste;
public String save;
public String print;
public String printablepage;
public String nonprintablepage;
public String search;
public String watermarkimageurl;
public String expiry;
public String versiondescription;
public String update_available;
public String localfilepath;
}
public class Row_CategoriesTable extends Object {
public String dockey;
public String category_id;
public String category_name;
}
private static final String DROP_DOCUMENTDETAIL_TABLE_FROM_DATABASE = "drop table if exists CONTENTRAVENDB.DOCUMENTDETAIL";
private static final String DROP_CATEGORIES_TABLE_FROM_DATABASE = "drop table if exists CONTENTRAVENDB.CATEGORIES";
private static final String DATABASE_CREATE_DOCUMENTDETAIL = "create table DOCUMENTDETAIL(row_id integer primary key autoincrement, dockey text , "
+ "docid text not null,"
+ "size text not null,"
+ "status text not null,"
+ "name text not null,"
+ "product_discription text not null,"
+ "type text not null,"
+ "publisher text not null,"
+ "version text not null,"
+ "filepathurl text not null,"
+ "basepage text not null,"
+ "copypaste text not null,"
+ "save text not null,"
+ "print text not null,"
+ "printablepage text not null,"
+ "nonprintablepage text not null,"
+ "search text ,"
+ "watermarkimageurl text not null,"
+ "expiry text not null,"
+ "versiondescription text not null,"
+ "update_available text not null,"
+ "localfilepath text not null"
+ ");";
private static final String DATABASE_CREATE_CATEGORIES = "create table CATEGORIES(_id integer primary key autoincrement, "
+ "dockey text ,"
+ "category_id text ,"
+ "category_name text"
+ ");";
private static final String DATABASE_NAME = "CONTENTRAVENDB";
private static final String DATABASE_TABLE1 = "CATEGORIES";
private static final String DATABASE_TABLE2 = "DOCUMENTDETAIL";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase db;
public PersonDbHelper(Context ctx) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
db.execSQL(DATABASE_CREATE_DOCUMENTDETAIL);
db.execSQL(DATABASE_CREATE_CATEGORIES);
}
public void dropAllTable(Context ctx) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
// db.execSQL(DROP_DOCUMENTDETAIL_TABLE_FROM_DATABASE);
// db.execSQL(DROP_CATEGORIES_TABLE_FROM_DATABASE);
db.delete(DATABASE_TABLE1, null, null);
db.delete(DATABASE_TABLE2, null, null);
close();
}
public PersonDbHelper(Context ctx, String abc) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
}
public PersonDbHelper() {
}
public void close() {
db.close();
}
public void createRow_InDocumentDetailTable(String dockey, String docid,
String size, String status, String name,
String product_discription, String type, String publisher,
String version, String filepathurl, String basepage,
String copypaste, String save, String print, String printablepage,
String nonprintablepage, String search, String watermarkimageurl,
String expiry, String versiondescription, String update_available,
String localfilepath) {
ContentValues initialValues = new ContentValues();
initialValues.put("dockey", dockey);
initialValues.put("docid", docid);
initialValues.put("size", size);
initialValues.put("status", status);
initialValues.put("name", name);
initialValues.put("product_discription", product_discription);
initialValues.put("type", type);
initialValues.put("publisher", publisher);
initialValues.put("version", version);
initialValues.put("filepathurl", filepathurl);
initialValues.put("basepage", basepage);
initialValues.put("copypaste", copypaste);
initialValues.put("save", save);
initialValues.put("print", print);
initialValues.put("printablepage", printablepage);
initialValues.put("nonprintablepage", nonprintablepage);
initialValues.put("search", search);
initialValues.put("watermarkimageurl", watermarkimageurl);
initialValues.put("expiry", expiry);
initialValues.put("versiondescription", versiondescription);
initialValues.put("update_available", update_available);
initialValues.put("localfilepath", localfilepath);
db.insert(DATABASE_TABLE2, null, initialValues);
}
public void createRow_InCategorieTable(String dockey, String category_id,
String category_name) {
ContentValues initialValues = new ContentValues();
initialValues.put("dockey", dockey);
initialValues.put("category_id", category_id);
initialValues.put("category_name", category_name);
db.insert(DATABASE_TABLE1, null, initialValues);
}
public void deleteRow_FromDocumentDetailTable(long rowId) {
db.delete(DATABASE_TABLE2, "_id=" + rowId, null);
}
public List<Row_DocumentTable> fetchAllRows_FromDocumentDetailTable() {
ArrayList<Row_DocumentTable> ret = new ArrayList<Row_DocumentTable>();
try {
String sql = "select * from DOCUMENTDETAIL";
Cursor c = db.rawQuery(sql, null);
// Cursor c =
// db.query(DATABASE_TABLE2, new String[] {
// "row_id","dockey","docid","size", "status", "name",
// "product_discription",
// "type", "publisher", "version", "filepathurl", "basepage"
// , "copypaste", "save", "print", "printablepage",
// "nonprintablepage"
// , "search", "watermarkimageurl", "expiry",
// "versiondescription","update_available","localfilepath"
// }, null, null, null, null, null);
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; ++i) {
Row_DocumentTable row = new Row_DocumentTable();
row.rwo_id = c.getInt(0);
row.dockey = c.getString(1);
row.docid = c.getString(2);
row.size = c.getString(3);
row.status = c.getString(4);
row.name = c.getString(5);
row.product_discription = c.getString(6);
row.type = c.getString(7);
row.publisher = c.getString(8);
row.version = c.getString(9);
row.filepathurl = c.getString(10);
row.basepage = c.getString(11);
row.copypaste = c.getString(12);
row.save = c.getString(13);
row.print = c.getString(14);
row.printablepage = c.getString(15);
row.nonprintablepage = c.getString(16);
row.search = c.getString(17);
row.watermarkimageurl = c.getString(18);
row.expiry = c.getString(19);
row.versiondescription = c.getString(20);
row.update_available = c.getString(21);
row.localfilepath = c.getString(22);
ret.add(row);
c.moveToNext();
}
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
}
return ret;
}
public List<Row_DocumentTable> fetchAllRows_Of_Single_Type(String argtype) {
ArrayList<Row_DocumentTable> ret = new ArrayList<Row_DocumentTable>();
try {
String sql = "select * from DOCUMENTDETAIL where type='" + argtype
+ "'";
Cursor c = db.rawQuery(sql, null);
// Cursor c=db.query(DATABASE_TABLE2, new String[] {
// "dockey","docid", "status", "name", "product_discription",
// "type", "publisher", "version", "filepathurl", "basepage"
// , "copypaste", "save", "print", "printablepage",
// "nonprintablepage"
// , "search", "watermarkimageurl", "expiry", "versiondescription"
// }, "type=PDF", null, null, null, null);
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; ++i) {
Row_DocumentTable row = new Row_DocumentTable();
row.rwo_id = c.getInt(0);
row.dockey = c.getString(1);
row.docid = c.getString(2);
row.size = c.getString(3);
row.status = c.getString(4);
row.name = c.getString(5);
row.product_discription = c.getString(6);
row.type = c.getString(7);
row.publisher = c.getString(8);
row.version = c.getString(9);
row.filepathurl = c.getString(10);
row.basepage = c.getString(11);
row.copypaste = c.getString(12);
row.save = c.getString(13);
row.print = c.getString(14);
row.printablepage = c.getString(15);
row.nonprintablepage = c.getString(16);
row.search = c.getString(17);
row.watermarkimageurl = c.getString(18);
row.expiry = c.getString(19);
row.versiondescription = c.getString(20);
row.update_available = c.getString(21);
ret.add(row);
c.moveToNext();
}
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
}
return ret;
}
public List<Row_CategoriesTable> fetchAllRows_FromCategorieTable(
String argsql) {
ArrayList<Row_CategoriesTable> ret = new ArrayList<Row_CategoriesTable>();
try {
String sql = argsql;
Cursor c = db.rawQuery(sql, null);
// Cursor c =
// db.query(true,DATABASE_TABLE1, new String[] {
// "dockey","category_id","category_name"
// }, null,null,null, null, null,null);
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; ++i) {
Row_CategoriesTable row = new Row_CategoriesTable();
row.dockey = c.getString(0);
row.category_id = c.getString(0);
row.category_name = c.getString(0);
ret.add(row);
c.moveToNext();
}
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
}
return ret;
}
public Row_DocumentTable fetchRow_FromDocumentDetailTableByDocKey(
String dockey) {
Row_DocumentTable row = new Row_DocumentTable();
String sql = "select * from DOCUMENTDETAIL where dockey='" + dockey
+ "'";
try {
Cursor c = db.rawQuery(sql, null);
// Cursor c =
// db.query(DATABASE_TABLE2, new String[] {
// "dockey","docid", "status", "name", "product_discription",
// "type", "publisher", "version", "filepathurl", "basepage"
// , "copypaste", "save", "print", "printablepage",
// "nonprintablepage"
// , "search", "watermarkimageurl", "expiry", "versiondescription"},
// "dockey=" + dockey, null, null,
// null,null,"name desc");
if (c.getCount() > 0) {
c.moveToFirst();
row.rwo_id = c.getInt(0);
row.dockey = c.getString(1);
row.docid = c.getString(2);
row.size = c.getString(3);
row.status = c.getString(4);
row.name = c.getString(5);
row.product_discription = c.getString(6);
row.type = c.getString(7);
row.publisher = c.getString(8);
row.version = c.getString(9);
row.filepathurl = c.getString(10);
row.basepage = c.getString(11);
row.copypaste = c.getString(12);
row.save = c.getString(13);
row.print = c.getString(14);
row.printablepage = c.getString(15);
row.nonprintablepage = c.getString(16);
row.search = c.getString(17);
row.watermarkimageurl = c.getString(18);
row.expiry = c.getString(19);
row.versiondescription = c.getString(20);
row.update_available = c.getString(21);
row.localfilepath = c.getString(22);
return row;
} else {
row.docid = null;
row.dockey = row.name = null;
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
return row;
}
public void updateRow_InDocumentDetailTableByDocKey(String dockey,
String docid, String status, String name,
String product_discription, String type, String publisher,
String version, String filepathurl, String basepage,
String copypaste, String save, String print, String printablepage,
String nonprintablepage, String search, String watermarkimageurl,
String expiry, String versiondescription, String update_available) {
ContentValues args = new ContentValues();
args.put("dockey", dockey);
args.put("docid", docid);
args.put("status", status);
args.put("name", name);
args.put("product_discription", product_discription);
args.put("type", type);
args.put("publisher", publisher);
args.put("version", version);
args.put("filepathurl", filepathurl);
args.put("basepage", basepage);
args.put("copypaste", copypaste);
args.put("save", save);
args.put("print", print);
args.put("printablepage", printablepage);
args.put("nonprintablepage", nonprintablepage);
args.put("search", search);
args.put("watermarkimageurl", watermarkimageurl);
args.put("expiry", expiry);
args.put("versiondescription", versiondescription);
args.put("update_available", update_available);
db.update(DATABASE_TABLE2, args, "dockey='" + dockey + "'", null);
}
public Cursor GetAllRows() {
try {
return db.query(DATABASE_TABLE2, new String[] { "dockey", "docid",
"status", "name", "product_discription", "type",
"publisher", "version", "filepathurl", "basepage",
"copypaste", "save", "print", "printablepage",
"nonprintablepage", "search", "watermarkimageurl",
"expiry", "versiondescription" }, null, null, null, null,
null);
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
return null;
}
}
public void updateRow_InDocumentDetailTableByDocKey_UpdateAvl(Context ctx,
String dockey, String update_available) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
ContentValues args = new ContentValues();
args.put("update_available", update_available);
db.update(DATABASE_TABLE2, args, "dockey='" + dockey + "'", null);
}
public void updateRow_InDocumentDetailTableByDocKey_LocalFilePath(
Context ctx, String dockey, String argLocalFilePath) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
ContentValues args = new ContentValues();
args.put("localfilepath", argLocalFilePath);
db.update(DATABASE_TABLE2, args, "dockey='" + dockey + "'", null);
}
}
I have two table and apply all the query insert update delete and createtable select using the code it is working fine.
I hope this is help.
First of all don't use tv.append instead use setText because if u use append then ur next joke will be append to the previous one and textView show the jokes as you click the button
Actually the answere is long enough so
I have written a ansere in my blog please see the link the code will do exactly what you are lokking for but i just made one table you can add more table similarly.
You can visit HERE