java.lang.NumberFormatException for string values - android

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 "".

Related

How to proceed if cursor is empty or null

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;
}

Nullpointer exception while using SQLite

I am using sqlitedatabase,and i am able to insert data properly,but issue is when i am trying to display inserted data,my app got crash and giving nullpointer exception,can any one tell the what is the issue with my code,following is my snippet code,
Error in this line
if (c1 != null & c1.getCount() != 0) {
MAinActivity.java
public class MainActivity extends Activity {
private ListView upcominglist;
private ListView todays;
private ListView eventhistory;
private ImageView addnewevent;
public ArrayList<ContactListItems> contactList;
public ContactListItems contactListItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
upcominglist=(ListView)findViewById(R.id.listview_upcoming);
todays=(ListView)findViewById(R.id.listview_todays);
eventhistory=(ListView)findViewById(R.id.listview_eventhistory);
addnewevent=(ImageView)findViewById(R.id.addneweventbutton);
addnewevent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddNewEvent.class);
startActivity(intent);
}
});
contactList = new ArrayList<ContactListItems>();
contactList.clear();
String query = "SELECT * FROM PHONE_CONTACTS ";
Cursor c1 = SqlHandler.selectQuery(query);
if (c1 != null & c1.getCount() != 0) {
if (c1.moveToNext()) {
do {
contactListItems = new ContactListItems();
contactListItems.setSlno(c1.getString(c1.getColumnIndex("slno")));
contactListItems.setNameofevent(c1.getString(c1.getColumnIndex("nameofevent")));
contactListItems.setDtofevent(c1.getString(c1.getColumnIndex("dtofevent")));
contactListItems.setTimeofevent(c1.getString(c1.getColumnIndex("timeofevent")));
contactListItems.setDuration(c1.getString(c1.getColumnIndex("duration")));
contactList.add(contactListItems);
} while (c1.moveToNext());
}
}
else
{
c1.close();
}
c1.close();
String first=contactListItems.getSlno();
System.out.println("First" + first);
String second=contactListItems.getNameofevent();
System.out.println("SEcond"+second);
String third=contactListItems.getDtofevent();
System.out.println("Third"+third);
String fourth=contactListItems.getTimeofevent();
System.out.println("Fourth"+fourth);
String fifth=contactListItems.getDuration();
System.out.println("Fifth"+fifth);
}
Addnewevent.java
public class AddNewEvent extends Activity {
private int year;
private int month;
private int day;
static final int DATE_PICKER_ID = 1111;
static final int TIME_PICKER_ID = 11111;
int flag = 0;
private ImageView addnewdata;
private LinearLayout lnr;
private Button submit;
private EditText edtnmofevent;
private EditText edtdtofevent;
private EditText edttmofevent;
private EditText edtdurationofevent;
SqlHandler sqlHandler;
private ImageView datepicks;
private ImageView timepicks;
private Calendar cal;
private int hour;
private int min;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_new_event);
sqlHandler = new SqlHandler(getApplicationContext());
addnewdata = (ImageView) findViewById(R.id.addnewdata);
submit = (Button) findViewById(R.id.btnsubmit);
edtnmofevent = (EditText) findViewById(R.id.edtnameofevent);
edtdtofevent = (EditText) findViewById(R.id.edtdateofevent);
edttmofevent = (EditText) findViewById(R.id.edttimeofevent);
edtdurationofevent = (EditText) findViewById(R.id.edtdurationofevent);
datepicks = (ImageView) findViewById(R.id.calndrdat);
timepicks = (ImageView) findViewById(R.id.timepickrs);
cal = Calendar.getInstance();
hour = cal.get(Calendar.HOUR_OF_DAY);
min = cal.get(Calendar.MINUTE);
timepicks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog(TIME_PICKER_ID);
}
});
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
StringBuilder dateValue1 = new StringBuilder().append(day).append("-").append(month + 1).append("-")
.append(year).append(" ");
// for Converting Correct Date format Save into Database
SimpleDateFormat sdf123 = new SimpleDateFormat("dd-MM-yyyy");
String abs1 = dateValue1.toString();
Date testDate1 = null;
try {
try {
testDate1 = sdf123.parse(abs1);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MM-yyyy");
String DateFormat = formatter1.format(testDate1);
edtdtofevent.setText(DateFormat);
edtdtofevent.setFocusable(false);
edtdtofevent.setInputType(InputType.TYPE_NULL);
datepicks.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(DATE_PICKER_ID);
}
});
addnewdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater li = LayoutInflater.from(AddNewEvent.this);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
AddNewEvent.this);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
lnr = (LinearLayout) findViewById(R.id.addnewlinear);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(25, 0, 0, 0);
TextView valueTV = new TextView(AddNewEvent.this);
// valueTV.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
valueTV.setText(userInput.getText());
valueTV.setLayoutParams(lp);
valueTV.setTextSize(18);
valueTV.setTextColor(Color.parseColor("#2d6cae"));
LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp1.setMargins(25, 0, 25, 0);
lp1.height = 50;
EditText edtvalues = new EditText(AddNewEvent.this);
edtvalues.setBackgroundResource(R.drawable.rect_edt);
edtvalues.setLayoutParams(lp1);
lnr.addView(valueTV);
lnr.addView(edtvalues);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(AddNewEvent.this, EventDetails.class);
startActivity(intent);
String nameofevent = edtnmofevent.getText().toString();
String dtofevent = edtdtofevent.getText().toString();
String timeofevent = edttmofevent.getText().toString();
String duration = edtdurationofevent.getText().toString();
String query = "INSERT INTO PHONE_CONTACTS(nameofevent,dtofevent,timeofevent,duration) values ('"
+ nameofevent + "','" + dtofevent + "','" + timeofevent + "','" + duration + "')";
sqlHandler.executeQuery(query);
System.out.println("Querys" + query);
}
});
}
SQL
public class SqlDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_TABLE = "PHONE_CONTACTS";
public static final String COLUMN1 = "slno";
public static final String COLUMN2 = "nameofevent";
public static final String COLUMN3 = "dtofevent";
public static final String COLUMN4 = "timeofevent";
public static final String COLUMN5 = "duration";
/* public static final String COLUMN6 = "dlabl";
public static final String COLUMN7 = "dedt";*/
private static final String SCRIPT_CREATE_DATABASE = "create table "
+ DATABASE_TABLE + " (" + COLUMN1
+ " integer primary key autoincrement, " + COLUMN2
+ " text not null, " + COLUMN3 + " text not null, " + COLUMN4 + " text not null, " + COLUMN5 + " text not null);";
public SqlDbHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
The problem is in your SqlHandler.selectQuery() that returns a null, and another problem here checking the result:
if (c1 != null & c1.getCount() != 0)
You're using bitwise and & and not the short-circuiting logical and &&. Without short circuiting the complete expression including c1.getCount() on a null reference is evaluated.
There is too much here to explain it all, so I will give you the flaws causing a null pointer exception.
I can see your method of programming is coming from worrying too much about closing things and clearing up
resources to a point, it's causing problems.
contactList = new ArrayList<ContactListItems>();
// You are clearing your list, it should be empty, you have just created it.
contactList.clear();
String query = "SELECT * FROM PHONE_CONTACTS ";
Cursor c1 = SqlHandler.selectQuery(query);
// As mentioned by the other answer. You need && not &
// if (c1 != null & c1.getCount() != 0) {
if (c1 != null && c1.getCount() != 0) {
// Move to the first entry.
c1.moveToFirst();
//if (c1.moveToNext()) {
// do {
// Continue while it has not passed the last entry.
while (!cursor.isAfterLast())
contactListItems = new ContactListItems();
contactListItems.setSlno(c1.getString(c1.getColumnIndex("slno")));
contactListItems.setNameofevent(c1.getString(c1.getColumnIndex("nameofevent")));
contactListItems.setDtofevent(c1.getString(c1.getColumnIndex("dtofevent")));
contactListItems.setTimeofevent(c1.getString(c1.getColumnIndex("timeofevent")));
contactListItems.setDuration(c1.getString(c1.getColumnIndex("duration")));
contactList.add(contactListItems);
// Move the cursor along to the next entry.
cursor.moveToNext();
}
}
// Close cursor after while and within if (so you know it is not null).
c1.close();
}
else
{
// You can't close c1 if it is Null. This will throw and error. Lose the else.
c1.close();
}
// Move this to within your if statment.
c1.close();
From your code you provided in the chat.
Don't open and close your database continuously, just close each cursor you use when you're done. Just open it at the beginning and end of your program run.
public static Cursor selectQuery(String query) {
Cursor c1 = null;
try {
if (sqlDatabase.isOpen()) {
// You are closing the database.
sqlDatabase.close();
}
sqlDatabase = dbHelper.getWritableDatabase();
c1 = sqlDatabase.rawQuery(query, null);
} catch (Exception e) {
System.out.println("DATABASE ERROR " + e);
}
return c1;
}
There are many other flaws in your project. Like the structure and how and when you are calling things. You need to modularise it out, create methods for particular tasks and call those methods, rather than have a great lump of code in oncreate.
I am sure you will have many questions about this. But currently this question is addressing your null pointer exception and that is all I will discuss here. For questions about this not relating to this exception, please ask a new question. Hope this helps.

