How to store the .txt file in SQLite Android - java

I created application of write and read file. when i click button ,my file is write and also read the file on the same button click.I want as and when my file is write , that file is save it into SQLite.I'm surfing lot of on the net but can't find proper source or ideas how to do this.And that file is compare with input String something like "code" . If this input_String is match with that file which is store in the SQLite database , if match user can't go ahead for the further process.I would appreciate if anybody out there is capable of giving me some advice on this one and I hope other people find this helpful too.Here is my code.Thanks in Advanced.
The Activity class
public class Write extends Activity {
/** Called when the activity is first created. */
EditText myText;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.abc);
myText = (EditText) findViewById(R.id.myText);
Button createButton = (Button) findViewById(R.id.btnCreate);
Button readButton = (Button) findViewById(R.id.btnRead);
createButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
createFile(myText.getText().toString());
myText.setText("");
readFile();
}
});
}
private void createFile(String Text)
{
FileOutputStream fos = null;
try
{
fos = openFileOutput("mynote.txt", MODE_PRIVATE);
fos.write(Text.getBytes());
Toast.makeText(getApplicationContext(), "File created succesfully",
Toast.LENGTH_SHORT).show();
}
catch (FileNotFoundException e)
{
Log.e("CreateFile", e.getLocalizedMessage());
}
catch (IOException e)
{
Log.e("CreateFile", e.getLocalizedMessage());
}
finally
{
if (fos != null)
{
try
{
// drain the stream
fos.flush();
fos.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
And the DataBase_Adapter code
//Table Name
public static final String TABLE_NAME_CODE="code_table";
//Colum,n Names
public static final String KEY_CODE_ID="ID";
public static final String KEY_CODE_NAME="USERNAME";
//Table Create Statement
public static final String DATABASE_CREATE_CODE = "CREATE TABLE "+TABLE_NAME_CODE+" ("+KEY_CODE_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+KEY_CODE_NAME+"TEXT)";
//Insert Code in Database code_table
public void saveCode(String strKey_Code)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(KEY_CODE_NAME , strKey_Code);
// Insert the row into your table
db.insert(TABLE_NAME_CODE, null, newValues);
}

The approach you have taken could be improved a little bit, consider storing in the database only the name of the files, you already have the files saved, right? why store their content again in the database?

Related

renameTo() not working for renaming images and returns false

I have an image gallery app, I am trying to rename images using renameTo() method but it is not able to change the name of files and returns false. I read many questions on SO for renaming files and all of them suggest for only one method for renaming files - renameTo(). Strangely enough, many questions talk about how it is not a good method for renaming files in various conditions.
Is there any other way of renaming files in android? If I use this way only, how to make it work?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
alert = new AlertDialog.Builder(this);
etRenameFile = new EditText(getApplicationContext());
alert.setTitle("Do you want to rename the file?");
alert.setMessage(" ");
alert.setView(etRenameFile);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int whichButton) {
renameFileAlert();
adapter.notifyDataSetChanged();
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// what ever you want to do with No option.
}
});
private void renameFileAlert(){
String renameFile = etRenameFile.getText().toString();
Log.v(TAG, renameFile + " another");
String filename= al_images.get(int_position).getAl_imagepath().get(fileIndex);
File oldFilePath = new File(al_images.get(int_position).getAl_imagepath().get(fileIndex));
Log.v(TAG,oldFilePath.toString());
// Log.d("OLDFILEPATH", oldFilePath.toString()); // prints the correct path of the file being selected
x = al_images.get(int_position).getAl_imagepath().get(fileIndex);
File renamedFile = new File(x.replace(filename, renameFile));
Log.v(TAG, renamedFile.toString() + " new name"); //prints new name of the file being entered
// Log.d("NEWFILE", renamedFile.toString());
boolean renamed = oldFilePath.renameTo(renamedFile);
if(renamed){
Log.v(TAG, "rename done");
} else Log.v(TAG, "failed");
notifyMediaStoreScanner(renamedFile);
}
public final void notifyMediaStoreScanner(File file) {
// try {
// MediaStore.Images.Media.insertImage(getBaseContext().getContentResolver(),
// file.getAbsolutePath(), file.getName(), null);
getBaseContext().sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
getBaseContext().sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
}
What are you trying to rename it to exactly? renameTo() will only return true if and only if the renaming succeeded; returning false otherwise.

