I am creating a landscape layout using fragment class. But now my code is showing error in my listMovieActivity file. I tried following some answers from stackoverflow but that didnt help me on it.
This is my listMovieActivity code:
package com.example.moviemanager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
public class listMovieActivity extends FragmentActivity {
private MovieDetailFragment detailFragment = null;
private MovieListFragment listFragment = null;
private FragmentManager manager;
private int selectedItemIndex = -1;
private String title=null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listmovie);
manager = getSupportFragmentManager();
detailFragment = (MovieDetailFragment) manager.findFragmentById(R.id.detailmovie_fragment);
listFragment = (MovieListFragment) manager.findFragmentById(R.id.listmovie_fragment);
}
public boolean onCreateOptionsMenu(android.view.Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
protected void onResume() {
super.onResume();
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE)
showDetails(selectedItemIndex,title);
}
public void showDetails(int selectedItem, String ttl) {
//Log.d("FRAGMENT", "Selected item " + selectedItem);
selectedItemIndex = selectedItem;
title = ttl;
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (detailFragment != null) {
// update entry
detailFragment.updateDetails(selectedItem,ttl);
}
} else {
// show DetailsActivity
Intent intent = new Intent(this, DetailMovie.class);
intent.putExtra("POSITION", selectedItem);
intent.putExtra("TITLE", ttl);
startActivity(intent);
}
}
}
This is my DatabaseHandler code:
public class DatabaseHandler {
String cmd;
private static final String DBTAG = "DatabaseHandler";
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_KEY = "key";
public static final String KEY_TITLE = "title";
public static final String KEY_TYPE = "type";
public static final String KEY_STORY = "story";
public static final String KEY_RATING = "rating";
public static final String KEY_LANGUAGE = "language";
public static final String KEY_RUNTIME = "runtime";
public static final int COL_KEY = 1;
public static final int COL_TITLE = 2;
public static final int COL_TYPE = 3;
public static final int COL_STORY = 4;
public static final int COL_RATING = 5;
public static final int COL_LANGUAGE = 6;
public static final int COL_RUNTIME = 7;
public static final String[] ALL_KEYS = new String[] {
KEY_ROWID, KEY_KEY, KEY_TITLE, KEY_TYPE, KEY_STORY,
KEY_RATING, KEY_LANGUAGE, KEY_RUNTIME};
public static final String DATABASE_NAME = "movieDb";
public static final String DATABASE_TABLE = "movieTable";
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement,"
+ KEY_KEY + " text not null,"
+ KEY_TITLE + " text not null,"
+ KEY_TYPE + " text not null,"
+ KEY_STORY + " text not null,"
+ KEY_RATING + " text not null,"
+ KEY_LANGUAGE + " text not null,"
+ KEY_RUNTIME + " integer not null"
+ ");";
private final Context context;
private DatabaseHelper dbHelper;
private SQLiteDatabase db;
public DatabaseHandler(Context ctx){
this.context = ctx;
dbHelper = new DatabaseHelper(context);
}
public DatabaseHandler open(){
db = dbHelper.getWritableDatabase();
return this;
}
public void close(){
dbHelper.close();
}
public void insertRow(String mvkey, String mvtitle, String mvtype,
String mvstory, String mvrating, String mvlanguage, int mvruntime){
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_KEY, mvkey);
initialValues.put(KEY_TITLE, mvtitle);
initialValues.put(KEY_TYPE, mvtype);
initialValues.put(KEY_STORY, mvstory);
initialValues.put(KEY_RATING, mvrating);
initialValues.put(KEY_LANGUAGE, mvlanguage);
initialValues.put(KEY_RUNTIME, mvruntime);
open();
db.insert(DATABASE_TABLE, null, initialValues);
close();
}
public void deleteRow(long rowId){
open();
cmd = new String ("DELETE FROM " + DATABASE_TABLE + " WHERE ( "+KEY_ROWID+" =" + rowId + " );");
db.execSQL(cmd);
close();
// String where = KEY_ROWID + "=" + rowId;
// return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll(){
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if(c.moveToFirst()){
do{
deleteRow(c.getLong((int)rowId));
}while(c.moveToNext());
}
c.close();
}
public Cursor getAllRows(){
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
if(c!= null){
c.moveToFirst();
}
return c;
}
public Cursor getRow(long rowId){
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
if(c!= null){
c.moveToFirst();
}
return c;
}
public boolean updateRow(long rowId, String mvkey, String mvtitle,
String mvtype, String mvstory, String mvrating,
String mvlanguage, int mvruntime){
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_KEY, mvkey);
newValues.put(KEY_TITLE, mvtitle);
newValues.put(KEY_TYPE, mvtype);
newValues.put(KEY_STORY, mvstory);
newValues.put(KEY_RATING, mvrating);
newValues.put(KEY_LANGUAGE, mvlanguage);
newValues.put(KEY_RUNTIME, mvruntime);
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
public Cursor listMovieTitle(){
return db.rawQuery("SELECT "+ KEY_TITLE + " FROM " + DATABASE_TABLE,null);
}
public Cursor get_id(String ttl){
return db.rawQuery("SELECT "+ KEY_ROWID + " FROM " + DATABASE_TABLE + " WHERE (" + KEY_TITLE + " = " + ttl + " );",null);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(DBTAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
This is the error stack trace i am receiving each time i click on my display button:
04-04 01:00:15.314 811-811/com.example.moviemanager E/Trace﹕ error opening trace file: No such file or directory (2)
04-04 01:01:15.098 859-859/com.example.moviemanager E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.moviemanager/com.example.moviemanager.listMovieActivity}: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:270)
at android.app.Activity.setContentView(Activity.java:1881)
at com.example.moviemanager.listMovieActivity.onCreate(listMovieActivity.java:20)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.example.moviemanager.DatabaseHandler.open(DatabaseHandler.java:65)
at com.example.moviemanager.MovieListFragment.onCreateView(MovieListFragment.java:29)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1478)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:900)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1082)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1184)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:285)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:676)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:270)
at android.app.Activity.setContentView(Activity.java:1881)
at com.example.moviemanager.listMovieActivity.onCreate(listMovieActivity.java:20)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
04-04 01:01:19.447 879-879/com.example.moviemanager E/Trace﹕ error opening trace file: No such file or directory (2)
Previously, I had the same problem error inflating class fragment, but then I solved it by changing my android listview id to android custome list id. But now the problem is appearing again but this time its worst my databasehandler also is showing error it seems. Can any help me on this.
In DatabaseHandler:
private final Context context;
This makes no sense, the final field cannot be assigned.And how can you make it pass the check?
Put up MovieListFragment code, please.
Related
I was altering my database structure as I noticed some things weren't in the right order. After doing so, it flashes up an error saying
02-10 19:42:06.562: E/AndroidRuntime(1215): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.project/com.example.project.MainActivity}: java.lang.NumberFormatException: Invalid int: "T"
"T" is what I used for my previous test data, so I presumed it was the previous data that's already in the database now flagging errors as the columns have changed around.
I thought if I deleted the database at the very beginning of onCreate() then it would clear the database and insert the new test data and getting rid of the errors. However I still get exactly the same error!
Full Code Below:
MainActivity.java
public class MainActivity extends Activity {
Intent appIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DB db = new DB(this);
db.insertStudent("Matt", "male", 22, "password", "computing", "modules");
List<tableStudents> outputList = db.getData();
for (tableStudents student: outputList) {
// Log your results.
Log.d("result_list", student.toString());
}
}
public void goHomepage(View v)
{
Intent intent = new Intent(MainActivity.this, Homepage.class);
startActivity(intent);
}
public void goAccount(View v)
{
Intent intent = new Intent(MainActivity.this, MyAccount.class);
startActivity(intent);
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
DB.java
public class DB extends SQLiteOpenHelper {
public static final int db_version = 1;
public static final String Table = "Students";
public static final String Student_ID = "Student_ID";
public static final String Student_Name = "Student_Name";
public static final String Student_Password = "Student_Password";
public static final String Student_Gender = "gender";
public static final String Student_Age = "age";
public static final String Student_Course = "course";
public static final String Modules = "modules";
public DB(Context context) {
super(context, tableColumns.Database, null, db_version);
}
#Override
public void onCreate(SQLiteDatabase db) {
delete(db);
//Create Table
db.execSQL("CREATE TABLE " + Table + "(" +
Student_ID + " INTEGER PRIMARY KEY, " +
Student_Name + " TEXT, " +
Student_Password + " TEXT, " +
Student_Gender + " TEXT, " +
Student_Age + " INTEGER, " +
Student_Course + " TEXT, " +
Modules + " TEXT)");
Log.d("DB", "DB Created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Table);
onCreate(db);
}
public void delete(SQLiteDatabase db)
{
db.delete(Table, null, null);
}
public List<tableStudents> getData() {
List<tableStudents> studentList = new ArrayList<tableStudents>();
// Select All Query
String selectQuery = "SELECT * FROM " + Table;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tableStudents student = new tableStudents();
student.name = cursor.getString(0);
student.gender = cursor.getString(1);
student.age = Integer.parseInt(cursor.getString(2));
student.password = cursor.getString(3);
student.course = cursor.getString(4);
student.modules = cursor.getString(5);
studentList.add(student);
} while (cursor.moveToNext());
}
// return contact list
return studentList;
}
public boolean insertStudent(String name, String gender, int age, String password, String course, String modules) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Student_Name, name);
contentValues.put(Student_Password, password);
contentValues.put(Student_Gender, gender);
contentValues.put(Student_Age, age);
contentValues.put(Student_Course, course);
contentValues.put(Modules, modules);
db.insert(Table, null, contentValues);
Log.d("DB", "Inserted Successfully");
return true;
}
}
tableStudents.java
public class tableStudents {
public String name, gender, password, course, modules;
public int age;
//Constructor
public tableStudents()
{
}
//constructor
public tableStudents(String name, String gender, int age, String password, String course, String modules)
{
this.name = name;
this.password = password;
this.gender = gender;
this.age = age;
this.course = course;
this.modules = modules;
}
public static abstract class tableColumns implements BaseColumns
{
public static final String Student_ID= "Student_ID";
public static final String Student_Name= "Student_Name";
public static final String Student_Password = "Student_Password";
public static final String Student_Gender = "gender";
public static final String Student_Age = "age";
public static final String Student_Course = "course";
public static final String Modules = "modules";
public static final String Database = "databasename";
public static final String Table = "tablename";
}
}
LogCat
02-10 19:56:42.132: D/DB(1741): Inserted Successfully
02-10 19:56:42.142: D/AndroidRuntime(1741): Shutting down VM
02-10 19:56:42.147: E/AndroidRuntime(1741): FATAL EXCEPTION: main
02-10 19:56:42.147: E/AndroidRuntime(1741): Process: com.example.project, PID: 1741
02-10 19:56:42.147: E/AndroidRuntime(1741): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.project/com.example.project.MainActivity}: java.lang.NumberFormatException: Invalid int: "T"
02-10 19:56:42.147: E/AndroidRuntime(1741): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
02-10 19:56:42.147: E/AndroidRuntime(1741): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
02-10 19:56:42.147: E/AndroidRuntime(1741): at android.app.ActivityThread.access$800(ActivityThread.java:151)
02-10 19:56:42.147: E/AndroidRuntime(1741): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
02-10 19:56:42.147: E/AndroidRuntime(1741): at android.os.Handler.dispatchMessage(Handler.java:102)
02-10 19:56:42.147: E/AndroidRuntime(1741): at android.os.Looper.loop(Looper.java:135)
02-10 19:56:42.147: E/AndroidRuntime(1741): at android.app.ActivityThread.main(ActivityThread.java:5257)
02-10 19:56:42.147: E/AndroidRuntime(1741): at java.lang.reflect.Method.invoke(Native Method)
02-10 19:56:42.147: E/AndroidRuntime(1741): at java.lang.reflect.Method.invoke(Method.java:372)
02-10 19:56:42.147: E/AndroidRuntime(1741): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
02-10 19:56:42.147: E/AndroidRuntime(1741): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
02-10 19:56:42.147: E/AndroidRuntime(1741): Caused by: java.lang.NumberFormatException: Invalid int: "T"
02-10 19:56:42.147: E/AndroidRuntime(1741): at java.lang.Integer.invalidInt(Integer.java:138)
02-10 19:56:42.147: E/AndroidRuntime(1741): at java.lang.Integer.parse(Integer.java:410)
02-10 19:56:42.147: E/AndroidRuntime(1741): at java.lang.Integer.parseInt(Integer.java:367)
02-10 19:56:42.147: E/AndroidRuntime(1741): at java.lang.Integer.parseInt(Integer.java:334)
02-10 19:56:42.147: E/AndroidRuntime(1741): at com.example.project.DB.getData(DB.java:72)
02-10 19:56:42.147: E/AndroidRuntime(1741): at com.example.project.MainActivity.onCreate(MainActivity.java:31)
02-10 19:56:42.147: E/AndroidRuntime(1741): at android.app.Activity.performCreate(Activity.java:5990)
02-10 19:56:42.147: E/AndroidRuntime(1741): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
02-10 19:56:42.147: E/AndroidRuntime(1741): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
try this in the begining of onCreate():
deleteDatabase("your_db_name");
have you tried delete data of the application and then run it again?
I need to use a SQLite Database on my android app but when I try and open it, it crashes and I cannot figure out why. I have had a look online for the past hour and a bit but cannot find any help.
Here is the code:
public class PrivDB {
public static final String KEY_ROWID = "_id";
public static final String KEY_LEVEL = "level";
public static final String KEY_LOCKED = "locked";
public static final String KEY_SEQUENCE = "sequence";
public static final String KEY_TRIES = "tries";
private static final String DATABASE_NAME = "patdb";
private static final String DATABASE_TABLE = "tablename";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
arg0.execSQL("CREATE TABLE " + DATABASE_TABLE + " ("+
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
KEY_LEVEL + " STRING NOT NULL, " +
KEY_LOCKED + " INTEGER NOT NULL, " +
KEY_SEQUENCE + " INTEGER NOT NULL, "+
KEY_TRIES + " INTEGER NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
arg0.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(arg0);
}
}
public PrivDB (Context c) {
ourContext = c;
}
public PrivDB open() throws SQLException {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry (String level, int locked, int sequence, int tries){
ContentValues cv = new ContentValues();
cv.put(KEY_LEVEL, level);
cv.put(KEY_LOCKED, locked);
cv.put(KEY_SEQUENCE, sequence);
cv.put(KEY_TRIES, tries);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
String[] columns = new String[]{KEY_ROWID, KEY_LEVEL, KEY_LOCKED, KEY_SEQUENCE, KEY_TRIES};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iLevel = c.getColumnIndex(KEY_LEVEL);
int iLocked = c.getColumnIndex(KEY_LOCKED);
int iSequence = c.getColumnIndex(KEY_SEQUENCE);
int iTries = c.getColumnIndex(KEY_TRIES);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iLevel) + " " + c.getString(iLocked) + " "
+ c.getString(iSequence) + c.getString(iTries) + "\n";
}
return result;
}
public int getLocked(String s) throws SQLException {
String[] columns = new String[]{KEY_ROWID, KEY_LEVEL, KEY_LOCKED, KEY_SEQUENCE, KEY_TRIES};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_LEVEL + "=" + s, null, null, null, null);
if(c != null){
c.moveToFirst();
int locked = c.getInt(2);
return locked;
}
return (Integer) null;
}
public void updateEntry(String s, int locked, int tries) throws SQLException {
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_LOCKED, locked);
cvUpdate.put(KEY_TRIES, tries);
ourDatabase.update(DATABASE_TABLE, cvUpdate, KEY_LEVEL + "=" + s, null);
}
}
and how I am calling the database:
public class Stats extends Activity {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
tv = (TextView) findViewById(R.id.tvStats);
PrivDB info = new PrivDB(this);
info.open();
String data = info.getData();
info.close();
tv.setText(data);
}
}
When I open the Stats class, the app crashes, but if I comment out the info.open() until the info.close() then it works fine (but obviously nothing happens).
UPDATE
here is the log cat output:
01-09 13:16:32.786: E/AndroidRuntime(517): FATAL EXCEPTION: main
01-09 13:16:32.786: E/AndroidRuntime(517): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.docime.vamoose.patternz/com.docime.vamoose.patternz.Stats}: java.lang.StringIndexOutOfBoundsException
01-09 13:16:32.786: E/AndroidRuntime(517): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.os.Handler.dispatchMessage(Handler.java:99)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.os.Looper.loop(Looper.java:123)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-09 13:16:32.786: E/AndroidRuntime(517): at java.lang.reflect.Method.invokeNative(Native Method)
01-09 13:16:32.786: E/AndroidRuntime(517): at java.lang.reflect.Method.invoke(Method.java:521)
01-09 13:16:32.786: E/AndroidRuntime(517): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-09 13:16:32.786: E/AndroidRuntime(517): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-09 13:16:32.786: E/AndroidRuntime(517): at dalvik.system.NativeStart.main(Native Method)
01-09 13:16:32.786: E/AndroidRuntime(517): Caused by: java.lang.StringIndexOutOfBoundsException
01-09 13:16:32.786: E/AndroidRuntime(517): at android.app.ContextImpl.validateFilePath(ContextImpl.java:1579)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:539)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:203)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:98)
01-09 13:16:32.786: E/AndroidRuntime(517): at com.docime.vamoose.patternz.PrivDB.open(PrivDB.java:60)
01-09 13:16:32.786: E/AndroidRuntime(517): at com.docime.vamoose.patternz.Stats.onCreate(Stats.java:18)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-09 13:16:32.786: E/AndroidRuntime(517): ... 11 more
You never pass DATABASE_TABLE name or assign it in you code. that's why it's crashing.
private static final String DATABASE_TABLE = "TABLE_NAME";
Update: do update your onCreate(). SQLite suport TEXT instedOf String
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
arg0.execSQL("CREATE TABLE " + DATABASE_TABLE + " ( "+
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
KEY_LEVEL + " TEXT NOT NULL, " +
KEY_LOCKED + " INTEGER NOT NULL, " +
KEY_SEQUENCE + " INTEGER NOT NULL, "+
KEY_TRIES + " INTEGER NOT NULL);");
}
Another important things you are passing the context but not saving it using static variable.
You should use like following
private static Context ourContext;
public PrivDB (Context c) {
this.ourContext = c;
}
But above all, as you are facing the error/ exception
Caused by: java.lang.StringIndexOutOfBoundsException ,
This Thrown when the a string is indexed with a value less than zero, or greater than or equal to the size of the array
I would request you to check the following so- java.lang.StringIndexOutOfBoundsException: index=0 length=0 in get sqlite database
change STRING to TEXT in below
arg0.execSQL("CREATE TABLE " + DATABASE_TABLE + " ("+
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
KEY_LEVEL + " STRING NOT NULL, " +
KEY_LOCKED + " INTEGER NOT NULL, " +
KEY_SEQUENCE + " INTEGER NOT NULL, "+
KEY_TRIES + " INTEGER NOT NULL);");
NOTE :After change please add one to your database version
I think your info is pointing to null
Try this code :
if (null != info)
{
info.open();
String data = info.getData();
info.close();
}else
Log.d("App Name", "Info is null");
One more thing for getData() function you are reading the database
so u should open the database in read mode.
ourDatabase = ourHelper.getWritableDatabase(); To
ourDatabase = ourHelper.getReadableDatabase();
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
arg0.execSQL("CREATE TABLE " + DATABASE_TABLE + " ("+
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
KEY_LEVEL + " STRING NOT NULL, " +
KEY_LOCKED + " INTEGER NOT NULL, " +
KEY_SEQUENCE + " INTEGER NOT NULL, "+
KEY_TRIES + " INTEGER NOT NULL);");
}
This line KEY_TRIES + " INTEGER NOT NULL);"); has two ;.Does your table get created/populated?
I want to retrieve all the data whose status is open in my database so that I have use LIKE command in my android application with SQLite Database.
But when I run the app I'm getting NullPointerException at the line of searchList . setAdapter (new_Lead_List_Adapter).
Here is my Database Adapter Class
public class DataBase_Adapter
{
//Database NAme
static final String DATABASE_NAME = "lead_management.db";
//Database Version
static final int DATABASE_VERSION = 4;
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public DataBase_Adapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public DataBase_Adapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
//Table name
public static String TABLE_NEW_LEAD="new_lead";
//Creating New Lead Table Columns
public static final String KEY_NEW_LEAD_ID ="id";
public static final String KEY_NEW_LEAD_NAME ="name";
public static final String KEY_NEW_LEAD_EMAIL ="email";
public static final String KEY_NEW_LEAD_MOBILE="mobile";
public static final String KEY_NEW_LEAD_Product="define_products";
public static final String KEY_NEW_LEAD_BUDGET="budget";
public static final String KEY_NEW_LEAD_PRIORITY="priority";
public static final String KEY_NEW_LEAD_STATUS="status";
public static final String KEY_NEW_LEAD_NOTES="notes";
public static final String KEY_NEW_LEAD_REMINDER_DATE="reminder_date";
public static final String KEY_NEW_LEAD_REMINDER_TIME="reminder_time";
public static final String KEY_NEW_LEAD_ADDtoCONTACTS="add_to_contacts";
//// SQL Statement to create a New Lead Database.
static final String CREATE_NEW_LEAD_TABLE = "CREATE TABLE "+ TABLE_NEW_LEAD + "("
+ KEY_NEW_LEAD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_NEW_LEAD_NAME + " TEXT,"
+ KEY_NEW_LEAD_EMAIL + " TEXT,"
+ KEY_NEW_LEAD_MOBILE+ " TEXT,"
+ KEY_NEW_LEAD_Product + " TEXT,"
+ KEY_NEW_LEAD_BUDGET + " TEXT,"
+ KEY_NEW_LEAD_PRIORITY +" TEXT,"
+ KEY_NEW_LEAD_STATUS + " TEXT,"
+ KEY_NEW_LEAD_NOTES + " TEXT,"
+ KEY_NEW_LEAD_REMINDER_DATE + " TEXT,"
+ KEY_NEW_LEAD_REMINDER_TIME + " TEXT,"
+ KEY_NEW_LEAD_ADDtoCONTACTS + " TEXT"+");";
//");";
//Insert New Record In New Lead Table
public void insert_NewLead_Entry(New_Lead_BeanClass newLead_BeanClass)
{
SQLiteDatabase sdb = dbHelper.getWritableDatabase();
ContentValues contentNewLead_Val=new ContentValues();
contentNewLead_Val.put(KEY_NEW_LEAD_NAME, newLead_BeanClass.get_Name());
contentNewLead_Val.put(KEY_NEW_LEAD_EMAIL, newLead_BeanClass.get_Email());
contentNewLead_Val.put(KEY_NEW_LEAD_MOBILE, newLead_BeanClass.get_MobileNo());
contentNewLead_Val.put(KEY_NEW_LEAD_Product, newLead_BeanClass.get_Product());
contentNewLead_Val.put(KEY_NEW_LEAD_BUDGET, newLead_BeanClass.get_Budget());
contentNewLead_Val.put(KEY_NEW_LEAD_PRIORITY, newLead_BeanClass.get_Priority());
contentNewLead_Val.put(KEY_NEW_LEAD_STATUS, newLead_BeanClass.get_Status());
contentNewLead_Val.put(KEY_NEW_LEAD_NOTES, newLead_BeanClass.get_Notes());
contentNewLead_Val.put(KEY_NEW_LEAD_REMINDER_DATE, newLead_BeanClass.get_Reminder_Date());
contentNewLead_Val.put(KEY_NEW_LEAD_REMINDER_TIME, newLead_BeanClass.get_Reminder_Time());
contentNewLead_Val.put(KEY_NEW_LEAD_ADDtoCONTACTS, newLead_BeanClass.get_AddtoContact());
sdb.insert(TABLE_NEW_LEAD , null , contentNewLead_Val );
//Close The Database Connection
sdb.close();
}
public ArrayList<HashMap<String,String>> getAllUserData()
{
ArrayList<HashMap<String,String>> newLeadDat_Listl;
newLeadDat_Listl = new ArrayList<HashMap<String,String>>();
SQLiteDatabase sdatabase = dbHelper.getWritableDatabase();
String selectQuery= "SELECT * FROM" + TABLE_NEW_LEAD ;
Cursor cursor = sdatabase.rawQuery(selectQuery, null);
if (cursor.moveToFirst())
{
do
{
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_NEW_LEAD_ID, cursor.getString(0));
map.put(KEY_NEW_LEAD_NAME, cursor.getString(1));
map.put(KEY_NEW_LEAD_EMAIL, cursor.getString(2));
map.put(KEY_NEW_LEAD_MOBILE, cursor.getString(3));
map.put(KEY_NEW_LEAD_Product, cursor.getString(4));
map.put(KEY_NEW_LEAD_BUDGET, cursor.getString(5));
map.put(KEY_NEW_LEAD_PRIORITY, cursor.getString(6));
map.put(KEY_NEW_LEAD_STATUS, cursor.getString(7));
map.put(KEY_NEW_LEAD_NOTES, cursor.getString(8));
map.put(KEY_NEW_LEAD_REMINDER_DATE, cursor.getString(9));
map.put(KEY_NEW_LEAD_REMINDER_TIME, cursor.getString(10));
map.put(KEY_NEW_LEAD_ADDtoCONTACTS, cursor.getString(11));
newLeadDat_Listl.add(map);
}
while (cursor.moveToNext());
}
return newLeadDat_Listl;
}
}
Here is my Activity code
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.search_data);
searchSpinner=(Spinner)findViewById(R.id.searchSpinner);
searchBtn=(ImageButton)findViewById(R.id.searchButton);
searchSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View v,
int position, long id) {
// TODO Auto-generated method stub
selectedSearchItem=parent.getItemAtPosition(position).toString().trim();
System.out.println("selectedProductItem =" + selectedSearchItem);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
searchBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
displayNewLeadData();
}
});
}
public void displayNewLeadData()
{
dbAdapter=new DataBase_Adapter(Serach_Data.this).open();
dataBase = dbAdapter.getDatabaseInstance();
//Cursor mCursor = dataBase.rawQuery("SELECT name FROM " + DataBase_Adapter.TABLE_NEW_LEAD, null);
cursor = dataBase.rawQuery("SELECT id, name, priority, status FROM new_lead WHERE status LIKE ?",
new String[]{ selectedSearchItem + "%"});
cursor.moveToFirst();
arrayList_newLead_Id.clear();
arrayList_newLead_Name.clear();
arrayList_newLead_Priority.clear();
arrayList_newLead_Status.clear();
{
do
{
arrayList_newLead_Id.add(cursor.getString(cursor.getColumnIndex(DataBase_Adapter.KEY_NEW_LEAD_ID)));
arrayList_newLead_Name.add(cursor.getString(cursor.getColumnIndex(DataBase_Adapter.KEY_NEW_LEAD_NAME)));
arrayList_newLead_Priority.add(cursor.getString(cursor.getColumnIndex(DataBase_Adapter.KEY_NEW_LEAD_PRIORITY)));
arrayList_newLead_Status.add(cursor.getString(cursor.getColumnIndex(DataBase_Adapter.KEY_NEW_LEAD_STATUS)));
} while (cursor.moveToNext());
}
new_Lead_List_Adapter = new New_Lead_List_Adapter(Serach_Data.this ,
arrayList_newLead_Id,
arrayList_newLead_Name ,
arrayList_newLead_Priority,
arrayList_newLead_Status);
searchList.setAdapter(new_Lead_List_Adapter);
new_Lead_List_Adapter.notifyDataSetChanged();
cursor.close();
System.out.printf("Data will Be Display." , new_Lead_List_Adapter);
}
}
Here is my Adapter Class
public class New_Lead_List_Adapter extends BaseAdapter
{
Context mContext;
protected New_Lead_List_Adapter(Context mContext,
ArrayList<String> newLead_ArrayList_ID,
ArrayList<String> newLead_ArrayList_Name,
ArrayList<String> newLead_ArrayList_Pririty,
ArrayList<String> newLead_ArrayList_Status)
{
this.mContext = mContext;
this.newLead_ArrayList_ID = newLead_ArrayList_ID;
this.newLead_ArrayList_Name = newLead_ArrayList_Name;
this.newLead_ArrayList_Pririty = newLead_ArrayList_Pririty;
this.newLead_ArrayList_Status = newLead_ArrayList_Status;
}
ArrayList<String> newLead_ArrayList_ID;
ArrayList<String> newLead_ArrayList_Name;
ArrayList<String> newLead_ArrayList_Pririty;
ArrayList<String> newLead_ArrayList_Status;
protected New_Lead_List_Adapter() {
super();
// TODO Auto-generated constructor stub
}
//#Override
public int getCount() {
// TODO Auto-generated method stub
return newLead_ArrayList_Name.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View child, ViewGroup parent) {
// TODO Auto-generated method stub
Holder mHolder;
LayoutInflater layoutInflater;
if(child == null)
{
layoutInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater .inflate(R.layout.search_data_item_listview, null);
mHolder = new Holder();
mHolder.txt_newLead_ID=(TextView)child.findViewById(R.id.txtId);
mHolder.txt_newLead_Name=(TextView)child.findViewById(R.id.textView2_Name);
mHolder.txt_newLead_Priority=(TextView)child.findViewById(R.id.textView7Priority);
mHolder.txt_newLead_Status=(TextView)child.findViewById(R.id.textView8_Status);
child.setTag(mHolder);
}
else
{
mHolder = (Holder) child.getTag();
}
mHolder.txt_newLead_ID.setText(newLead_ArrayList_ID.get(position));
mHolder.txt_newLead_Name.setText(newLead_ArrayList_Name.get(position));
mHolder.txt_newLead_Priority.setText(newLead_ArrayList_Pririty.get(position));
mHolder.txt_newLead_Status.setText(newLead_ArrayList_Status.get(position));
return child;
}
public class Holder
{
TextView txt_newLead_ID;
TextView txt_newLead_Name;
TextView txt_newLead_Priority;
TextView txt_newLead_Status;
}
}
And the Log Cat Stack Trace info.
12-14 11:22:30.184: E/AndroidRuntime(7872): FATAL EXCEPTION: main
12-14 11:22:30.184: E/AndroidRuntime(7872): java.lang.NullPointerException
12-14 11:22:30.184: E/AndroidRuntime(7872): at com.lead_management_project.Serach_Data.displayNewLeadData(Serach_Data.java:142)
12-14 11:22:30.184: E/AndroidRuntime(7872): at com.lead_management_project.Serach_Data$2.onClick(Serach_Data.java:84)
12-14 11:22:30.184: E/AndroidRuntime(7872): at android.view.View.performClick(View.java:2485)
12-14 11:22:30.184: E/AndroidRuntime(7872): at android.view.View$PerformClick.run(View.java:9080)
12-14 11:22:30.184: E/AndroidRuntime(7872): at android.os.Handler.handleCallback(Handler.java:587)
12-14 11:22:30.184: E/AndroidRuntime(7872): at android.os.Handler.dispatchMessage(Handler.java:92)
12-14 11:22:30.184: E/AndroidRuntime(7872): at android.os.Looper.loop(Looper.java:123)
12-14 11:22:30.184: E/AndroidRuntime(7872): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-14 11:22:30.184: E/AndroidRuntime(7872): at java.lang.reflect.Method.invokeNative(Native Method)
12-14 11:22:30.184: E/AndroidRuntime(7872): at java.lang.reflect.Method.invoke(Method.java:507)
12-14 11:22:30.184: E/AndroidRuntime(7872): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-14 11:22:30.184: E/AndroidRuntime(7872): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-14 11:22:30.184: E/AndroidRuntime(7872): at dalvik.system.NativeStart.main(Native Method)
I'm creating an Android app in Android Studio which implements a custom ContentProvider. For some reason, whenever I go to compile the app and test it out on an emulator, I'm getting this error message:
11-17 21:12:29.918 1381-1381/com.aiorsoft.encryptic E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to get provider com.aiorsoft.encryptic.providers.AccountProvider: java.lang.ClassNotFoundException: Didn't find class "com.aiorsoft.encryptic.providers.AccountProvider" on path: DexPathList[[zip file "/data/app/com.aiorsoft.encryptic-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.aiorsoft.encryptic-2, /system/lib]]
at android.app.ActivityThread.installProvider(ActivityThread.java:4882)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4485)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4425)
at android.app.ActivityThread.access$1300(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.aiorsoft.encryptic.providers.AccountProvider" on path: DexPathList[[zip file "/data/app/com.aiorsoft.encryptic-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.aiorsoft.encryptic-2, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:53)
at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
at android.app.ActivityThread.installProvider(ActivityThread.java:4867)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4485)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4425)
at android.app.ActivityThread.access$1300(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
I've done a bit of background research into this, but have yet to come across a solution to my problem. I'm not using ProGuard in this project, so that rules out anything not being kept by that service. Can anyone help me out with this issue? I may be missing something that's obvious and staring me right in the face, but I can't find it. Thank you for any help! I've included the relevant files below.
Here's my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aiorsoft.encryptic"
android:installLocation="preferExternal"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/title_app_name"
android:theme="#style/Theme.Encryptic">
<activity android:name=".activities.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".services.ConnectionService"
android:exported="false" />
<provider
android:name=".providers.AccountProvider"
android:authorities=".providers" />
</application>
</manifest>
And the provider itself:
package com.aiorsoft.encryptic.providers;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;
public class AccountProvider extends ContentProvider {
private static final String AUTHORITY = "com.aiorsoft.encryptic.providers";
private static final String DATABASE_NAME = "accounts";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + DATABASE_NAME);
private static final int DATABASE_VERSION = 1;
private static final String TABLE_ACCOUNTS = "Account";
private static final int ACCOUNTS_ALL = 1;
private static final int ACCOUNTS_SINGLE = 2;
private interface AccountColumns extends BaseColumns {
public static final String _ID = BaseColumns._ID;
public static final String USERNAME = "username";
public static final String EMAIL = "email";
public static final String TOKEN = "token";
}
private static final String[] ALL_COLUMNS = new String[] {
AccountColumns._ID, AccountColumns.USERNAME, AccountColumns.EMAIL, AccountColumns.TOKEN
};
private static final String CREATE_SQL = "CREATE TABLE "
+ TABLE_ACCOUNTS + " ("
+ AccountColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ AccountColumns.USERNAME + " TEXT NOT NULL, "
+ AccountColumns.EMAIL + " TEXT, "
+ AccountColumns.TOKEN + " TEXT);";
private static final String USERNAME_INDEX_SQL = "CREATE INDEX "
+ AccountColumns.USERNAME + "_idx ON " + TABLE_ACCOUNTS + " ("
+ AccountColumns.USERNAME + " ASC);";
private static UriMatcher uriMatcher;
private DatabaseHelper dbHelper;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, DATABASE_NAME, ACCOUNTS_ALL);
uriMatcher.addURI(AUTHORITY, DATABASE_NAME + "/#", ACCOUNTS_SINGLE);
}
#Override
public boolean onCreate() {
dbHelper = new DatabaseHelper(getContext());
return true;
}
#Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case ACCOUNTS_ALL:
return "vnd.android.cursor.dir/vnd." + AUTHORITY + "." + DATABASE_NAME;
case ACCOUNTS_SINGLE:
return "vdn.android.cursor.item/vnd." + AUTHORITY + "." + DATABASE_NAME;
default:
return null;
}
}
#Override
public Uri insert(Uri uri, ContentValues values) {
Uri result = doInsert(uri, values, dbHelper.getWritableDatabase());
return result;
}
#Override
public int bulkInsert(Uri uri, ContentValues[] values) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int count = 0;
try {
db.beginTransaction();
for (ContentValues value : values) {
Uri resultUri = doInsert(uri, value, db);
if (resultUri != null) {
count++;
} else {
count = 0;
throw new SQLException("Error in bulk insert");
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
db.close();
return count;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor query;
// Fix the projection
if (projection == null) {
projection = ALL_COLUMNS;
}
// Fix sort order
if (sortOrder == null) {
sortOrder = AccountColumns._ID;
}
switch (uriMatcher.match(uri)) {
case ACCOUNTS_ALL:
query = db.query(TABLE_ACCOUNTS, projection, selection, selectionArgs, null, null, sortOrder);
db.close();
return query;
case ACCOUNTS_SINGLE:
String accountId = uri.getLastPathSegment();
selection = fixSelectionString(selection);
selectionArgs = fixSelectionArgs(selectionArgs, accountId);
query = db.query(TABLE_ACCOUNTS, projection, selection, selectionArgs, null, null, sortOrder);
db.close();
return query;
default:
throw new IllegalArgumentException("Invalid uri: " + uri);
}
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
getContext().getContentResolver().notifyChange(uri, null);
SQLiteDatabase db = dbHelper.getWritableDatabase();
int rowsAffected;
switch (uriMatcher.match(uri)) {
case ACCOUNTS_ALL:
rowsAffected = db.update(TABLE_ACCOUNTS, values, selection, selectionArgs);
break;
case ACCOUNTS_SINGLE:
String accountId = uri.getLastPathSegment();
selection = fixSelectionString(selection);
selectionArgs = fixSelectionArgs(selectionArgs, accountId);
rowsAffected = db.update(TABLE_ACCOUNTS, values, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Illegal URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsAffected;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int rowsAffected;
switch (uriMatcher.match(uri)) {
case ACCOUNTS_ALL:
rowsAffected = db.delete(TABLE_ACCOUNTS, selection, selectionArgs);
break;
case ACCOUNTS_SINGLE:
String accountId = uri.getLastPathSegment();
selection = fixSelectionString(selection);
selectionArgs = fixSelectionArgs(selectionArgs, accountId);
rowsAffected = db.delete(TABLE_ACCOUNTS, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Illegal URI: " + uri);
}
return rowsAffected;
}
private String[] fixSelectionArgs(String[] selectionArgs, String accountId) {
String[] newSelectionArgs;
if (selectionArgs == null) {
newSelectionArgs = new String[] {accountId};
} else {
newSelectionArgs = new String[selectionArgs.length + 1];
newSelectionArgs[0] = accountId;
System.arraycopy(selectionArgs, 0, newSelectionArgs, 1, selectionArgs.length);
}
return newSelectionArgs;
}
private String fixSelectionString(String selection) {
if (selection == null) {
selection = AccountColumns._ID + " = ?";
} else {
selection = AccountColumns._ID + " = ? AND (" + selection + ")";
}
return selection;
}
private Uri doInsert(Uri uri, ContentValues values, SQLiteDatabase db) {
Uri result = null;
switch (uriMatcher.match(uri)) {
case ACCOUNTS_ALL:
long id = db.insert(TABLE_ACCOUNTS, "", values);
if (id == -1) {
throw new SQLException("Error inserting data");
}
result = Uri.withAppendedPath(uri, String.valueOf(id));
break;
}
db.close();
return result;
}
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_SQL);
db.execSQL(USERNAME_INDEX_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
Well this was stupid... Apparently, in the Android Studio settings, the SDK that I was using wasn't being found, so I had to fix that. Everything works now!
I am attempting to update my SQLite database with a date field, using a DatePicker. for simplicties sake (on my part) I decided to just take the date and pass it to a String to update the database using just Strings (I have no desire to perform any DATETIME functions in this instance.
The datbase works (at least, via a dialog I set up) however when the data is cast to a TextView nothing appears, also eclipse stacktrace reports the following:
05-09 22:47:30.164: E/SQLiteDatabase(3112): Error inserting chest=100 arms=android.widget.TextView#4125c110 legs=100 waist=100 weight=100
05-09 22:47:30.164: E/SQLiteDatabase(3112): android.database.sqlite.SQLiteConstraintException: personalStats.date may not be NULL (code 19)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:775)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at com.uhi.fatfighter.Stats.createEntry(Stats.java:86)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at com.uhi.fatfighter.MainActivity.onClick(MainActivity.java:250)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.view.View.performClick(View.java:4084)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.view.View$PerformClick.run(View.java:16966)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.os.Handler.handleCallback(Handler.java:615)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.os.Handler.dispatchMessage(Handler.java:92)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.os.Looper.loop(Looper.java:137)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.app.ActivityThread.main(ActivityThread.java:4928)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at java.lang.reflect.Method.invokeNative(Native Method)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at java.lang.reflect.Method.invoke(Method.java:511)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at dalvik.system.NativeStart.main(Native Method)
Below is the class where the SQL is handled:
public class Stats {
public static final String KEY_ROWID = "_id";
public static final String KEY_WEIGHT = "weight";
public static final String KEY_WAIST = "waist";
public static final String KEY_CHEST = "chest";
public static final String KEY_LEGS = "legs";
public static final String KEY_ARMS = "arms";
public static final String KEY_DATE = "date";
private static final String DATABASE_NAME = "statsDB";
private static final String DATABASE_TABLE = "personalStats";
private static final int DATABASE_VERSION = 4;
private DbHelper ffHelper;
private final Context ffContext;
private SQLiteDatabase ffDatabase;
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_WEIGHT
+ " TEXT NOT NULL, " + KEY_WAIST + " TEXT NOT NULL, "
+ KEY_CHEST + " TEXT NOT NULL, " + KEY_LEGS
+ " TEXT NOT NULL, " + KEY_ARMS + " TEXT NOT NULL,"
+ KEY_DATE + " TEXT NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Stats(Context c) {
ffContext = c;
}
public Stats open() throws SQLException {
ffHelper = new DbHelper(ffContext);
ffDatabase = ffHelper.getWritableDatabase();
return this;
}
public void close() {
ffHelper.close();
}
public long createEntry(String weight, String waist, String chest, String legs, String arms, String date) {
ContentValues cv = new ContentValues();
cv.put(KEY_WEIGHT, weight);
cv.put(KEY_WAIST, waist);
cv.put(KEY_CHEST, chest);
cv.put(KEY_LEGS, legs);
cv.put(KEY_ARMS, arms);
cv.put(KEY_ARMS, date);
return ffDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
String[] columns = new String[] { KEY_ROWID, KEY_WEIGHT, KEY_WAIST, KEY_CHEST, KEY_LEGS, KEY_ARMS, KEY_DATE};
Cursor c = ffDatabase.query(DATABASE_TABLE, columns, null, null, null,
null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iWeight = c.getColumnIndex(KEY_WEIGHT);
int iWaist = c.getColumnIndex(KEY_WAIST);
int iChest = c.getColumnIndex(KEY_CHEST);
int iLegs = c.getColumnIndex(KEY_LEGS);
int iArms = c.getColumnIndex(KEY_ARMS);
int iDate = c.getColumnIndex(KEY_DATE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " " + c.getString(iWeight)
+ " " + c.getString(iWaist)
+ " " + c.getString(iChest)
+ " " + c.getString(iLegs)
+ " " + c.getString(iArms)
+ " " + c.getString(iDate)+ "\n";
}
return result;
}
}
The view class:
public class DBView extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.view_stats);
TextView tv = (TextView) findViewById(R.id.tvDBInfo);
Stats dbInfo = new Stats(this);
dbInfo.open();
String data = dbInfo.getData();
dbInfo.close();
tv.setText(data);
}
The EditTexts and DatePicker are in my main_activity, i can post if it would help?
You put two times the same key in your content values.
cv.put(KEY_ARMS, arms);
cv.put(KEY_ARMS, date);
Change it with :
cv.put(KEY_ARMS, arms);
cv.put(KEY_DATE, date);
You didn't insert nothing in KEY_DATE, but KEY_DATE is not null.
Yu must put cv.put(KEY_DATE, date); before insert
Instead of having your KEY_DATE column set to "TEXT NOT NULL", Just set it to plain "TEXT". You can also do that with any other columns where you may be inserting a null or empty value.