One Time Quiter - android

I am having a little trouble understanding this problem. It only happens when the first time the app is open after a fresh install of the app not an update.
On the menu screen I click the see high score button and the app crashes restart the app and it goes to the blank screen as it should no scores are in the db. As far as I can tell it never crashes again, no matter how hard I try. The issue will be when the user first uses the app after downloading it from the store.
Caused by: java.lang.IllegalStateException: Cannot perform this operation because the connection pool has been closed.
public class Top extends ListActivity {
public static int mScreenWidth, mScreenHeight;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
mScreenWidth = display.getWidth();
mScreenHeight = display.getHeight();
this.setTitle("HIGH SCORE");
final SQLiteHelper helpter = new SQLiteHelper(this);
Cursor cursor = helpter.query();
String[] from = {"_rank", "_name", "_score"};
int[] to = {R.id.mid, R.id.mname, R.id.mscore};
if (cursor != null) {
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.show, cursor, from, to);
ListView listView = getListView();
listView.setAdapter(adapter);
}
}
SQLite:
public class SQLiteHelper extends SQLiteOpenHelper{
//
private static final String DB_NAME = "score.db";
private static final String TABLE_NAME = "ScoreTable";
private static final String CREATE_TABLE = " create table "
+ " if not exists " + TABLE_NAME + " (_id integer primary key autoincrement," +
"_name text,_score Integer,_rank Integer) ";
private SQLiteDatabase mDB;
SQLiteHelper(Context context) {
super(context, DB_NAME, null, 2);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
this.mDB = db;
db.execSQL(CREATE_TABLE);
}
/**
*
* #param values
*/
public void insert(ContentValues values){
mDB = getWritableDatabase();
mDB.beginTransaction();//¡
try{
mDB.insert(TABLE_NAME, null, values);
mDB.setTransactionSuccessful(); //endTransaction()
}catch (Exception e) {
//Log.e(TAG, e.getMessage());
}finally{
mDB.endTransaction();//
mDB.close();
}
}
/**
* #param values
* #param id
*/
public void update(ContentValues values,int id){
mDB = getWritableDatabase();
mDB.beginTransaction();//
try{
mDB.update(TABLE_NAME, values, "_id = '"+id+"'", null);
mDB.setTransactionSuccessful(); //
}catch (Exception e) {
//Log.e(TAG, e.getMessage());
}finally{
mDB.endTransaction();//
close();
}
}
/**
* #param id
*/
public void delete(int id){
try {
if (mDB == null)
mDB = getWritableDatabase();
mDB.delete(TABLE_NAME, "_id=?", new String[] { String.valueOf(id) });
} catch (Exception e) {
// TODO: handle exception
}finally{
close();
}
}
/**
*
*/
public Cursor query(){
Cursor c = null;
try {
SQLiteDatabase db = getWritableDatabase();
c = db.query(TABLE_NAME, null, null, null, null, null, "_score desc",null);
} catch (Exception e) {
// TODO: handle exception
}finally{
close();
}
return c;
}
/**
* #param score
* #return
*/
public String queryrank(String score){
String rank = null;
try {
SQLiteDatabase db = getWritableDatabase();
Cursor c = db.query(TABLE_NAME, null, " _score >= '"+score+"'" , null, null, null, null, null);
rank = String.valueOf(c.getCount());
Cursor cc = db.query(TABLE_NAME, null, " _score < '"+score+"'" , null, null, null, null, null);
if(cc.getCount() > 0){
int mName = cc.getColumnIndex("_name");
int mScore = cc.getColumnIndex("_score");
int mRank = cc.getColumnIndex("_rank");
//String[][] tmpUpdate=new String[cc.getCount()][cc.getColumnCount()];
String aa ="";
String bb ="";
String ee ="";
for(cc.moveToFirst();!(cc.isAfterLast());cc.moveToNext()){
if(cc.getString(mName)!=null){
aa=aa+","+ cc.getString(mName);
bb =bb+ ","+String.valueOf(cc.getInt(mScore));
ee =ee+","+String.valueOf(cc.getInt(mRank));
}
}
String[] aaa=aa.split(",");
String[] bbb=bb.split(",");
String[] ddd=ee.split(",");
for(int i=0;i<aaa.length;i++){
if(aaa[i]!=null && aaa[i]!="" && aaa[i].length()>0){
Log.v("001",aaa[i]+":"+bbb[i]+":"+ddd[i]);
ContentValues values=new ContentValues();
values.put("_name", aaa[i]);
values.put("_score", Integer.parseInt(bbb[i]));
values.put("_rank", Integer.parseInt(ddd[i])+1);
db.update(TABLE_NAME, values, "_score = '"+bbb[i]+"'", null);
}
}
}
} catch (Exception e) {
// TODO: handle exception
}finally{
close();
}
return rank;
}
/**
* #param nameString
* #return
*/
public boolean isNameExist(String nameString){
boolean flag = false;
mDB = getReadableDatabase();
Cursor cursor = mDB.query(TABLE_NAME, null, "_name='"+nameString+"'", null, null, null, null, null);//
int nameIndex = cursor.getColumnIndex("_name");
for(cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()){
if(cursor.getString(nameIndex).equals("") ||cursor.getString(nameIndex) == null){
flag = false;//
}else {
flag = true;//
}
}
cursor.close();
mDB.close();
return flag;
}
/**
*
*/
public void close() {
if (mDB != null)
mDB.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("drop table if exists " + TABLE_NAME);
onCreate(db);
}
/**
* #param model
* #param start
* #param end
* #return
*/
public Cursor getListViewCursorByModel(int model,String start,String end) {
Cursor cursor = null;
try {
mDB = getWritableDatabase();
cursor = mDB.query(TABLE_NAME, null, "_model='"+model+"'", null, null, null, "_score desc","'"+start+"','"+end+"'");
} catch (Exception e) {
// TODO: handle exception
}finally{
mDB.close();
}
return cursor;
}
}
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bigtexapps.zookeeper/com.bigtexapps.zookeeper.Top}: java.lang.IllegalStateException: Cannot perform this operation because the connection pool has been closed.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.IllegalStateException: Cannot perform this operation because the connection pool has been closed.
at android.database.sqlite.SQLiteConnectionPool.throwIfClosedLocked(SQLiteConnectionPool.java:1027)
at android.database.sqlite.SQLiteConnectionPool.waitForConnection(SQLiteConnectionPool.java:664)
at android.database.sqlite.SQLiteConnectionPool.acquireConnection(SQLiteConnectionPool.java:397)
at android.database.sqlite.SQLiteSession.acquireConnection(SQLiteSession.java:905)
at android.database.sqlite.SQLiteSession.executeForCursorWindow(SQLiteSession.java:834)
at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:62)
at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:143)
at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:132)
at android.widget.CursorAdapter.getCount(CursorAdapter.java:235)
at android.widget.ListView.setAdapter(ListView.java:508)
at com.bigtexapps.zookeeper.Top.onCreate(Top.java:43)
at android.app.Activity.performCreate(Activity.java:6876)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349) 
at android.app.ActivityThread.access$1100(ActivityThread.java:221) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7224) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 