catch exception while connecting android application to mysql using jdbc

public class MainActivity extends Activity {
Button login,signup;
EditText name,pass;
ResultSet res;
int a=0;
setting id to the views in xml page
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login=(Button)findViewById(R.id.login);
signup=(Button)findViewById(R.id.sign);
name=(EditText)findViewById(R.id.username);
pass=(EditText)findViewById(R.id.password);
establishing mysql connection on "login" button click.
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String n=name.getText().toString();
String p=pass.getText().toString();
Connection co
Statement st;
try
{
Class.forName("com.mysql.jdbc.Driver")
co =DriverManager.getConnection("jdbc:mysql://localhost /mcon","root","");
retriving the data from login "table" in mysql.i have stored two fields in login table for username and password with same value "admin".On the login button click the page will directed to admin page if the user enter correct admin, admin in the edit text.
st = co.createStatement();
res=st.executeQuery("select * from login");
Boolean rec = res.next();
if (!rec)
{
Toast.makeText(getApplication(),"norecordinthetable",
Toast.LENGTH_LONG).show( );
}
else {
do {
String s3 = res.getString(1);
String s4 = res.getString(2);
if (n.equals(s3) && p.equals(s4))
Intent iii=new Intent(MainActivity.this,Admin.class);
startActivity(iii);
a = 1;
break;
}
} while (res.next());
}
if (a == 0)
{
Toast.makeText(getApplication(),"wrongName/Password",
Toast.LENGTH_LONG).show();
name.setText("");
pass.setText("");
}
st.close();
co.close();
} catch (Exception e) {
Toast.makeText(getApplication(), "error",Toast.LENGTH_LONG).show();
}
}
});
the jdbc is really a overdue framework,try to use some new ones like mybaits. You will get much more help for the widely using of mybaits.
Make Sure you have mysql-connector-java-3.0.17-ga-bin.jar driver.
Check for permissions in the androidManifest.xml file.

NumberFormatException in Android