Application stops working on mobile device but runs on emmulator

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 have 2 activities & want to save the records in its fields, also must edit and update the fields and save it finally to send it to web service

FIRSTPAGE.JAVA Here there few edit text and to be saved temporarily
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.first_page);
applno = (EditText) findViewById(R.id.rpfno);
financerups = (EditText) findViewById(R.id.finance_rupees);
tenure = (EditText) findViewById(R.id.tenure);
assetname = (EditText) findViewById(R.id.asset);
rowId = (EditText) findViewById(R.id.etRowInfo);
page1 = (Button) findViewById(R.id.pf1);
page2 = (Button) findViewById(R.id.pf2);
page3 = (Button) findViewById(R.id.pf3);
page4 = (Button) findViewById(R.id.pf4);
save = (Button) findViewById(R.id.btn_saveandcontinue);
exit = (Button) findViewById(R.id.btn_exit);
info = (Button) findViewById(R.id.info);
submitserver = (Button) findViewById(R.id.submitserver);
edit = (Button) findViewById(R.id.bEdit);
update = (Button) findViewById(R.id.bUpdate);
delete = (Button) findViewById(R.id.bDelete);
delete.setOnClickListener(this);
save.setOnClickListener(this);
exit.setOnClickListener(this);
info.setOnClickListener(this);
submitserver.setOnClickListener(this);
edit.setOnClickListener(this);
update.setOnClickListener(this);
page2.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
startActivity(new Intent(FirstPage.this, Reference.class));
}
});
page1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
startActivity(new Intent(FirstPage.this, ProfilePage1.class));
}
});
page3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(FirstPage.this, Asset.class));
}
});
page4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(FirstPage.this, OfficeUse.class));
}
});
}
public void onClick(View arg0)
{
switch (arg0.getId())
{
case R.id.btn_saveandcontinue:
boolean didItWork = true;
try{
String Applno = applno.getText().toString();
String Financerups = financerups.getText().toString();
String Tenure = tenure.getText().toString();
String Assetname = assetname.getText().toString();
WayDataBase entry = new WayDataBase(FirstPage.this);
entry.open();
entry.createEntry(Applno, Financerups, Tenure, Assetname);
entry.close();
} catch (Exception e){
didItWork = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Dang");
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();*/
startActivity(new Intent(FirstPage.this, OfficeUse.class));
}
}
break;
case R.id.info:
startActivity(new Intent (FirstPage.this, TableView.class));
finish();
break;
case R.id.bEdit:
String s = rowId.getText().toString();
long l = Long.parseLong(s);
WayDataBase wdb = new WayDataBase(this);
wdb.open();
String returnedappno = wdb.getAppno(l);
String returnedfinancerups= wdb.getfinancerups(l);
String returnedtenure = wdb.getTenure(l);
String returnedasset = wdb.getAsset(l);
wdb.close();
applno.setText(returnedappno);
financerups.setText(returnedfinancerups);
tenure.setText(returnedtenure);
assetname.setText(returnedasset);
break;
case R.id.bUpdate:
break;
case R.id.bDelete:
break;
}}}
OFFICEUSE.JAVA Here there is few mor edit text to be saved with repect to the above fields using update method and with its corresponding unique field must be used to retrieval
page2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(OfficeUse.this, Reference.class));
}});
page1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(OfficeUse.this,ProfilePage1.class));
}});
page4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(OfficeUse.this, OfficeUse.class));
}});
page3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(OfficeUse.this, Asset.class));
}});
exit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),FirstPage.class);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}});}
public void onClick(View arg0){
switch (arg0.getId()){
case R.id.btn_saveandcontinue:
boolean isItWork = true;
try{
String Applcname = applcname.getText().toString();
String Employee = employee.getText().toString();
String Psnem = psnem.getText().toString();
String Branch = branch.getText().toString();
String Clientid = clientid.getText().toString();
String Schmcode = schmcode.getText().toString();
String Agreeno = agreeno.getText().toString();
String Promoschm = promoschm.getText().toString();
WayDataBase entry1 = new WayDataBase(OfficeUse.this);
entry1.open();
entry1.createEntry1(Applcname, Employee, Psnem, Branch, Clientid, Schmcode, Agreeno, Promoschm);
entry1.close();
} catch (Exception e){
isItWork = false;
String error = e.toString();
Dialog d1 = new Dialog(this);
d1.setTitle("Office Dang");
TextView tv1 = new TextView(this);
tv1.setText(error);
d1.setContentView(tv1);
d1.show();
}finally{
if(isItWork){
Dialog d1 = new Dialog(this);
d1.setTitle("Office too work");
TextView tv1 = new TextView(this);
d1.setContentView(tv1);
d1.show();
}}
break;
case R.id.info:
startActivity(new Intent (OfficeUse.this, TableView.class));
finish();
break;
}}}
WAYDATABASE.JAVA
private static class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL( "CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_APPNO + " TEXT NOT NULL, " +
KEY_AMT + " TEXT NOT NULL, " +
KEY_TENURE + " TEXT NOT NULL, " +
KEY_ASSETS + " TEXT NOT NULL, " +
KEY_APPLCNAME + " TEXT NOT NULL, " +
KEY_EMPLOYEE + " TEXT NOT NULL, " +
KEY_PSNEM + " TEXT NOT NULL, " +
KEY_BRANCH + " TEXT NOT NULL, " +
KEY_CLIENTID + " TEXT NOT NULL, " +
KEY_SCHMCODE + " TEXT NOT NULL, " +
KEY_AGREENO + " TEXT NOT NULL, " +
KEY_PROMOSCHM + " TEXT NOT NULL);" );}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(" DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
} }
public WayDataBase(Context c){
ourContext=c;
}
public WayDataBase open() throws SQLException{
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public long createEntry(String applno, String financerups, String tenure,String assetname){
ContentValues cv = new ContentValues();
cv.put(KEY_APPNO, applno);
cv.put(KEY_AMT, financerups);
cv.put(KEY_TENURE, tenure);
cv.put(KEY_ASSETS, assetname);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public long createEntry1(String applcname, String employee, String psnem,
String branch, String clientid, String schmcode, String agreeno,
String promoschm) {
ContentValues cv1 = new ContentValues();
cv1.put(KEY_APPLCNAME,applcname);
cv1.put(KEY_EMPLOYEE,employee);
cv1.put(KEY_PSNEM,psnem);
cv1.put(KEY_BRANCH,branch);
cv1.put(KEY_CLIENTID,clientid);
cv1.put(KEY_SCHMCODE,schmcode);
cv1.put(KEY_AGREENO,agreeno);
cv1.put(KEY_PROMOSCHM,promoschm);
return ourDatabase.insert(DATABASE_TABLE, null, cv1);
}
public void close(){
ourHelper.close();
}
public String getData() {
String[] columns = new String[]{ KEY_ROWID, KEY_APPNO, KEY_AMT,KEY_TENURE, KEY_ASSETS,KEY_APPLCNAME,KEY_EMPLOYEE,KEY_PSNEM,KEY_BRANCH,KEY_CLIENTID,KEY_SCHMCODE,KEY_AGREENO,KEY_PROMOSCHM };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result=" ";
int iRow = c.getColumnIndex(KEY_ROWID);
int iAppno = c.getColumnIndex(KEY_APPNO);
int iAmt = c.getColumnIndex(KEY_AMT);
int iTenure = c.getColumnIndex(KEY_TENURE);
int iAssets = c.getColumnIndex(KEY_ASSETS);
int iApplcname = c.getColumnIndex(KEY_APPLCNAME);
int iEmployee = c.getColumnIndex(KEY_EMPLOYEE);
int iPsnem = c.getColumnIndex(KEY_PSNEM);
int iBranch = c.getColumnIndex(KEY_BRANCH);
int iClientId = c.getColumnIndex(KEY_CLIENTID);
int iSchmode = c.getColumnIndex(KEY_SCHMCODE);
int iAgreeno = c.getColumnIndex(KEY_AGREENO);
int iPromoschm = c.getColumnIndex(KEY_PROMOSCHM);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
result = result + c.getString(iRow) + " " + c.getString(iAppno) + " " + c.getString(iAmt) + " " + c.getString(iTenure) + c.getString(iAssets) +
c.getString(iApplcname) + " " + c.getString(iEmployee) + " " + c.getString(iPsnem) + " " + c.getString(iBranch) + c.getString(iClientId) +
c.getString(iSchmode) + " " + c.getString(iAgreeno) + " " + c.getString(iPromoschm) + "\n";
}
return result; }
public String getAppno(long l) {
String[] columns = new String[]{ KEY_ROWID, KEY_APPNO, KEY_AMT, KEY_TENURE, KEY_ASSETS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null, null);
if(c != null) {
c.moveToFirst();
String appno = c.getString(1);
return appno;
}
return null;}
public String getfinancerups(long l) {
String[] columns = new String[]{ KEY_ROWID, KEY_APPNO, KEY_AMT, KEY_TENURE, KEY_ASSETS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null, null);
if(c != null) {
c.moveToFirst();
String rups = c.getString(2);
return rups;
}
return null; }
public String getTenure(long l) {
String[] columns = new String[]{ KEY_ROWID, KEY_APPNO, KEY_AMT, KEY_TENURE, KEY_ASSETS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null, null);
if(c != null){
c.moveToFirst();
String tenur = c.getString(3);
return tenur;
}
return null;
}
public String getAsset(long l) {
String[] columns = new String[]{ KEY_ROWID, KEY_APPNO, KEY_AMT, KEY_TENURE, KEY_ASSETS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null, null);
if(c != null){
c.moveToFirst();
String aset = c.getString(4);
return aset;
}
return null;
}}

How to retrieve data from database in android Creating database on SqliteBrowser

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

Categories

Resources