Related

Model object is not matching with the database result

After the record iteration, the list key value is mismatching/wrongly shown ! what could be the reason.
Correct data in the database like this is saved (which is correct)
Problem: You can see in this screenshot link, record is a mismatch with columns, e.g the key dayName has wrong value showing , key MenuIcon value is shown on dayName key
the sql lite DAO
/*
* Get the all the exercises by ID asecending order
*/
public LinkedList<ExerciseDetails> getAllExerciseInfo() {
LinkedList<ExerciseDetails> listCompanies = new LinkedList<ExerciseDetails>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_EXERCISE_DETAILS, mAllColumns,
"",
new String[]{}, "order_id", null, "order_id ASC");
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ExerciseDetails company = cursorToExerciseDetails(cursor);
listCompanies.add(company);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listCompanies;
}
Full code of DAO for insertion,create table, list object . Please let me know any code you want to see, i will post
public class ExercisesDAO {
public static final String TAG = "ExercisesDAO";
// Database fields
private SQLiteDatabase mDatabase;
private DBHelper mDbHelper;
private Context mContext;
private String[] mAllColumns = {DBHelper.COLUMN_EX_DETAILS_ID,
DBHelper.COLUMN_ROUTINE_ID,
DBHelper.COLUMN_DAY_ID,
DBHelper.COLUMN_EXERCISE_ID,
DBHelper.COLUMN_REPS,
DBHelper.COLUMN_SETS,
DBHelper.COLUMN_TIME_PERSET,
DBHelper.COLUMN_CALORIE_BURN,
DBHelper.COLUMN_RESTTIME_PERSET,
DBHelper.COLUMN_RESTTIME_POST_SET,
DBHelper.COLUMN_ORDER_ID,
DBHelper.COLUMN_EXERCISE_NAME,
DBHelper.COLUMN_TIPS,
DBHelper.COLUMN_YOUTUBE_URL,
DBHelper.COLUMN_WARNINGS,
DBHelper.COLUMN_DISPLAY_ID,
DBHelper.COLUMN_VISIBILITY,
DBHelper.COLUMN_FOR_DATE,
DBHelper.COLUMN_GIF,
DBHelper.COLUMN_DAYNAME
};
public ExercisesDAO(Context context) {
this.mContext = context;
mDbHelper = new DBHelper(context);
// open the database
try {
open();
} catch (SQLException e) {
Log.e(TAG, "SQLException on openning database " + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDbHelper.getWritableDatabase();
}
public void close() {
mDbHelper.close();
}
public ExerciseDetails createExerciseDetail(String routineId,String dayId,
String exerciseId, String reps,String sets, String timePerset,
String calorieBurn, String resttimePerset, String resttimeAfterex,String order,
String menuName, String tips, String youtubeUrl, String warnings, String displayId,
String visibility, String forDate, String menuIcon, String dayName) {
ExerciseDetails newCompany = null;
try {
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_ROUTINE_ID, routineId);
values.put(DBHelper.COLUMN_DAY_ID, dayId);
values.put(DBHelper.COLUMN_EXERCISE_ID, exerciseId);
values.put(DBHelper.COLUMN_REPS, reps);
values.put(DBHelper.COLUMN_SETS, sets);
values.put(DBHelper.COLUMN_TIME_PERSET, timePerset);
values.put(DBHelper.COLUMN_CALORIE_BURN, calorieBurn);
values.put(DBHelper.COLUMN_RESTTIME_PERSET, resttimePerset);
values.put(DBHelper.COLUMN_RESTTIME_POST_SET, resttimeAfterex);
values.put(DBHelper.COLUMN_ORDER_ID, order);
values.put(DBHelper.COLUMN_EXERCISE_NAME, menuName);
values.put(DBHelper.COLUMN_TIPS, tips);
values.put(DBHelper.COLUMN_YOUTUBE_URL, youtubeUrl);
values.put(DBHelper.COLUMN_WARNINGS, warnings);
values.put(DBHelper.COLUMN_DISPLAY_ID, displayId);
values.put(DBHelper.COLUMN_VISIBILITY, visibility);
values.put(DBHelper.COLUMN_FOR_DATE, forDate);
values.put(DBHelper.COLUMN_GIF, menuIcon);
values.put(DBHelper.COLUMN_DAYNAME, dayName);
long insertId = mDatabase
.insert(DBHelper.TABLE_EXERCISE_DETAILS, null, values);
Cursor cursor = mDatabase.query(DBHelper.TABLE_EXERCISE_DETAILS, mAllColumns,
DBHelper.COLUMN_EX_DETAILS_ID + " = " + insertId, null, null,
null, null);
cursor.moveToFirst();
newCompany = cursorToExerciseDetails(cursor);
cursor.close();
} catch (Exception e) {
Log.e("exception", "exception in CreateFollowing class - " + e);
}
return newCompany;
}
public void executeSqlOnExerciseDetail(String sql) {
mDatabase.execSQL(sql);
}
public Long getTotalCountExerciseDetail() {
return DatabaseUtils.queryNumEntries(mDatabase, DBHelper.TABLE_EXERCISE_DETAILS);
}
/*
* Get the all the exercises by ID asecending order
*/
public LinkedList<ExerciseDetails> getAllExerciseInfo() {
LinkedList<ExerciseDetails> listCompanies = new LinkedList<ExerciseDetails>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_EXERCISE_DETAILS, mAllColumns,
"",
new String[]{}, "order_id", null, "order_id ASC");
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ExerciseDetails company = cursorToExerciseDetails(cursor);
listCompanies.add(company);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listCompanies;
}
/*
* Check whether the exercise data present or not in the db before executing statement
*/
public boolean CheckIfRecordExists(String rid, String did) {
String Query = "Select * from " + DBHelper.TABLE_EXERCISE_DETAILS + " where " + DBHelper.COLUMN_ROUTINE_ID + " = " + rid + " AND " + DBHelper.COLUMN_DAY_ID + " = " + did;
Cursor cursor = mDatabase.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
protected ExerciseDetails cursorToExerciseDetails(Cursor cursor) {
try{
ExerciseDetails exerciseDetails = new ExerciseDetails();
exerciseDetails.setExDetailsId(cursor.getLong(0));
exerciseDetails.setRoutineId(cursor.getString(1));
exerciseDetails.setDayId(cursor.getString(2));
exerciseDetails.setExerciseId(cursor.getString(3));
exerciseDetails.setReps(cursor.getString(4));
exerciseDetails.setSets(cursor.getString(5));
exerciseDetails.setTimePerset(cursor.getString(6));
exerciseDetails.setCalorieBurn(cursor.getString(7));
exerciseDetails.setResttimePerset(cursor.getString(8));
exerciseDetails.setOrder(cursor.getString(9));
exerciseDetails.setMenuName(cursor.getString(10));
exerciseDetails.setTips(cursor.getString(11));
exerciseDetails.setYoutubeUrl(cursor.getString(12));
exerciseDetails.setWarnings(cursor.getString(13));
exerciseDetails.setDisplayId(cursor.getString(14));
exerciseDetails.setVisibility(cursor.getString(15));
exerciseDetails.setForDate(cursor.getString(16));
exerciseDetails.setMenuIcon(cursor.getString(17));
exerciseDetails.setDayName(cursor.getString(18));
return exerciseDetails;
} catch (Exception e){
System.out.println("error------------"+e);
return null;
}
}
}
FUll json value which i inserted Into sqllite
https://pastebin.com/DmAkPkXg
In cursorToExerciseDetails() instead of explicitly setting the index of a column:
exerciseDetails.setExDetailsId(cursor.getLong(0));
exerciseDetails.setRoutineId(cursor.getString(1));
....................................................
use getColumnIndex() with he name of the column to return the index:
exerciseDetails.setExDetailsId(cursor.getLong(cursor.getColumnIndex(DBHelper.COLUMN_EX_DETAILS_ID)));
exerciseDetails.setRoutineId(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_ROUTINE_ID))));
....................................................