I'm making an application in which the user can add Store departments and for those departments the ability to add the cities of where the departments are located.
I keep on getting a NumberFormatException when I'm trying to add a city for a departement:
Caused by: java.lang.NumberFormatException: Invalid long: "null"
at java.lang.Long.invalidLong(Long.java:124)
at java.lang.Long.parseLong(Long.java:345)
at java.lang.Long.parseLong(Long.java:321)
at org.hello.addgroups.vestiging_list.onCreate(vestiging_list.java:45)
after this the app crashes but when I restart the app the values are added into the list.
these are my classes:
Add_vestiging.java:
public class Add_vestiging extends Activity implements View.OnClickListener{
EditText et,hiddenet;
Button add_bt, cancel_btn;
SQLController dbcon;
Intent i;
Long groupd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_new_vestiging);
et = (EditText)findViewById(R.id.vestigingName);
add_bt = (Button) findViewById(R.id.addBtn);
cancel_btn = (Button) findViewById(R.id.cancelBtn);
dbcon = new SQLController(this);
try {
dbcon.open();
} catch(SQLException e) {
e.printStackTrace();
}
i = getIntent();
String id = i.getStringExtra("groupID");
groupd = Long.parseLong(id);
add_bt.setOnClickListener(this);
cancel_btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.addBtn:
String name = et.getText().toString();
try {
dbcon.insertVestiging(groupd, name);
}catch(SQLiteException e) {
e.printStackTrace();
}
Intent main = new Intent(Add_vestiging.this, vestiging_list.class);
startActivity(main);
break;
case R.id.cancelBtn:
super.finish();
break;
}
}
}
vestiging_list.java:
public class vestiging_list extends Activity {
ListView lv;
SQLController dbcon;
TextView title;
Button addves;
Long long_id;
String groupid;
Intent add_ves;
String groupname;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vestiging_list);
dbcon = new SQLController(this);
title = (TextView) findViewById(R.id.vestitel);
try {
dbcon.open();
} catch (SQLException e) {
e.printStackTrace();
}
add_ves = getIntent();
groupid = add_ves.getStringExtra("groupID");
groupname = add_ves.getStringExtra("groupName");
title.setText(groupname);
long_id = Long.parseLong(groupid);
addves = (Button)findViewById(R.id.addves_bt_id);
lv = (ListView)findViewById(R.id.vestigingList_id);
addves.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add_ves = new Intent(getApplicationContext(), Add_vestiging.class);
add_ves.putExtra("groupID", groupid);
startActivity(add_ves);
}
});
Cursor cursor = dbcon.readVestigingen(long_id);
String[] from = new String[] { GroupDatabaseHelper.V_ID, GroupDatabaseHelper.VESNAME};
int[] to = new int [] { R.id.vesID, R.id.vesName};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(vestiging_list.this, R.layout.vestiging_single_row_item, cursor, from, to,1);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
}
Any ideas on how to remove the NumberFormatException?
Any help is greatly appreciated.
Thanks in advance.
Any ideas on how to remove the NumberFormatException?
The exception is caused by Long.parseLong in vestiging_list at line 45. The reason is that groupid, in your case in null. Since you didn't fill up the Intent object you used to start vestiging_list.
E.g.
case R.id.addBtn:
String name = et.getText().toString();
try {
dbcon.insertVestiging(groupd, name);
}catch(SQLiteException e) {
e.printStackTrace();
}
Intent main = new Intent(Add_vestiging.this, vestiging_list.class);
main.putExtra("groupID", String.valueOf(groupd));
startActivity(main);
break;
assuming that groupd is a long.
I think problem is in the following line :
int[] to = new int [] { R.id.vesID, R.id.vesName};
What is the type of "R.id.vesName" ?. It should be integer.
From the stack trace that you have provided I can assume that groupId is null:
groupid = add_ves.getStringExtra("groupID");
...
long_id = Long.parseLong(groupid);
According to the Long's Javadoc Long#parseLong(String) throws an Exception if the argument is not a parsable Long, sth which is the case with null.
Check if groupid can be null else you have a bug. If it can be null then check if it equals null and then set long_id to an appropriate value e.g. 0 or -1.
It looks to me like you're creating an Intent, but you're not passing the info to the intent. The class reference to the current class is just a trace, and doesn't include info.
When you make the Intent in the Add_vestiging class, in onClick, do something like main.putExtra("groupID", id).
Looks like you're putting it in the SQLController, so you could try passing that as well.

How to use ArrayList<String> for saving/retrieving in sharedpreferences

