i try to access a database of another application, i want to insert data on that database from my application. I test it on my phone (rooted) but i get errors. Can anyone help me?
12-30 00:01:27.315: E/SQLiteLog(10477): (14) os_unix.c:30241: (13) open(/data/data/com.otherapplication/databases/records.db) -
12-30 00:01:27.376: E/SQLiteDatabase(10477): Failed to open database '/data/data/com.otherapplication/databases/records.db'.
12-30 00:01:27.376: E/SQLiteDatabase(10477): at com.test.MySQLiteOpenHelper.insertData(MySQLiteOpenHelper.java:28)
12-30 00:01:27.376: E/SQLiteDatabase(10477): at com.test.MainActivity.test(MainActivity.java:45)
12-30 00:01:27.446: E/AndroidRuntime(10477): at com.test.MySQLiteOpenHelper.insertData(MySQLiteOpenHelper.java:28)
12-30 00:01:27.446: E/AndroidRuntime(10477): at com.test.MainActivity.test(MainActivity.java:45)
Here are the files, MySQLiteOpenHelper.java :
package com.test;
import java.util.HashMap;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
MySQLiteOpenHelper(Context context) {
super(context, "/data/data/com.otherapplication/databases/records.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public void insertData() {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("id", "testvalue");
database.insert("table", null, values);
database.close();
}
}
MainActivity.java
public class MainActivity extends Activity {
MySQLiteOpenHelper controller = new MySQLiteOpenHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void test(View v) {
controller.insertData();
}
}
I have found the solution:
I did chmod 777 to that application's 'databases' folder and that database file. And now i can insert data from my application.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 6 years ago.
I'm trying to create a basic database and insert three users, but it doesn't work.
This is a class that creates the database
package com.example.matadoor.db1;
import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by matadoor on 06/08/2016.
*/
public class dbcreat extends SQLiteOpenHelper {
public final String tbname="t1";
public final String cid="id";
public static String cid2="test";
public final String user="username";
public final String creat="CREATE TABLE "+cid2+"("+cid+"INTEGER primery key AUTO_INCREMENT , "+user+" TEXT); ";
public dbcreat(Context context) {
super(context,cid2,null, 1);
}
public dbcreat(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
super(context, name, factory, version, errorHandler);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(creat);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
And it's the other class which handles the database - opens it, closes it, and inserts into it
package com.example.matadoor.db1;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
* Created by matadoor on 08/08/2016.
*/
public class dbhandler {
private dbcreat dbc;
private SQLiteDatabase sdb;
public dbhandler(Context context)
{
dbc=new dbcreat(context);
}
public void open()
{
sdb=dbc.getWritableDatabase();
}
public void close(){
dbc.close();
}
public String display(int row)
{
Cursor cu=sdb.query(dbc.tbname,null,null,null,null,null,null);
cu.moveToPosition(row);
String user=cu.getString(1);
return user;
}
public void insert(String user)
{
ContentValues cn=new ContentValues();
cn.put(dbc.user,user);
}
}
And the main class which has one Button for inserting a user into the db
package com.example.matadoor.db1;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Main extends AppCompatActivity {
Button btn;
dbhandler db;
dbcreat dbc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn=(Button)findViewById(R.id.ins);
// dbc.getWritableDatabase();
db.open();
db=new dbhandler(this);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String [] user={"ali","reza","ahmed"};
for(int i=0;i<user.length;i++)
{
db.insert(user[i]);
}
}
});
}
}
So this seems to be a error. You need to switch those two lines.
db.open(); // NullPointer here
db=new dbhandler(this);
Assuming there are no other errors with the code, this method is doing nothing to the database.
public void insert(String user)
{
ContentValues cn=new ContentValues();
cn.put(dbc.user,user);
}
You have to call sdb.insert with that cn variable.
I am new to Android Programming.. I am trying to create sqLite Database in android Here is my code
sqLitee.java
package com.example.sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class sqLitee extends SQLiteOpenHelper
{
public static final String DB_NAME="student.db";
public static final String TABLE_NAME="student";
public static final String COL_1="ID";
public static final String COL_2="FIRST_NAME";
public static final String COL_3="LAST_NAME";
public static final String COL_4="MARKS";
public sqLitee(Context context)
{
super(context, DB_NAME,null, 1);
// TODO Auto-generated constructor stub
SQLiteDatabase db=this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTO INCREMENT, FIRST_NAME TEXT, LAST_NAME TEXT, MARKS INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXIST " + TABLE_NAME);
onCreate(db);
}
}
MainActivity.java
package com.example.sqlite;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
sqLitee myDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDB = new sqLitee(this);
setContentView(R.layout.activity_main);
}
}
When I am trying to run it on Android virtual Device , It says unfortunately , sqLite has stopped..
Thanks
remove this line in your sqllite constructor:
SQLiteDatabase db=this.getWritableDatabase();
you try to get the db, which is currently initializing.
There's a syntax error in your CREATE TABLE SQL. AUTO INCREMENT should be AUTOINCREMENT.
As always, first see the logcat for exception stacktrace and to learn what is failing and where.
i am trying to implement an app in which text entered in edittext is saved to the DB and then is displayed in a text field. But the app is crashing when i try to do this and i get a null pointer exception. This is my code
package com.example.dbex;
import java.sql.SQLOutput;
import java.sql.SQLPermission;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHandler extends SQLiteOpenHelper {
public static final int DATABASE_VERSION=1;
public static final String DATABASE_NAME="contactsmanager";
public static final String TABLE_CONTACTS="contacts";
public static final String KEY_ID="id";
public static final String KEY_NAME="name";
public static final String KEY_NUMBER="number";
public DBHandler(Context context) {
super(context,DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_TABLE_CONTACTS="CREATE TABLE "+TABLE_CONTACTS+"("+KEY_ID+" INTEGER PRIMARY KEY,"+KEY_NAME+" TEXT,"+KEY_NUMBER+" TEXT"+")";
db.execSQL(CREATE_TABLE_CONTACTS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+TABLE_CONTACTS);
onCreate(db);
}
public void addContact(Contacts contacts)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(KEY_NAME, contacts.getname());
values.put(KEY_NUMBER, contacts.getnumber());
db.insert(TABLE_CONTACTS,null,values);
db.close();
}
public Contacts getContact(int id)
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor c=db.query(TABLE_CONTACTS, new String[]{KEY_ID,KEY_NAME,KEY_NUMBER},KEY_ID+" =?",new String[]{String.valueOf(id)}, null, null, null, null);
Contacts contacts=null;
if(c!=null&&c.moveToFirst())
{
contacts=new Contacts(Integer.parseInt(c.getString(0)),c.getString(1),c.getString(2));
}
return contacts;
}
public void deleteContact(Contacts contacts)
{
SQLiteDatabase db=this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID+" =?", new String[]{String.valueOf(contacts.getID())});
db.close();
}
}
and the main activity is
package com.example.dbex;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1=(Button)findViewById(R.id.button1);
EditText et1=(EditText)findViewById(R.id.editText1);
EditText et2=(EditText)findViewById(R.id.editText2);
final TextView tv1=(TextView)findViewById(R.id.textView1);
final String _name=et1.getText().toString();
final String _phone=et2.getText().toString();
final DBHandler dbh=new DBHandler(getBaseContext());
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dbh.addContact(new Contacts(_name, _phone));
String contact1=(dbh.getContact(0)).getname();
tv1.setText(contact1);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
i am getting the null pointer exception in the line
String contact1=(dbh.getContact(0)).getname();
where is my mistake?
thanks
Since you are telling you are able to insert the value, I assume your DB creation is correct You have hardcoded the id being queried to 0. You may not be having any value here. See this post to understand that even when you delete existing rows the auto increment ID could be continuing from the last used value instead of 0. So you could be returning a null value in this part of your code:
Contacts contacts=null;
if(c!=null&&c.moveToFirst())
{
contacts=new Contacts(Integer.parseInt(c.getString(0)),c.getString(1),c.getString(2));
}
return contacts;
I am trying to write a Race database where you would enter a race name, then click on that race name, and edit/delete it.
So I am getting an error in my logcat (error code=1). It tells me there is no table created so I think I am not calling my variables correctly.
//LogCat
12-08 12:46:21.019: I/INFORMATION(650): You entered the insert method
12-08 12:46:21.019: I/Database(650): sqlite returned: error code = 1, msg = no such table: Note
12-08 12:46:21.062: E/Database(650): Error inserting note=ft
12-08 12:46:21.062: E/Database(650): android.database.sqlite.SQLiteException: no such table: Note: , while compiling: INSERT INTO Note(note) VALUES(?);
12-08 12:46:21.062: E/Database(650): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
12-08 12:46:21.062: E/Database(650): at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:92)
12-08 12:46:21.062: E/Database(650): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:65)
//View races java code
package com.CIS2818.tritracker;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class View_races extends Activity {
NoteAdapter adapter=null;
RaceHelper helper2=null;
Cursor dataset_cursor=null;
EditText editNote2=null;
String noteId2=null;
String TAG = "INFORMATION";
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try
{
setContentView(R.layout.activity_view_races);
ListView list2=(ListView)findViewById(R.id.list2);
editNote2 = (EditText)findViewById(R.id.myEditText2);
helper2=new RaceHelper(this);
dataset_cursor=helper2.getAll();
startManagingCursor(dataset_cursor);
adapter=new NoteAdapter(dataset_cursor);
list2.setAdapter(adapter);
Button btnSimple2 = (Button) findViewById(R.id.btnSimple2);
btnSimple2.setOnClickListener(onSave);
Button btnDelete2 = (Button) findViewById(R.id.btnDelete2);
btnDelete2.setOnClickListener(onDelete);
list2.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
helper2.close();
}
private View.OnClickListener onSave=new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
Log.i(TAG,"You passed through the save method");
if (noteId2==null) {
helper2.insert(editNote2.getText().toString());
}
else{
helper2.update(noteId2, editNote2.getText().toString());
noteId2=null;
}
dataset_cursor.requery();
editNote2.setText("");
}
};
private View.OnClickListener onDelete=new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
if (noteId2==null) {
return;
}
else{
helper2.delete(noteId2);
noteId2=null;
}
dataset_cursor.requery();
editNote2.setText("");
}
};
private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position,
long id2)
{
noteId2 =String.valueOf(id2);
Cursor c=helper2.getById(noteId2);
c.moveToFirst();
editNote2.setText(helper2.getNote(c));
}
};
class NoteAdapter extends CursorAdapter {
#SuppressWarnings("deprecation")
NoteAdapter(Cursor c) {
super(View_races.this, c);
}
#Override
public void bindView(View row, Context ctxt,Cursor c) {
NoteHolder2 holder=(NoteHolder2)row.getTag();
holder.populateFrom(c, helper2);
}
#Override
public View newView(Context ctxt, Cursor c,ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.row2, parent, false);
NoteHolder2 holder=new NoteHolder2(row);
row.setTag(holder);
return(row);
}
}
static class NoteHolder2 {
private TextView noteText2=null;
NoteHolder2(View row) {
noteText2=(TextView)row.findViewById(R.id.note2);
}
void populateFrom(Cursor c, RaceHelper helper) {
noteText2.setText(helper.getNote(c));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_view_races, menu);
return true;
}
//Button Method to return to the main Menu
public void Menu(View v){
Intent intent = new Intent(this, MainMenuActivity.class);
startActivity(intent);
}
//Button Method to go to the Race Activity
public void Races(View v){
Intent intent = new Intent(this, UpComingRaceActivity.class);
startActivity(intent);
}}
//RaceHelper java code
package com.CIS2818.tritracker;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
class RaceHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="note2.db";
private static final int SCHEMA_VERSION=1;
String TAG ="INFORMATION";
public RaceHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE Note (_id INTEGER PRIMARY KEY AUTOINCREMENT, note TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insert(String note2) {
Log.i(TAG,"You entered the insert method");
ContentValues cv2=new ContentValues();
cv2.put("note", note2);
getWritableDatabase().insert("Note", "note", cv2);
}
public void update(String id, String note2) {
ContentValues cv2=new ContentValues();
String[] args={id};
cv2.put("note", note2);
getWritableDatabase().update("Note", cv2, "_id=?", args);
}
public void delete(String id2) {
getWritableDatabase().delete("Note", "_id=?", new String[] {id2});
}
public Cursor getAll() {
return(getReadableDatabase()
.rawQuery("SELECT _id, note FROM Notes",
null));
}
public String getNote(Cursor c2) {
return(c2.getString(1));
}
public Cursor getById(String id2) {
String[] args={id2};
return(getReadableDatabase()
.rawQuery("SELECT _id, note FROM Note WHERE _id=?",
args));
}
}
It appears you have changed your SQL schema in your Java code but haven't informed SQLite. In order for your SQLiteOpenHelper class to use the new schema you provided in onCreate(), you need to upgrade your database. This is the most basic approach.
First add some functionality to onUpgrade():
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS Note");
onCreate(db);
}
Now increment SCHEMA_VERSION to trigger an upgrade:
private static final int SCHEMA_VERSION=2;
Understand that SQLiteOpenHelper does not check the code inside onCreate() for you, you must tell SQLite there is a change by incrementing SCHEMA_VERSION.
In your insert method make the second value null. For example getWritableDatabase().insert("Note",null,cv2);
I have the same question as yours.I solved it.At first I rename the table that I create but do nothing with the CREATE_DATABASE order.Then I notice it. Although I corrected the order it does not works.So I add the onUpgrade method, and increment DATABASE_VERSION to a higher number,it works!!!Hope it works also for you.
I'm newbie to android. I have gone through the android docs and I googled it, but I'm confused why my code is returning a no such table error.
I want to create a DB named as demo and I want to create a table student with three columns.
Here's my code:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
static final String dbName="demo";
public DatabaseHelper(Context context) {
super(context, dbName, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("Create table IF NOT EXISTS student(title text,address text,gender text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public void insert_datas(String title,String artist,String patharray,String table_name){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put("title",title);
initialValues.put("address",address);
initialValues.put("gender",gender);
long n = db.insert(table_name,title,initialValues);
System.out.println("n"+n);
db.close();
}
public Cursor get_datas(){
SQLiteDatabase db=this.getReadableDatabase();
Cursor cur=db.rawQuery("SELECT * FROM student",null);
return cur;
}
}
and this how i m call the DatabaseHelper class:
public class MYActivity extends Activity{
DatabaseHelper dbAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customlist);
dbAdapter = new DatabaseHelper(this);
dbAdapter.insert_datas("test","test","test","student");
}
}
My error
**11-26 02:10:00.210: INFO/SqliteDatabaseCpp(27151): sqlite returned: error code = 1, msg = no such table: student, db=/data/data/com.player.activites/databases/demo
11-26 02:10:00.210: ERROR/SQLiteDatabase(27151): android.database.sqlite.SQLiteException: no such table: student: , while compiling: INSERT INTO studenty(title,address,gender) VALUES (?,?,?)**
Thanks
Try upgrading the database version number (right now you have it as 1). Is it possible you ran your app and tried to access the DB before your helper's onCreate actually did anything? If you did that, you would have an empty DB at version 1. If you don't want to increment your version numbers, you could alternatively uninstall your app or clear its data to delete the DB file entirely.