CursorIndexOutOfBoundsException: Index 1 requested, with a size of 1

I'm getting the following warning in debugger. My code consists of Users and their Friends. At some point in FriendsDAO the username from Users is brought in. But right now I'm running into a cursor issue below. Any help is appreciated.
05-30 10:32:15.098 1957-1957/com.example.mms.mobile E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.mms.mobile, PID: 1957
android.database.CursorIndexOutOfBoundsException: Index 1 requested, with a size of 1
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getLong(AbstractWindowedCursor.java:74)
at com.example.mms.mobile.UserDAO.cursorToUser(UserDAO.java:182)
at com.example.mms.mobile.UserDAO.getUser(UserDAO.java:113)
at com.example.mms.mobile.FriendsDAO.cursorToFriends(FriendsDAO.java:156)
at com.example.mms.mobile.FriendsDAO.createFriend(FriendsDAO.java:73)
at com.example.mms.mobile.AddFriendActivity.onClick(AddFriendActivity.java:120)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
My code for UserDAO and FriendsDAO are below:
//UserDAO
public class UserDAO {
public static final String TAG = "UserDAO";
// Database fields
private SQLiteDatabase Database;
private DBHelper DbHelper;
private Context Context;
private String[] AllColumns = {
DBHelper.USER_ID,
DBHelper.USER_NAME ,
DBHelper.PASSWORD ,
DBHelper.COUNTY ,
DBHelper.EMAIL ,
DBHelper.COUNTRY
};
public UserDAO(Context context) {
this.Context = context;
DbHelper = new DBHelper(context);
// open the database
try {
open();
} catch (SQLException e) {
Log.e(TAG, "SQLException on opening database " + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
Database = DbHelper.getWritableDatabase();
}
public void close() {
DbHelper.close();
}
public USER createUser(String usrname, String pass, String county, String email,
String country) {
ContentValues values = new ContentValues();
values.put(DBHelper.USER_NAME ,usrname);
values.put(DBHelper.PASSWORD ,pass);
values.put(DBHelper.COUNTY ,county);
values.put(DBHelper.EMAIL ,email);
values.put(DBHelper.COUNTRY,country);
long insertId = Database
.insert(DBHelper.TABLE_LOGIN, null, values);
Cursor cursor = Database.query(DBHelper.TABLE_LOGIN, AllColumns,
DBHelper.USER_ID + " = " + insertId, null, null,null,null);
cursor.moveToFirst();
USER newUser = cursorToUser(cursor);
cursor.close();
return newUser;
}
public USER getUser(String name) {
Cursor cursor = Database.query(DBHelper.TABLE_LOGIN, AllColumns,
DBHelper.USER_NAME + " = ?",
new String[] { String.valueOf(name) }, null, null, null);
//if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
USER user = cursorToUser(cursor);
cursor.moveToNext();
}
cursor.close();
return user;
}
protected USER cursorToUser(Cursor cursor) {
USER user = new USER();
user.setId(cursor.getLong(0));
user.setUser(cursor.getString(1));
user.setPass(cursor.getString(2));
user.setCounty(cursor.getString(3));
user.setEmail(cursor.getString(4));
user.setCountry(cursor.getString(5));
return user;
}
}
And FriendsDAO:
public class FriendDAO {
public static final String TAG = "FriendDAO";
// Database fields
private SQLiteDatabase pDatabase;
private DBHelper pDbHelper;
private Context pContext;
private String[] pAllColumns = {
DBHelper.FRIEND_ID,
DBHelper.FRIEND_USERNAME,
DBHelper.list1_ID,
DBHelper.list2_ID,
DBHelper.list3_ID,
DBHelper.location,
DBHelper.FRIEND_NAME,
DBHelper.FRIEND_ADDRESS,
DBHelper.FRIEND_PHONE_NUMBER
};
public FriendDAO(Context context) {
this.pContext = context;
pDbHelper = new DBHelper(context);
// open the database
try {
open();
} catch (SQLException e) {
Log.e(TAG, "SQLException on opening database " + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
pDatabase = pDbHelper.getWritableDatabase();
}
public void close() {
pDbHelper.close();
}
public Friend createFriend(String userN, Integer list1ID, Integer list2ID, Integer list3ID,
String loc, String name, String address, String phone) {
ContentValues values = new ContentValues();
values.put(DBHelper.FRIEND_USERNAME, userN);
values.put(DBHelper.list1_ID, list1ID);
values.put(DBHelper.list2_ID, list2ID);
values.put(DBHelper.list3_ID, list3ID);
values.put(DBHelper.location, loc);
values.put(DBHelper.FRIEND_NAME, name);
values.put(DBHelper.FRIEND_ADDRESS, address);
values.put(DBHelper.FRIEND_PHONE_NUMBER, phone);
long insertId = pDatabase
.insert(DBHelper.TABLE_FRIENDS, null, values);
Cursor cursor = pDatabase.query(DBHelper.TABLE_FRIENDS, pAllColumns,
DBHelper.FRIEND_ID + " = " + insertId, null, null,null,null);
cursor.moveToFirst();
Friend newFriend = cursorToFriend(cursor);
cursor.close();
return newFriend;
}
protected Friend cursorToFriend(Cursor cursor) {
Friend friend = new Friend();
friend.setId(cursor.getLong(0));
// get The user by id
String userN = cursor.getString(1);
UserDAO dao = new UserDAO(pContext);
USER user = dao.getUser(userN);
if(user != null)
friend.setUser(user);
friend.setlocation(cursor.getString(2));
friend.setlist1(cursor.getString(3));
friend.setlist2Id(cursor.getString(4));
friend.setlist3Id(cursor.getString(5));
friend.setName(cursor.getString(6));
friend.setAddress(cursor.getString(7));
friend.setPhoneNumber(cursor.getString(8));
return friend;
}
}

android.content.Context.getContentResolver()' on a null object reference

I can't seem work out why I am getting a null pointer on this?
This is my AsyncTask that I call to grab the data. It passes it to a JSON Parser and an array of Objects is returned. This is then passed to my DBHelper where it was passing to my database through a ContentResolver....
public class getFilms extends AsyncTask<String, Void, Void> {
public int LIMIT_FILMS = 10;
String KEY = "apikey";
String LIMIT = "limit";
private static final String URL = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?";
private static final String API_KEY = "******************";
ArrayList<HashMap<String, String>> filmArrayList = new ArrayList<HashMap<String, String>>();
Context mContext;
#Override
protected Void doInBackground(String... params) {
Uri RottenUrl = Uri.parse(URL).buildUpon()
.appendQueryParameter(KEY, API_KEY)
.appendQueryParameter(LIMIT, Integer.toString(LIMIT_FILMS))
.build();
JSONParser jParser = new JSONParser();
Film[] json = jParser.getJSONFromUrl(RottenUrl.toString());
sortData(json);
return null;
}
public void sortData(Film[] jsonlist) {
DatabaseHelper dbHelper = new DatabaseHelper(mContext, null, null, 1);
dbHelper.deleteAll();
for (int i = 0; i < jsonlist.length; i++) {
dbHelper.contentAddFilm(jsonlist[i]);
}
}
}
This is my Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
private ContentResolver myCR;
public DatabaseHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, FilmDataContract.DATABASE_NAME, factory, FilmDataContract.DATABASE_VERSION);
myCR = context.getContentResolver();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(FilmDataContract.FilmEntry.SQL_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(FilmDataContract.FilmEntry.DELETE_TABLE);
onCreate(db);
}
public void addFilm(Film film) {
ContentValues values = new ContentValues();
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_TITLE, film.getTitle());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RATING, film.getRating());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RUNTIME, film.getRuntime());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_CRITICS, film.getCritics());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_AUDIENCE, film.getAudience());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_SYNOPSIS, film.getSynopsis());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_PROFILE, film.getProfile());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(FilmDataContract.TABLE_NAME,
null,
values);
db.close();
}
public Film getFilm(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor =
db.query(FilmDataContract.TABLE_NAME,
FilmDataContract.FilmEntry.COLUMNS,
"_id = ?",
new String[]{String.valueOf(id)},
null,
null,
null,
null);
if (cursor != null)
cursor.moveToFirst();
Film film = new Film();
film.setTitle(cursor.getString(1));
film.setRating(cursor.getString(2));
film.setRuntime(cursor.getString(3));
film.setCritics(cursor.getString(4));
film.setAudience(cursor.getString(5));
film.setSynopsis(cursor.getString(6));
film.setProfile(cursor.getString(7));
return film;
}
public List<Film> getAllFilms() {
List<Film> films = new LinkedList<Film>();
String query = "SELECT * FROM " + FilmDataContract.TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Film film = null;
if (cursor.moveToFirst()) {
do {
film = new Film();
film.setId(Integer.parseInt(cursor.getString(0)));
film.setTitle(cursor.getString(1));
film.setRating(cursor.getString(2));
film.setRuntime(cursor.getString(3));
film.setCritics(cursor.getString(4));
film.setAudience(cursor.getString(5));
film.setSynopsis(cursor.getString(6));
film.setProfile(cursor.getString(7));
films.add(film);
} while (cursor.moveToNext());
}
return films;
}
public int updateFilm(Film film) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_TITLE, film.getTitle());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RATING, film.getRating());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RUNTIME, film.getRuntime());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_CRITICS, film.getCritics());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_AUDIENCE, film.getAudience());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_SYNOPSIS, film.getSynopsis());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_PROFILE, film.getProfile());
int i = db.update(FilmDataContract.FilmEntry.TABLE_NAME,
values,
"_id+ = ?",
new String[]{String.valueOf(film.getId())});
db.close();
return i;
}
public int getFilmsCount() {
String countQuery = "SELECT * FROM " + FilmDataContract.FilmEntry.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
public void deleteAll() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(FilmDataContract.FilmEntry.TABLE_NAME, null, null);
}
public boolean contentDelete(String filmName) {
boolean result = false;
String selection = "title = \"" + filmName + "\"";
int rowsDeleted = myCR.delete(FilmProvider.CONTENT_URI,
selection, null);
if (rowsDeleted > 0)
result = true;
return result;
}
public Film contentFindFilm(String filmName) {
String[] projection = FilmDataContract.FilmEntry.COLUMNS;
String selection = "title = \"" + filmName + "\"";
Cursor cursor = myCR.query(FilmProvider.CONTENT_URI,
projection, selection, null,
null);
Film film = new Film();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
film.setId(Integer.parseInt(cursor.getString(0)));
film.setTitle(cursor.getString(1));
film.setRating(cursor.getString(2));
film.setRuntime(cursor.getString(3));
film.setCritics(cursor.getString(4));
film.setAudience(cursor.getString(5));
film.setSynopsis(cursor.getString(6));
film.setProfile(cursor.getString(7));
cursor.close();
} else {
film = null;
}
return film;
}
public void contentAddFilm(Film film) {
ContentValues values = new ContentValues();
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_TITLE, film.getTitle());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RATING, film.getRating());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RUNTIME, film.getRuntime());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_CRITICS, film.getCritics());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_AUDIENCE, film.getAudience());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_SYNOPSIS, film.getSynopsis());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_PROFILE, film.getProfile());
myCR.insert(FilmProvider.CONTENT_URI, values);
}
This is my stack trace... Seems to be happening when I am passing the context.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference
at com.purewowstudio.topmovies.data.DatabaseHelper.<init>(DatabaseHelper.java:25)
at com.purewowstudio.topmovies.util.getFilms.sortData(getFilms.java:48)
at com.purewowstudio.topmovies.util.getFilms.doInBackground(getFilms.java:43)
at com.purewowstudio.topmovies.util.getFilms.doInBackground(getFilms.java:16)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
             at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            