I compile the list: titleList.add(0, title), apply it in sharedpreferences: prefs.putString(TITLES, title).apply() and now need to retrieve it.
I have looked at a lot of the solutions here and none seem to fit my problem well.
The program is suppose to take text a user inputs and save it using SharedPreferences, so it can be used in a ListActivity later. This list is currently an ArrayList (I believe I need it in an array list because I am using AutoCompleteEditText for suggestions from the array list, so I need the adapter).
Based on the above logic,prefs is a sharedpreference object full of string objects. I have tried using prefs.getAll().values.toArray(new String[0...100]). I found that in an "Android" book. It works, but only gets the first item. After trying methods, Set<?> and a few others, that was the method that got anything at all.
It is all I need to have the program working PERFECTLY. Can someone please help getting this list to save in sharedpreferences, retrieving it as a complete, split, list (that can be indexed) and passing it to a ListActivity?
ArrayList<String> titleList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_lyric);
autoCompleteAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
titleList
);
lyricTitle.setAdapter(autoCompleteAdapter);
lyricTitle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// load in song when selected from auto-complete list
lyricHolder.setText(openSongFile(lyricTitle.getText().toString()));
}
});
saveBtn = (Button) findViewById(R.id.saveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
performSave();
}
});
titlePref = getSharedPreferences(titlePrefFile, MODE_PRIVATE);
//titleList = titlePref.getAll().values().toArray();
}
private void performSave() {
String title = lyricTitle.getText().toString();
String song = lyricHolder.getText().toString();
if(!areFieldsNull(title, song)) {
saveSongFile(title, song);
warnSave.show();
}
else
warnEmpty.show();
}
private void saveSongFile(String title, String song) {
BufferedWriter bufferWriter = null;
try {
FileOutputStream fos = openFileOutput(title, Context.MODE_PRIVATE);
bufferWriter = new BufferedWriter(new OutputStreamWriter(fos));
bufferWriter.write(song);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//update song title list adapter
autoCompleteAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
titleList
);
lyricTitle.setAdapter(autoCompleteAdapter);
titleList.add(0,title);
prefEditor = titlePref.edit();
prefEditor.putString("titleList", title).apply();
}
Sorry, formatting the code just wont work for me.
Thank you and Happy Holidays!
I think you need to use ObjectSerializer.
Save :
ArrayList<String> strings = new ArrayList<String>();
string.add("Hello!");
//save list into SP
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
try {
editor.putString("LIST", ObjectSerializer.serialize(strings));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
Restore :
// load list from preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
ArrayList<String> strings = new ArrayList<String>();
try {
strings = (ArrayList<String>) ObjectSerializer.deserialize(prefs.getString("LIST", ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Or use parcelable wrapping to save/retrieve your data
Sergey's answer may be just fine. Also, take a look at JPM's answer and class, on this thread. I used it yesterday.
So, using JPM's class, here's writing myBigArrayList:
// write data file for later use
String ser = SerializeObject.objectToString(myBigArrayList);
if (ser != null && !ser.equalsIgnoreCase("")) {
SerializeObject.WriteSettings(c, ser, "myobject.dat");
} else {
SerializeObject.WriteSettings(c, "", "myobject.dat");
}
And, here's a method I adapted, that returns a complete, intact arraylist:
private ArrayList<yabbaData> getYabbaData() {
String ser = SerializeObject.ReadSettings(getActivity().getApplicationContext(), "myobject.dat");
ArrayList<yabbaData> give = null;
if (ser != null && !ser.equalsIgnoreCase("")) {
Object obj = SerializeObject.stringToObject(ser);
// Then cast it to your object and
if (obj instanceof ArrayList) {
// Do something
give = (ArrayList<yabbaData>) obj;
}
}
return give;
}
In the write, I use c as my application context, where I had passed in getApplicationContext().
In the read, I used getActivity().getApplicationContext() because I was in a fragment. Sub in String for my yabbaData object, in ArrayList, and I think it's ready to use.

Eclipse inserting data into SQLite Database, no such table

I'm trying to insert data into the database but it tells me there's no such table. I also have another sqlite database inside the application, i'm not sure if that affects this one, but I don't think so. It uses the same database name, but a different table name. If you think it does affect it, tell me and I'll post up the code for that too.
The logcat gives me these messages:
(1) no such table: notes
Error inserting title=Bleh desc=bleh
android.database.sqlite.SQLiteException: no such table: notes (code 1): , while compiling: INSERT INTO notes(title,desc) VALUES (?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
at com.example.stepsaway.NoteActivity.addEntry(NoteActivity.java:102)
at com.example.stepsaway.NoteActivity.onClick(NoteActivity.java:75)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
The Activity java is:
public class NoteActivity extends Activity implements OnClickListener {
Button buttonLeaveNote;
private EditText mTitle;
private EditText mDesc;
protected NoteDBHelper noteDB = new NoteDBHelper(NoteActivity.this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note);
buttonLeaveNote = (Button) findViewById(R.id.buttonLeaveNote);
buttonLeaveNote.setOnClickListener(this);
mTitle = (EditText)findViewById(R.id.etitle);
mDesc = (EditText)findViewById(R.id.edesc);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.note, menu);
return true;
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonLeaveNote:
String title = mTitle.getText().toString();
String desc = mDesc.getText().toString();
boolean invalid = false;
if(title.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Please enter a title", Toast.LENGTH_SHORT).show();
}
else
if(desc.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Please enter description", Toast.LENGTH_SHORT).show();
}
else
if(invalid == false)
{
addEntry(title, desc);
Intent i_note = new Intent(NoteActivity.this, JustWanderingActivity.class);
startActivity(i_note);
//finish();
}
break;
}
}
public void onDestroy()
{
super.onDestroy();
noteDB.close();
}
private void addEntry(String title, String desc)
{
SQLiteDatabase notedb = noteDB.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("title", title);
values.put("desc", desc);
//values.put("lati", lati);
//values.put("lng", lng);
try
{
long newRowId;
newRowId = notedb.insert(NoteDBHelper.DATABASE_TABLE_NAME, null, values);
Toast.makeText(getApplicationContext(), "Note successfully added", Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
And the Database java is:
public class NoteDBHelper extends SQLiteOpenHelper
{
private SQLiteDatabase notedb;
public static final String NOTE_ID = "_nid";
public static final String NOTE_TITLE = "title";
public static final String NOTE_DESC = "desc";
public static final String NOTE_LAT = "lati";
public static final String NOTE_LONG = "lng";
NoteDBHelper noteDB = null;
private static final String DATABASE_NAME = "stepsaway.db";
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_TABLE_NAME = "notes";
private static final String DATABASE_TABLE_CREATE =
"CREATE TABLE " + DATABASE_TABLE_NAME + "(" +
"_nid INTEGER PRIMARY KEY AUTOINCREMENT," +
"title TEXT NOT NULL, desc LONGTEXT NOT NULL);";
public NoteDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
System.out.println("In constructor");
}
#Override
public void onCreate(SQLiteDatabase notedb) {
try{
notedb.execSQL(DATABASE_TABLE_CREATE);
}catch(Exception e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase notedb, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public Cursor rawQuery(String string, String[] strings) {
// TODO Auto-generated method stub
return null;
}
public void open() {
getWritableDatabase();
}
public Cursor getDetails(String text) throws SQLException
{
Cursor mCursor =
notedb.query(true, DATABASE_TABLE_NAME,
new String[]{NOTE_ID, NOTE_TITLE, NOTE_DESC},
NOTE_TITLE + "=" + text,
null, null, null, null, null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
}
Any help would be appreciated, thank you.
Edit: Looks like the problem is creating a second table within the same database name. It won't let me create a second one. The first time creating the DB works fine, but it gives the SQLite Exception with no such table when trying to create another table. Is there some code I need to alter or add to create a second table? Because all i did was create another sqlite database java with the same DATABASE_NAME, but a different DATABASE_TABLE_NAME.
My best guess is when you create nodeDB object, the activity is still not available. Therefore you will failed creating the table.
You can try moving how you initialise the noteDB into inside onCreate():
protected NoteDBHelper noteDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note);
noteDB = new NoteDBHelper(NoteActivity.this);
buttonLeaveNote = (Button) findViewById(R.id.buttonLeaveNote);
buttonLeaveNote.setOnClickListener(this);
mTitle = (EditText)findViewById(R.id.etitle);
mDesc = (EditText)findViewById(R.id.edesc);
}
Your onUpgrade() is empty and database schema version is 2. My guess is that your initial version of the database didn't have the notes table and when it was later added, the empty upgrade code couldn't add it. But SQLiteOpenHelper is satisfied as it is now running version 2 of the database.
To fix it once, clean your app data. E.g. in settings app, go to manage apps -> downloaded -> select your app and click on the "Clear application data" button. Or just uninstall and reinstall the app. This approach is good enough during development.
To fix it for released versions, implement onUpgrade() so that is updates the database schema and does any necessary data migration. If you're not concerned about data loss, you can just call DROP TABLE on the old tables and then call onCreate() to recreate the tables.
To your follow-up question regarding multiple tables: Just use the same helper class to manage the database. One helper per database file. Create all tables in onCreate() and do any required migrations in onUpgrade().
Regarding to First issue : as I explained in my comment >
If you have created the DB before and adding a table afterwards this can cause the problem. Tables are created for the first time DB created. So uninstall or clean the data in the app from device and run it again.
For the Second Issue :
If you want to Create a table, do the same that you are already doing for the table you have.
#Override
public void onCreate(SQLiteDatabase notedb) {
try{
notedb.execSQL(DATABASE_TABLE_CREATE);
notedb.execSQL(DATABASE_TABLE_CREATE_STRING_2);
}catch(Exception e){
e.printStackTrace();
}
}

Categories

Resources