Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SQLiteDatabase.openOrCreateDatabase("/gregpeck.db", null);
}
Obviously this is inside my Main Activity.
I have also added the permission to my Main Activity:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ie.callanan.dennis.testhw" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
The error message I receive is:
Failed to open database 'gregpeck.db'.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
I would recommend to use a SQLiteOpenHelper, if you need a private database for your application:
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "DatabaseName";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_CREATE = "CREATE TABLE ....";
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(TABLE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
// do whatever is required for the upgrade
}
}
Here you find a full example. If you want to open a database from SD card, use:
File file = new File("/sdcard/db.sqlite" );
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(file, null);
Log.d("MyApp", "Successfully opened: " + db.isOpen());
For the first case you don't need any particular permissions. For the second one you do. Note: Android 4.3 and 4.4 do restrict the access on the SD card. So it might be that you cannot access the database file at all (see for instance this article).
Related
I've done firebase authentication for login and sign up and now i want
to save user profile in local sqlite database. I've fetched the user
information from firebase and storing them in a string variable and
passing these variables to the Adduser function to save this data in
the local database.But data is not getting stored and showing "Error
with saving user" ,that is rowid is "-1" always. i'm new to android.
please help me to solve this issue. thanks in advance
java file
package com.example.mansi.busezon;
import android.app.Application;
import android.content.ContentValues;
mport android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.example.mansi.busezon.data.dbContract;
import com.example.mansi.busezon.data.dbHelper;
import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
i
public class SELL_BUY extends AppCompatActivity {
// private dbHelper mDbHelper;
String name;
String email ;
String address ;
String phoneno ;
String password ;
//String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the content of the activity to use the activity_main.xml layout file
setContentView(R.layout.activity_sell__buy);
check();
TextView BUY= (TextView) findViewById(R.id.buy);
BUY.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//create intent to open the activity
Intent BUYintent= new Intent(SELL_BUY.this,HomeActivity.class);
//start the new activity
startActivity(BUYintent);
}
});
TextView SELL= (TextView) findViewById(R.id.sell);
SELL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//create intent to open the activity
Intent SELLintent= new Intent(SELL_BUY.this,SellHomepage.class);
//start the new activity
startActivity(SELLintent);
}
});
}
public void sendMessage(View view)
{
Intent intent = new Intent(SELL_BUY.this, profile_page.class);
startActivity(intent);
}
private void check()
{
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
//database reference pointing to demo node
// DatabaseReference demoRef = rootRef.child("CI8hvEW0sfZ0oU1GziTpGYPJv2z2");
// String value = "User22";
// //push creates a unique id in database
// demoRef.push().setValue(value);
rootRef.addListenerForSingleValueEvent(new ValueEventListener()
{
String userId=getIntent().getStringExtra("Id");
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren())
{
if(ds.getKey().equals(userId))
{
//name1="aakritijohar";
name = ds.child("name").getValue(String.class);
email = ds.child("email").getValue(String.class);
address = ds.child("addres").getValue(String.class);
phoneno = ds.child("phoneno").getValue(String.class);
TextView textView = (TextView) findViewById(R.id.test);
textView.setText(phoneno);
password = ds.child("password").getValue(String.class);
Toast.makeText(SELL_BUY.this, email + " " + ds.getKey(), Toast.LENGTH_SHORT).show();
insertUser(name,email,address,phoneno,password);
}
}
Bundle extras=getIntent().getExtras();
if(extras!=null) {
String name = extras.getString("name");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
private void insertUser(String nameString,String EMAILString,String addressString,String numbertString,String pass) {
// Create database helper
dbHelper mDbHelper = new dbHelper(this);
// Gets the database in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(dbContract.userEntry.COLUMN_USER_NAME, nameString);
values.put(dbContract.userEntry.COLUMN_EMAIL, EMAILString);
values.put(dbContract.userEntry.COLUMN_number, numbertString);
values.put(dbContract.userEntry.COLUMN_address, addressString);
values.put(dbContract.userEntry.COLUMN_password, pass);
// Insert a new row for user in the database, returning the ID of that new row.
long newRowId = db.insert(dbContract.userEntry.TABLE_NAME, null, values);
// Show a toast message depending on whether or not the insertion was successful
if (newRowId == -1) {
// If the row ID is -1, then there was an error with insertion.
Toast.makeText(this, "Error with saving user", Toast.LENGTH_SHORT).show();
} else {
// Otherwise, the insertion was successful and we can display a toast with the row ID.
Toast.makeText(this, "user saved " + newRowId, Toast.LENGTH_SHORT).show();
}
}
}
database helper class
package com.example.mansi.busezon.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Database helper for Pets app. Manages database creation and version management.
*/
public class dbHelper extends SQLiteOpenHelper {
public static final String LOG_TAG = dbHelper.class.getSimpleName();
/** Name of the database file */
private static final String DATABASE_NAME = "user.db";
/**
* Database version. If you change the database schema, you must increment the database version.
*/
private static final int DATABASE_VERSION = 1;
/**
* Constructs a new instance of {#link dbHelper}.
*
* #param context of the app
*/
public dbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* This is called when the database is created for the first time.
*/
#Override
public void onCreate(SQLiteDatabase db) {
// Create a String that contains the SQL statement to create the pets table
String SQL_CREATE_USER_TABLE = "CREATE TABLE " + dbContract.userEntry.TABLE_NAME + " ("
+ dbContract.userEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ dbContract.userEntry.COLUMN_USER_NAME + " TEXT NOT NULL, "
+ dbContract.userEntry.COLUMN_address + " VARCHAR, "
+ dbContract.userEntry.COLUMN_number + " VARCHAR NOT NULL, "
+ dbContract.userEntry.COLUMN_EMAIL + " VARCHAR NOT NULL, "
+ dbContract.userEntry.COLUMN_password + " VARCHAR NOT NULL );";
// Execute the SQL statement
db.execSQL(SQL_CREATE_USER_TABLE);
}
/**
* This is called when the database needs to be upgraded.
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// The database is still at version 1, so there's nothing to do be done here.
}
}
There doesn't appear to be anything wrong with the code as it is.
As such I suspect that your issue may be that you have changed the table structure since running the App.
e.g. by adding a new column and then changing the code accordingly
However, that you have then not taken into consideration that the onCreate method only gets automatically invoked when the database is created.
That is the 'onCreate' method does not run every time the App is started.
I'd suggest that deleting the App's data or uninstalling the App and then rerunning the App will resolve the issue.
If that doesn't resolve the issue then please check the log as that should contain a stack-trace for when the insert comes across the issue even though the App doesn't itself crash (you could use the insertOrThrow method instead of insert which would then result in an exception/crash).
If you then still have issues, please update the question to include the stack-trace.
I have reached the wall on the following. I am trying to pass a variable from my main activity to a java class that generates my database because I want to use this variable in one of my queries of that database to get a result and then pass it to the Main activity. Here's my piece of code:
//MainActivity
public class MainActivity extends AppCompatActivity {
private static RadioGroup selectedAvgStds;
...... //rest of the code///
public void onClickListenerButton(){
selectedAvgStds = (RadioGroup)findViewById(R.id.controlAverageOfLiving);
showResults.setOnClickListener(
int avgStdLiving = selectedAvgStds.getCheckedRadioButtonId();
selectedAvgStdsRb = (RadioButton) findViewById(avgStdLiving);
//variable that I want to pass
String avgStdLivingText = (String) selectedAvgStdsRb.getText();
switch (option) {
case "one":
Intent intent = new Intent(MainActivity.this,DatabaseHelper.class);
Intent.putExtra("values",avgStdLivingText);
startActivity(intent);
break;
}
);
}
Piece of code of my database
//DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper{
public Cursor showResults(){
SQLiteDatabase db = this.getWritableDatabase();
//the intent does NOT work
Bundle bundle = getIntent().getExtras();
Cursor results = db.rawQuery("select * from "+TEMP_TABLE+"where value = " + selectedAvgStds , null);
return results;
}
}
The intent is not working despite the fact I have imported all the Intent libraries in the activity and the class. How can I achieve my goal? Why the Intents do not work here?
Any suggestion and idea will be enormously appreciated.
As per your comment, why do you not simply make DatabaseHelper an instance variable and parameterize your showResults method as following:
public class MyActivity extends Activity {
private DatabaseHelper myDatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//initialise your helper here
myDatabaseHelper = ...
}
public void onClickListenerButton(){
// All your other stuff here...
// variable that I want to pass
String avgStdLivingText = selectedAvgStdsRb.getText().toString();
myDatabaseHelper.showResults(avgStdLivingText);
}
}
And then within the helper class you can simply do:
public Cursor showResults(String selectedAvgStds){
SQLiteDatabase db = this.getWritableDatabase();
Cursor results = db.rawQuery("select * from "+TEMP_TABLE+"where value = " + selectedAvgStds , null);
return results;
}
}
The reason you are not able to get data using intent is that SQLiteOpenHelper class might not have the method definition for getIntent(). I would prefer you use Shared Preferences to store the data and retrieve it inside you SQLiteOpenHelper class.
in order to working with SQLite in android, I wrote this code:
public class TimeTrackerOpenHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "timetracker.db";
public TimeTrackerOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table timerecords " +
"(id integer primary key, time text, notes text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
and also for instantiating of above class, I added following code to one of my activity class oncreate method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView = (ListView) findViewById(R.id.times_list);
adapter = new TimeTrackerAdapter();
listView.setAdapter(adapter);
TimeTrackerOpenHelper openHelper = new TimeTrackerOpenHelper(this);
Log.d("databaseCreation", openHelper.toString());
openHelper.close();
}
For monitoring the result of each query that I send to my timetracker.db, I need to access to my database file. I do the following steps:
1.Run your application.
2.Go to Tools--->Android---->Device Monitor.
3.Find your application name in left panel.
4.Then click on File Explorer tab.
5.Select data folder.
6.Select data folder again and find your app or module name.
7.Click on your database name.
8.On right-top window you have an option to pull file from device.
9.Click it and save it on your PC.
10.Use FireFox Sqlite manager to attach it to your project.
but I have to say that there is not any trace of my .db file. So how can I find that?
Your database will not be created until you call getReadableDatabase() or getWriteableDatabase() on the SQLiteOpenHelper. Simply creating the instance of the SQLiteOpenHelper will not do that.
Uninstall and Reinstall the app, it will work because you changed TimeTrackerOpenHelper class so ..
When I run my app in my mobile device, I get this under the logcat :
error opening trace file: No such file or directory (2) . Any one know what met be the cause? I tried to re-build the project and clean it under:
Project > Clean...
But I still get the same error. The app says unfortunately the you cant record on this device, of which is a message I have created under my String.xml files if the phone does not support recordings.
Any one with help please do so. I will be happy to get one.
Here is the code:
public class MainActivity extends Activity {
public static final String FILE_DIRECTORY = "iRecorded_Calls";
public ListView listView;
public ScrollView mScrollView;
public TextView mTextView;
public static final String LISTEN_ENABLED = "ListenEnabled";
private static final int CATEGORY_DETAIL = 1;
private static final int NO_MEMORY_CARD = 2;
private static final int TERMS = 3;
public RadioButton radEnable;
public RadioButton radDisable;
public static final int MEDIA_MOUNTED = 0;
public static final int MEDIA_MOUNTED_READ_ONLY = 1;
public static final int NO_MEDIA = 2;
private static Resources res;
private Context context;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startActivity(new Intent(this, HomeActivity.class));
res = getResources();
listView = (ListView) findViewById(R.id.mylist);
mScrollView = (ScrollView) findViewById(R.id.ScrollView02);
mTextView = (TextView) findViewById(R.id.txtNoRecords);
SharedPreferences settings = this.getSharedPreferences(LISTEN_ENABLED,
0);
boolean silent = settings.getBoolean("silentMode", false);
if (!silent)
showDialog(CATEGORY_DETAIL);
context = this.getBaseContext();
}
//Explorer the file directory
#SuppressWarnings("deprecation")
#Override
protected void onResume() {
if (updateExternalStorageState() == MEDIA_MOUNTED) {
String filepath = Environment.getExternalStorageDirectory()
.getPath();
final File file = new File(filepath, FILE_DIRECTORY);
if (!file.exists()) {
file.mkdirs();
}
final List<Model> listDir = ListDir2(file);
filepath = getFilesDir().getAbsolutePath();
final File file2 = new File(filepath, FILE_DIRECTORY);
if (!file2.exists()) {
file2.mkdirs();
}
final List<Model> listDir2 = ListDir2(file2);
listDir.addAll(listDir2);
if (listDir.isEmpty()) {
mScrollView.setVisibility(TextView.VISIBLE);
listView.setVisibility(ScrollView.GONE);
} else {
mScrollView.setVisibility(TextView.GONE);
listView.setVisibility(ScrollView.VISIBLE);
}
final CallsAdapter adapter = new CallsAdapter(this, listDir);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
adapter.showPromotionPieceDialog(listDir.get(position)
.getCallName(), position);
}
});
I managed to figured out what was the problem on my code and fixed it and now I can be able to recorder the incoming and outgoing calls. The problem was under my RecordSercive class on the recorder part
> //________Test with the Default outputFormat and default
> Encoder________
>
> /* recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
> recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
> recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);*/
>
> //_______End for the Test with the Default outputFortmat and default Encoder________
That is where I got the Message that says unfortunately the you cant record on this device
So I changed my code to this:
> recorder = new MediaRecorder();
> recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_DOWNLINK + MediaRecorder.AudioSource.VOICE_UPLINK);//test using the addition sign
> for both DOWNLINK + UPLINK
> recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
> recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
> myFileName = getFilename();
> recorder.setOutputFile(myFileName);
Which worked fine for me, but the sound quality is is a problem, of which I will just have to increase the volume using the
> volume = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
but under the LogCat the on Eclipse when I debug my app, I still get the error opening trace file: No such file or directory (2). Of which I think it might be caused by other reasons of which I'm currently investigating like (Chris Stratton) mentioned.
In the latest version of Android they have clearly restricted working with a network of the main stream.
This had been done for UI not to break.
Possibly you raised the API version in the manifest.
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();
}
}