DatabaseHelper dbHelper = new DatabaseHelper(mContext, null, null, 1);
mContext is null, because you never assign a value to it.

how do i fetch a record from SQL

sorry im kind of a beginner,
I have a simple app that stores data on one page and fetches it on another. i keep getting an error when i try and fetch the data, stating that no such column could be found. please help
this is my code from where i enter the data,
EnterDetails.java
#Override
public void onClick(View arg0) {
EditText holdersala = (EditText) findViewById(R.id.rawsalary);
EditText wantspercentage = (EditText) findViewById(R.id.wantspercent);
EditText needspercentage = (EditText) findViewById(R.id.needspercent);
String holdersalary = holdersala.getText().toString();
final int salary = Integer.parseInt(holdersalary);
String holderwantsp = wantspercentage.getText().toString();
final int wantsp = Integer.parseInt(holderwantsp);
String holderneedsp = needspercentage.getText().toString();
final int needsp = Integer.parseInt(holderneedsp);
if(wantsp + needsp <= 100){
DatabaseAdapter databaseAdapter = new DatabaseAdapter(getApplicationContext());
databaseAdapter.open();
databaseAdapter.createRecordS(salary);
databaseAdapter.createRecordW(wantsp);
databaseAdapter.createRecordN(needsp);
databaseAdapter.close();
startActivity(new Intent(EnterDetails.this, Summary.class));
} else {
}
Toast toast = Toast.makeText(EnterDetails.this, "incorrect data", 5000);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
code from where i fetch the data
TextView bn = (TextView) findViewById(R.id.budget_need);
DatabaseAdapter databaseAdapter = new DatabaseAdapter(getApplicationContext());
databaseAdapter.open();
bn.setText(databaseAdapter.fetchRecordS(1));
databaseAdapter.close();
and code from my databaseAdapter.java
public class DatabaseAdapter {
private Context context;
private SQLiteDatabase database;
private DatabaseOpenHelper dbHelper;
public DatabaseAdapter(Context context) {
this.context = context;
}
public DatabaseAdapter open() throws SQLException {
dbHelper = new DatabaseOpenHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
public long createRecordS(int interger) {
ContentValues contentValue = new ContentValues();
contentValue.put("salafig", interger);
return database.insert("maindata", null, contentValue);
}
public long createRecordN(int interger) {
ContentValues contentValue = new ContentValues();
contentValue.put("needsper", interger);
return database.insert("maindata", null, contentValue);
}
public long createRecordW(int interger) {
ContentValues contentValue = new ContentValues();
contentValue.put("wantsper", interger);
return database.insert("maindata", null, contentValue);
}
public int fetchRecordS(long rowId) throws SQLException {
Cursor mCursor = database.query(true, "maindata", new String[] { "salafig",
"needsper", "wantsper" }, "salafig"+ rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
return (mCursor.getInt(1));
}
return (Integer) null;
}
public int fetchRecordW(long rowId) throws SQLException {
Cursor mCursor = database.query(true, "maindata", new String[] { "salafig",
"needsper", "wantsper" }, "wantsper"+ rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
return (mCursor.getInt(1));
}
return (Integer) null;
}public int fetchRecordN(long rowId) throws SQLException {
Cursor mCursor = database.query(true, "maindata", new String[] { "salafig",
"needsper", "wantsper" }, "needsper"+ rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
return (mCursor.getInt(1));
}
hope it makes sense thanks if advance for any help.
Look at HEREto check the correct syntax of the SQLiteDatabase query method.
The forth parameter of the method is the selection condition, it s supposed to be something like:
"salafig = "+ rowId"
instead of this :
"salafig"+ rowId"

Application stops working on mobile device but runs on emmulator

i have developed an app for 'bank simulation' which uses sqlite to create databases...
when i run the app on my mobile it stops unexpectedly....do i need to install any server to run sqlite based apps on mobile?
Thanks in advance!
DbHelper.java
private static final String DATABASE_NAME = "saket.db";
private static final int DATABASE_VERSION = 1;
public static final String SUBH_TABLE_NAME = "login";
public static final String SUBH_TABLE_DATA = "TBL_Transaction";
public static final String KEY_ROWID = "_id";
private static final String SUBH_TABLE_CREATE =
"CREATE TABLE " + SUBH_TABLE_NAME + "(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+
"username TEXT NOT NULL, password TEXT NOT NULL, email TEXT NOT NULL, balance INTEGER);";
private static final String SUBH_TABLE_DATA_CREATE =
"CREATE TABLE " + SUBH_TABLE_DATA + "(" +
"trans_id INTEGER PRIMARY KEY AUTOINCREMENT, "+
"user_id INTEGER, " +
"trans TEXT NOT NULL);";
private static final String SAKET_DB_ADMIN = "INSERT INTO "+ SUBH_TABLE_NAME +" values(1, admin, password, admin#gmail.com);";
//private static final String SAKET_DB_ADMIN_Trans = "INSERT INTO "+ SUBH_TABLE_DATA +" values(1, asdf);";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
System.out.println("In constructor");
}
/* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
*/
#Override
public void onCreate(SQLiteDatabase db) {
try{
//Create Database
db.execSQL(SUBH_TABLE_CREATE);
//create transaction account
db.execSQL(SUBH_TABLE_DATA_CREATE);
//create admin account
db.execSQL(SAKET_DB_ADMIN);
//db.execSQL(SAKET_DB_ADMIN_Trans);
System.out.println("In onCreate");
}catch(Exception e){
e.printStackTrace();
}
}
DatabaseActivity.java
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mNewUser = (Button) findViewById(R.id.buttonNewUser);
mNewUser.setOnClickListener(this);
mLogin = (Button) findViewById(R.id.buttonLogin);
mLogin.setOnClickListener(this);
mShowAll = (Button) findViewById(R.id.buttonShowAll);
mShowAll.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonLogin:
mUsername = (EditText) findViewById(R.id.editUsername);
mPassword = (EditText) findViewById(R.id.editPassword);
String uname = mUsername.getText().toString();
String pass = mPassword.getText().toString();
if (uname.equals("") || uname == null) {
Toast.makeText(getApplicationContext(), "Username Empty",
Toast.LENGTH_SHORT).show();
} else if (pass.equals("") || pass == null) {
Toast.makeText(getApplicationContext(), "Password Empty",
Toast.LENGTH_SHORT).show();
} else {
boolean validLogin = false;
try {
validLogin = validateLogin(uname, pass,
DatabaseActivity.this);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (validLogin) {
System.out.println("In Valid");
Intent i_login = new Intent(DatabaseActivity.this,
UserLoggedInPage.class);
try {
id = getID(uname, pass, DatabaseActivity.this);
Ubal = getBAL(uname, pass, DatabaseActivity.this);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d(TAG, "putting the extra " + id);
i_login.putExtra("key", id);
i_login.putExtra("bkey", Ubal);
startActivity(i_login);
finish();
}
}
break;
case R.id.buttonNewUser:
Intent i = new Intent(DatabaseActivity.this, NewUserActivity.class);
startActivity(i);
finish();
break;
case R.id.buttonShowAll:
Intent i_admin = new Intent(DatabaseActivity.this, AdminPage.class);
startActivity(i_admin);
finish();
break;
}
}
public boolean validateLogin(String uname, String pass, Context context)
throws Exception {
myDb = new DbHelper(context);
SQLiteDatabase db = myDb.getReadableDatabase();
// SELECT
String[] columns = { "_id" };
// WHERE clause
String selection = "username=? AND password=?";
// WHERE clause arguments
String[] selectionArgs = { uname, pass };
Cursor cursor = null;
try {
// SELECT _id FROM login WHERE username = uname AND password=pass
cursor = db.query(DbHelper.SUBH_TABLE_NAME, columns, selection,
selectionArgs, null, null, null);
startManagingCursor(cursor);
} catch (Exception e) {
e.printStackTrace();
}
int numberOfRows = cursor.getCount();
if (numberOfRows <= 0) {
Toast.makeText(getApplicationContext(),
"Login Failed..\nTry Again", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
// get rowid
// public int getID(String uname, String pass, Context context)
// throws Exception {
//
// myDb = new DbHelper(context);
// SQLiteDatabase db = myDb.getReadableDatabase();
// cursor = db.rawQuery("select * from " + DbHelper.SUBH_TABLE_NAME +
// " where username = " + uname + "&" + "password = " + pass + ";)", null);
// if (cursor != null) {
// if(cursor.moveToFirst()){
// int id = cursor.getInt(cursor.getColumnIndex(DbHelper.KEY_ROWID));
// }
//
// }
//
// return id;
//
// }
public String getID(String uname, String pass, Context context) {
try {
String idddd = null;
SQLiteDatabase db = myDb.getReadableDatabase();
String[] columns = { "_id" };
// WHERE clause
String selection = "username=? AND password=?";
// WHERE clause arguments
String[] selectionArgs = { uname, pass };
Cursor cursor = db.query(DbHelper.SUBH_TABLE_NAME, columns,
selection, selectionArgs, null, null, null);
if (cursor != null) {
startManagingCursor(cursor);
while (cursor.moveToNext()) {
idddd = cursor.getString(0);
}
return idddd;
}
System.out.println("Cursor NuLL");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private String getBAL(String uname, String pass,
DatabaseActivity databaseActivity) {
try {
String ballll = null;
SQLiteDatabase db = myDb.getReadableDatabase();
String[] columns = { "balance" };
// WHERE clause
String selection = "username=? AND password=?";
// WHERE clause arguments
String[] selectionArgs = { uname, pass };
Cursor cursor = db.query(DbHelper.SUBH_TABLE_NAME, columns,
selection, selectionArgs, null, null, null);
if (cursor != null) {
startManagingCursor(cursor);
while (cursor.moveToNext()) {
ballll = cursor.getString(0);
}
return ballll;
}
System.out.println("Cursor NuLL");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onDestroy() {
super.onDestroy();
if (myDb != null && cursor != null ) {
cursor.close();
myDb.close();
}
}
}

Categories

Resources