I'm hoping my question isn't too broad. What I would really like to know is how to tell exactly where my code is hitting a wall.
I'm not getting errors from my debugger, the app just crashes when the emulator starts an activity that uses a sqlite database (3rd activity in). I am positive it is the addition of sqlite into my code that causes the crash because it ran before I added it.
This code simply needs to access and read from an external database that I created and pasted into the assets folder. I reviewed the sqlite database in firefox's SQLite Manager; the information seems to be formatted correctly.
I created an assets folder within app/src/Main to facilitate the addition of the external database "ex3.db". Then I copied and pasted the database file there.
So here is the code. LetterImage is a class that holds strings retrieved from the sqlite database. MyDBHandler creates an empty database, copies the old one into it, and fills LetterImage with the values returned from a query based on a string. LoadSubjectActivity calls them both to search the database and return a string.
LetterImage:
public class LetterImage {
private Integer _ID;
private String _letter;
private String _bigfilename;
private String _littlefilename;
//Constructor(s)
public LetterImage(){
}
public LetterImage(Integer ID, String letter, String bigfilename, String littlefilename){
this._ID = ID;
this._letter = letter;
this._bigfilename = bigfilename;
this._littlefilename = littlefilename;
}
public LetterImage(String letter){
this._letter = letter;
}
//End Constructors
//Begin setters and getters
//ID is primary key
public void setID(Integer ID){
this._ID = ID;
}
public Integer getID(){
return this._ID;
}
//letter is main identifier used to search database
// passed to LoadSubjectActivity
// from ChooseSubjectABCActivity as extra from intent
public void setLetter(String letter){
this._letter = letter;
}
public String getLetter(){
return this._letter;
}
//Capital letter image file name
public void setBigFileName(String bigfilename){
this._bigfilename = bigfilename;
}
public String getBigFileName(){
return this._bigfilename;
}
//Lowercase Letter image file name
public void setLittleFileName(String littlefilename){
this._littlefilename = littlefilename;
}
public String getLittleFileName(){
return this._littlefilename;
}
}
Now, here is MyDBHandler:
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.database.Cursor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
public class MyDBHandler extends SQLiteOpenHelper{
private final Context myContext;
private static Context context;
private static final int DATABASE_VERSION = 1;
private static String DB_PATH = "data/data" + context.getPackageName() + "/databases/";
private static final String DATABASE_NAME = "ex3.db";
public static final String TABLE_IMAGES = "tbl1";
private SQLiteDatabase myDataBase;
//Fields in Database
public static final String COLUMN_ID = "_id";
public static final String COLUMN_BIGIMAGEFILE = "bigImage";
public static final String COLUMN_LITTLEIMAGEFILE = "littleImage";
public static final String COLUMN_LETTER = "letter";
//Constructor
public MyDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.myContext = context;
}
//if there is no existing database, create an empty one
public void createDatabase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist) {
//do nothing
}else {
//call this method and create an empty database
this.getReadableDatabase();
try {
copyDataBase();
} catch(IOException e){
throw new Error("Error copying database");
}
}
}
//check to see if there is an existing database
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e){
throw new Error("Unable to open database");
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
//fills new empty database with existing database ex3
private void copyDataBase() throws IOException{
InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
String outFileName = DB_PATH + DATABASE_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
//opens the new database
public void openDatabase() throws SQLException {
String myPath = DB_PATH + DATABASE_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close(){
if(myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db){
}
#Override
public void onUpgrade(SQLiteDatabase db, int OldVersion, int newVersion){
}
//creates an instance of letter LetterImage
//queries the new database by searching for the row with where the value of COLUMN_LETTER = letter
//fills LetterImage with the values from that row
public LetterImage findLetter(String letter) {
String query = "Select * FROM " + TABLE_IMAGES + " WHERE " + COLUMN_LETTER + " = \"" + letter + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
LetterImage LetterImage = new LetterImage();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
LetterImage.setID(Integer.parseInt(cursor.getString(0)));
LetterImage.setBigFileName(cursor.getString(1));
LetterImage.setLittleFileName(cursor.getString(2));
LetterImage.setLetter(cursor.getString(3));
cursor.close();
} else {
LetterImage = null;
}
db.close();
return LetterImage;
}
}
Finally, here are the pertinent parts of the LoadSubjectActivity class:
public class LoadSubjectActivity extends MainActivity{
private DrawingView drawView;
private ImageButton currPaint;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_load_subject);
//receives string letter, from last activity
//letter will be used to search array and return files names of the images to be used
Intent intent = getIntent();
String letter = intent.getExtras().getString("letter");
//displayFN calls testDB(letter) to test the database
//It should simply display the string returned by testDB()
TextView displayFN = (TextView)findViewById(R.id.display_filenames);
displayFN.setText(testDB(letter.toLowerCase()));
//Eventually, button images will be filled dynamically
ImageButton bigLetter = (ImageButton)findViewById(R.id.big_letter);
ImageButton littleLetter = (ImageButton)findViewById(R.id.little_letter);
bigLetter.setImageResource(R.drawable.biga);
littleLetter.setImageResource(R.drawable.littlea);
drawView = (DrawingView)findViewById(R.id.drawing);
LinearLayout paintLayout = (LinearLayout)findViewById(R.id.paint_colors);
currPaint = (ImageButton)paintLayout.getChildAt(0);
currPaint.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.paint_pressed));
}
//Function to test the database takes a string as an argument to search the database
public String testDB(String letter){
//create a new instance of dbHandler
MyDBHandler dbHandler = new MyDBHandler(this);
//try to either create an empty database or open the existing one
try{
dbHandler.createDatabase();
} catch (IOException ioe){
throw new Error("Unable to create database");
}
try{
dbHandler.openDatabase();
} catch(SQLException sqle){
sqle.printStackTrace();
throw new Error ("unable to open database");
}
LetterImage letterImage = dbHandler.findLetter(letter);
String blFileName = letterImage.getBigFileName();
//return the big letter image file name;
return blFileName;
}
Anyway, I apologize in advance for any obvious problems. I have traced the logic to the best of my ability...I am teaching myself java and sql...this is my first android project. Any and all insight is greatly appreciated.
I figured out one way to fix this:
1.) rewrite checkDatabase(). I referenced this tutorial: How to use an existing database with an Android application, and found this:
private boolean checkDataBase(){
File dbFile = new File(DB_PATH + DATABASE_NAME);
//Log.v("dbFile", dbFile + " "+ dbFile.exists());
return dbFile.exists();
}
2.) Hard code DB_PATH name, since context.getFilesDir and getDatabasePath() weren't returning the paths I needed.
***going through logcat and tracing the errors back to the exact place the problem started was how I found what I needed to change. In this instance, checkDatabase() wasn't returning false to createDatabase(), so the code was trying to open a database that didn't exist.
Related
I am learning android yet and not expert. I think I have some logic issue in handle my sqllite database. Let me explain what I am doing and what I am getting.
I have one application of quotes. I am providing local database as well online. I have included database file in Assets and copying database from it during first time when user open application from splash screen. After that I am checking last author and last quote number of local database which are stored in user's device and comparing with online database. If there new data in online then I am downloading and storing it in splash screen.
Now my splash screen code for do same is like below
DAO database=DAO.getInstance(this);
int lastAuthor =database.getLastAuthor();
String updatesUrl = constant.MainUrl + String.valueOf(lastAuthor)+ "/" + String.valueOf(lastQuote);
My DAO class is looking like this
public class DAO {
private SQLiteDatabase database;
private DBHandler dbHandler;
private static final String TABLE_QUOTES = "quotes";
private static final String TABLE_AUTHORS = "authors";
private static final String TABLE_SETTINGS = "settings";
private static final String QU_ID = "_quid";
private static final String QU_TEXT = "qu_text";
private static final String QU_AUTHOR = "qu_author";
private static final String QU_FAVORITE = "qu_favorite";
private static final String QU_TIME = "qu_time";
private static final String AU_NAME = "au_name";
private static final String AU_PICTURE = "au_picture";
private static final String AU_PICTURE_SDCARD = "au_picture_sdcard";
private static final String AU_WEB_ID = "au_web_id";
private static DAO dBObject;
private final Object lockObj=new Object();
public static DAO getInstance(Context context){
if(dBObject==null)dBObject=new DAO(context);
return dBObject;
}
private DAO(Context context) {
synchronized (lockObj) {
dbHandler = new DBHandler(context);
try {
dbHandler.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
dbHandler.openDataBase();
open();
}
}
public int getLastAuthor() {
String query = "SELECT " + AU_WEB_ID + " FROM " + TABLE_AUTHORS
+ " ORDER BY " + AU_WEB_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
int tmp = cursor.getInt(cursor.getColumnIndex(AU_WEB_ID));
cursor.close();
return tmp;
}
// ==============================================================================
public int getLastQuote() {
String query = "SELECT " + QU_ID + " FROM " + TABLE_QUOTES
+ " ORDER BY " + QU_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
int tmp = cursor.getInt(cursor.getColumnIndex(QU_ID));
cursor.close();
return tmp;
}
// ==============================================================================
public void addAuthor(String au_name, String au_picture, int au_web_id) {
open();
ContentValues v = new ContentValues();
v.put(AU_NAME, au_name);
v.put(AU_PICTURE, au_picture);
v.put(AU_PICTURE_SDCARD, 1);
v.put(AU_WEB_ID, au_web_id);
database.insert(TABLE_AUTHORS, null, v);
}
// ==============================================================================
public void addQuote(String qu_text, int qu_author, int _quid, String qu_time) {
open();
ContentValues v = new ContentValues();
v.put(QU_TEXT, qu_text);
v.put(QU_AUTHOR, qu_author);
v.put(QU_FAVORITE, "0");
v.put(QU_ID, _quid);
v.put(QU_TIME, qu_time);
database.insert(TABLE_QUOTES, null, v);
}
// ==============================================================================
//method changed
private void open() throws SQLException {
if(database!=null&&database.isOpen())return; //changed line
database = dbHandler.getWritableDatabase();
}
// ==============================================================================
public void closeDAO(){
synchronized (lockObj){
if(dbHandler!=null)dbHandler.close();
dbHandler=null;
database=null;
}
}
public static void dispose(){
if(dBObject!=null){
dBObject.closeDAO();
}
dBObject=null;
}
}
And My database handler class looking like this
public class DBHandler extends SQLiteOpenHelper {
private static String DB_PATH;
private static String DB_NAME = "xxx";
private SQLiteDatabase myDataBase;
private final Context myContext;
public DBHandler(Context context) {
super(context, DB_NAME, null, constant.DATABASE_VERSION);
this.myContext = context;
DB_PATH = context.getDatabasePath(DB_NAME).toString();
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
// ==============================================================================
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
// ==============================================================================
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
// ==============================================================================
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
// ==============================================================================
#Override
public void onCreate(SQLiteDatabase db) {
}
// ==============================================================================
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
I am getting errors in logcat like this
Failed to open database '/data/user/0/com.newdeveloper.test/databases/xxx'.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:835)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:820)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:723)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:692)
at com.newdeveloper.test.utility.DBHandler.checkDataBase(DBHandler.java:69)
at com.newdeveloper.test.utility.DBHandler.createDataBase(DBHandler.java:32)
at com.newdeveloper.test.utility.DAO.<init>(DAO.java:41)
at com.newdeveloper.test.utility.DAO.getInstance(DAO.java:31)
at com.newdeveloper.test.activities.SplashScreensActivity.checkForUpdate(SplashScreensActivity.java:111)
at com.newdeveloper.test.activities.SplashScreensActivity.access$000(SplashScreensActivity.java:41)
at com.newdeveloper.test.activities.SplashScreensActivity$1.onAnimationEnd(SplashScreensActivity.java:98)
at android.view.animation.AnimationSet.getTransformation(AnimationSet.java:400)
However application does not getting crashed and working fine as I
need. But This errors are confusing me what I need to change for
resolve this errors. I am trying to solve from last two days but not
found any working solution for it. Let me know if any senior developer
can help me for come out from this. Thanks
If you are not already using a bundled database with your apk, you have not actually created the database here in your code.
#Override
public void onCreate(SQLiteDatabase db) {
//you must create the database here
}
// ==============================================================================
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Handle the database update here
}
You need to do something like this.
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_STRING);
} catch (SQLException e) {
e.printStackTrace();
}
Log.e(TAG, "Table Created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_STRING);
onCreate(db);
Log.d(TAG, "Table upgraded to Version :" + newVersion);
}
I would also recommend to start using ROOM Android Architecture Component, which provides much better abstraction level for the Sqlite for the pattern are using.
I'm new to StackOverflow so I'm not sure how this works, but I really need some help with this app I'm building in Android Studio. I have a pre-populated chemicals.sqlite database that I am trying to search through in Android Studio. Basically, the app I'm designing is going to allow a user to search for a compound by name and it will display information about it. For some reason, my program is saying that it can't display any of the values that I'm trying to search in the app's emulator. It just always shows the "No Match Found".
Here is my DatabaseHelper class:
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "chemicals.sqlite";
private static final String TABLE_OSHA = "osha";
public static final String COLUMN_COMPOUND = "compound";
public static final String COLUMN_H = "h";
public static final String COLUMN_F = "f";
public static final String COLUMN_R = "r";
public static final String COLUMN_SN = "sn";
public DataBaseHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_OSHA_TABLE = "CREATE TABLE " +
TABLE_OSHA + "("
+ COLUMN_COMPOUND + " TEXT," + COLUMN_H
+ " TEXT," + COLUMN_F + " TEXT," + COLUMN_R + " TEXT," + COLUMN_SN + " TEXT" + ")";
db.execSQL(CREATE_OSHA_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_OSHA);
onCreate(db);
}
public Compound findCompound(String compoundname) {
String query = "Select * FROM " + TABLE_OSHA + " WHERE " + COLUMN_COMPOUND + "= '" + compoundname + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Compound compound = new Compound();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
compound.setH(cursor.getString(0));
compound.setF(cursor.getString(1));
compound.setR(cursor.getString(2));
compound.setSN(cursor.getString(3));
// cursor.moveToNext();
cursor.close();
} else {
compound = null;
}
db.close();
return compound;
}
}
Here is my compound class:
public class Compound {
private String _compound;
private String _h;
private String _f;
private String _r;
private String _sn;
public Compound() {
}
public Compound(String compound, String h, String f, String r, String sn) {
this._compound = compound;
this._h = h;
this._f = f;
this._r = r;
this._sn = sn;
}
public Compound(String h, String f, String r, String sn) {
this._h = h;
this._f = f;
this._r = r;
this._sn = sn;
}
public void setCompound(String compound) {
this._compound = compound;
}
public String getCompound() {
return this._compound;
}
public void setH(String h) {
this._h = h;
}
public String getH() {
return this._h;
}
public void setF(String f) {
this._f = f;
}
public String getF() {
return this._f;
}
public void setR(String r) {
this._r = r;
}
public String getR(){
return this._r;
}
public void setSN(String sn){
this._sn = sn;
}
public String getSN(){
return this._sn;
}
}
And here is my main class:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class oshaSearch extends AppCompatActivity {
TextView txtH;
TextView txtR;
TextView txtF;
TextView txtSN;
EditText txtCompound;
Button btnSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_osha_search);
txtF = (TextView) findViewById(R.id.txtF);
txtR = (TextView) findViewById(R.id.txtR);
txtH = (TextView) findViewById(R.id.txtH);
txtSN = (TextView) findViewById(R.id.txtSN);
txtCompound = (EditText) findViewById(R.id.searchCompound);
btnSearch = (Button) findViewById(R.id.btnSearch);
}
public void lookupCompound (View view) {
DataBaseHelper dbHandler = new DataBaseHelper(this, null, null, 1);
Compound compound =
dbHandler.findCompound(txtCompound.getText().toString());
if (compound != null) {
txtH.setText(String.valueOf(compound.getH()));
txtF.setText(String.valueOf(compound.getF()));
txtR.setText(String.valueOf(compound.getR()));
txtSN.setText(String.valueOf(compound.getSN()));
} else {
txtH.setText("No Match Found");
}
}
}
Any and all help is greatly appreciated. Please help me out.
Additional information: The database is in the assets folder, All values in the database are text fields, The user is searching by compound name, The database has a .sqlite extension. Thank you all in advanced.
You have to copy your database which you said is in the assets folder to newly created database -
private void copyDataBase(String dbname) throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(dbname);
// Path to the just created empty db
String outFileName = getDatabasePath(dbname);
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
you first need to check if database is properly created or not, for that
public DataBaseHelper(Context context) {
super(context, Environment.getExternalStorageDirectory()+"/"+DATABASE_NAME, null, 1);
}
use this constructor , this will save your app database in external storage of your phone.
before that give permission to external storage in manifest file.
and use sqliteManager application from google play store to check database structure.
Or you can use stetho to debug database of android.
reference link:http://code.tutsplus.com/tutorials/debugging-android-apps-with-facebooks-stetho--cms-24205
I need to show my data on a ListView everything is correct but When i run this project i get this error :
(1) no such table: WebSite_CategoryBack
My DataBase is correct .I think that my code has error.
This is my MainActivity.java:
public class MainActivity extends ActionBarActivity {
public static Context context;
public static final String DIR_SDCARD =Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_DATABASE = DIR_SDCARD + "/Mafatih/";
DB db = new DB(MainActivity.this);
public String Titel_Drawer;
public String messageCursor;
private ListView mainListView ;
public SQLiteDatabase sql;
public Cursor cursor;
public ArrayList<String> array;
private ArrayAdapter<String> listAdapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File file= new File(DIR_DATABASE);
file.mkdirs();
try{
db.createDataBase();
}catch (IOException e) {
Log.e("create DB3", e.toString());
}
try{
db.openDataBase();
}catch (SQLException e) {
Log.e("create DB3", e.toString());
}
sql = db.getReadableDatabase();
cursor = sql.rawQuery("SELECT * FROM WebSite_CategoryBack;", null);
array = new ArrayList<String>();
while(cursor.moveToNext()){
Titel_Drawer = cursor.getString(cursor.getColumnIndex("tittle"));
array.add(Titel_Drawer);
}
cursor.close();
mainListView = (ListView) findViewById( R.id.mainListView );
listAdapter = new ArrayAdapter<String>(this, R.layout.drawer_layout_main,R.id.rowTextView_Main, array);
mainListView.setAdapter( listAdapter );
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
int itemposition = position;
String itemvalue = (String) mainListView.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
"Position :"+itemposition+" ListItem : " +itemvalue , Toast.LENGTH_LONG).show();
}
});
mainListView.setTextFilterEnabled(true);
}
And this is my DB.java:
public class DB extends SQLiteOpenHelper{
public static final String DIR_SDCARD =Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_DATABASE = DIR_SDCARD + "/Mafatih/";
private static String DB_NAME = "Resaleh.db";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* #param context
*/
public DB(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database --> "+e.toString());
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DIR_DATABASE + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
Log.e("asdf", "checkDataBase-->"+e.toString());
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#getReadableDatabase()
*/
#Override
public synchronized SQLiteDatabase getReadableDatabase() {
return super.getReadableDatabase();
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DIR_DATABASE + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
try{
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
}catch (IOException e) {
Log.e("Copy", e.toString());
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DIR_DATABASE + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY|SQLiteDatabase.NO_LOCALIZED_COLLATORS);
}
#Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
THANKS.
There is one good reason why this error will come and i used to get this...
The reason why i got was like i created the db without THAT TABLE now when during course of time if i add a new table then it wont appear and i used to get the error so to make it fresh i used to do the following :-
rename DB.
change version of DB.
uninstall the app.
now install the app.
This used to solve the issue in my case...
thx
By default the SQLite DB is created and saved in the path : data/data/.... on internal storage and opened from there. In case we want to save it on SD card, the address should be manually set and called exactly from the SD card otherwise we will have error.
The correct code is:
public class MainActivity extends ActionBarActivity {
public static Context context;
public static final String DIR_SDCARD =Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_DATABASE = DIR_SDCARD + "/Mafatih/";
public String Titel_Drawer;
public String messageCursor;
private ListView mainListView ;
public SQLiteDatabase sql;
public Cursor cursor;
public ArrayList<String> array;
private ArrayAdapter<String> listAdapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File file= new File(DIR_DATABASE);
file.mkdirs();
sql = SQLiteDatabase.openOrCreateDatabase(DIR_DATABASE + "/Resaleh.db", null);
cursor = sql.rawQuery("SELECT * FROM WebSite_CategoryBack;", null);
array = new ArrayList<String>();
while(cursor.moveToNext()){
Titel_Drawer = cursor.getString(cursor.getColumnIndex("tittle"));
array.add(Titel_Drawer);
}
cursor.close();
mainListView = (ListView) findViewById( R.id.mainListView );
listAdapter = new ArrayAdapter<String>(this, R.layout.drawer_layout_main,R.id.rowTextView_Main, array);
mainListView.setAdapter( listAdapter );
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
int itemposition = position;
String itemvalue = (String) mainListView.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
"Position :"+itemposition+" ListItem : " +itemvalue , Toast.LENGTH_LONG).show();
}
});
mainListView.setTextFilterEnabled(true);
}
Delete the DB.java.THANKS.
I'm entirely new to Android Java, especially database linkage. So far I've got this, which all seems to work, I just now need to get the database values from the database to an array.
package com.example.sleepertrain5;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHelper extends SQLiteOpenHelper{
private static String DB_PATH = "/sleepertrain5/assets";
private static String DB_NAME="info2.sqlite";
private SQLiteDatabase myDatabase;
private final Context myContext;
public DataBaseHelper(Context context){
super(context, DB_NAME, null, 1);
this.myContext=context;
}
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
//nothing needs done
}else{
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e){
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//no databases they don't exist
}
if (checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException{
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH +DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length=myInput.read(buffer))>0){
myOutput.write(buffer,0,length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
//Open database
String myPath = DB_PATH + DB_NAME;
myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
public synchronized void close(){
if(myDatabase != null)
myDatabase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
How would I go about reading from this into an array? I'm struggling to make sense of this at the moment, so any help would be fantastic.
EDIT: The plan is to read the data, which is coordinates and names, into the array, which I can then use later to draw markers onto a GoogleMap. GoogleMap is all set up and I think I know what I'm doing from there, but this is the part I fall down on. The array would have to be multidimensional.
Ok, so the easiest way to work with SQLite in my opinion is using this three-class approach. I've read through a few tutorials and neither really did the trick for me....
So, here we go.
Table definition
package com.test.sqlite;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class ContactTable
{
//key identifiers / column names
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_URI = "uri";
public static final String TABLE_NAME = "contacts";
//useful stuff
public static final String[] TABLE_COLUMNS = { KEY_ROWID, KEY_NAME, KEY_URI }; //public makes it more useful
private static final String[] TABLE_COLTYPES = { "integer primary key autoincrement", "text not null", "text not null" };
// Database creation SQL statement in lazy-pretty version
private static final String TABLE_CREATE = "create table " + TABLE_NAME + "("
+ TABLE_COLUMNS[0] + " " + TABLE_COLTYPES[0] + ","
+ TABLE_COLUMNS[1] + " " + TABLE_COLTYPES[1] + ","
+ TABLE_COLUMNS[2] + " " + TABLE_COLTYPES[2] + ");";
private static final String LOGTAG = "ContactTable";
public static void onCreate(SQLiteDatabase database)
{
database.execSQL(TABLE_CREATE);
}
public static void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion)
{
Log.w(LOGTAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(database);
}
public static void scratch(SQLiteDatabase database)
{
database.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
database.execSQL(TABLE_CREATE);
}
}
Now that we have set that up, we need Database Helper class, to ease the use of it.
The helper class
package com.test.sqlite;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class ContactDBHelper extends SQLiteOpenHelper
{
// 'main' package name
private static final String PACKAGE_NAME = "com.test.demo";
private static final String DATABASE_PATH = "/data/data/" + PACKAGE_NAME + "/databases/";
private static final String DATABASE_NAME = "contactdata";
private static final int DATABASE_VERSION = 1;
private Context myContext;
public ContactDBHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
myContext = context;
}
// Method is called during creation of the database
#Override
public void onCreate(SQLiteDatabase database)
{
ContactTable.onCreate(database);
}
// Method is called during an upgrade of the database,
// e.g. if you increase the database version
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion)
{
ContactTable.onUpgrade(database, oldVersion, newVersion);
}
public void scratch(SQLiteDatabase database)
{
ContactTable.scratch(database);
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void createDataBase() throws IOException
{
boolean dbExist = checkDataBase();
if (dbExist)
{
// do nothing - database already exist
} else
{
// By calling this method and empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
File dirFile = new File(DATABASE_PATH);
if (!dirFile.exists())
{
dirFile.mkdir();
}
this.getReadableDatabase();
try
{
copyDataBase();
} catch (IOException e)
{
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase()
{
SQLiteDatabase checkDB = null;
try
{
String myPath = DATABASE_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e)
{
// database does't exist yet.
}
if (checkDB != null) checkDB.close();
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException
{
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
// Path to the just created empty db
String outFileName = DATABASE_PATH + DATABASE_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0)
{
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
/*
public void openDataBase() throws SQLException
{
// Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
*/
}
And finally, the adapter, which totally does what you want.
DatabaseAdapter
package com.test.sqlite;
import java.util.ArrayList;
import com.test.demo.Contact;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import static com.test.sqlite.ContactTable.*; //contains database fields
public class ContactDBAdapter
{
private Context context;
private SQLiteDatabase db;
private ContactDBHelper dbHelper;
public ContactDBAdapter(Context context)
{
this.context = context;
}
public synchronized ContactDBAdapter open() throws SQLException
{
dbHelper = new ContactDBHelper(context);
db = dbHelper.getWritableDatabase();
return this;
}
public synchronized void close()
{
dbHelper.close();
}
/**
* Create a new Contact entry. If the entry is successfully created return the new
* rowId for that note, otherwise return a -1 to indicate failure.
*/
public long createRow(Contact contact)
{
ContentValues values = createContentValue(contact);
return db.insert(TABLE_NAME, null, values);
}
/**
* Update a row / entry
*/
public boolean updateRow(long rowIndex, Contact contact)
{
ContentValues values = createContentValue(contact);
return db.update(TABLE_NAME, values, KEY_ROWID + "=" + rowIndex, null) > 0;
}
/**
* Deletes a row
*/
public boolean deleteRow(long rowIndex)
{
return db.delete(TABLE_NAME, KEY_ROWID + "=" + rowIndex, null) > 0;
}
public void deleteAllRows()
{
for(int i = 0; i < fetchAllEntries().getCount(); i++)
deleteRow(i);
}
/**
* Return a Cursor over the list of all Contacts in the database
*
* #return Cursor over all contacts
*/
public Cursor fetchAllEntries()
{
return db.query(TABLE_NAME, TABLE_COLUMNS, null, null, null, null, null);
}
/**
* Return a Cursor positioned at the defined Contact
*/
public Cursor fetchEntry(long rowIndex) throws SQLException
{
Cursor mCursor = db.query(true, TABLE_NAME, TABLE_COLUMNS, KEY_ROWID + "=" + rowIndex, null, null, null, null, null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
/**
* Fetch all entries and rebuild them as Contact objects in an ArrayList.
* If no results are found, an empty list is returned.
*
* #return ArrayList of Contacts
*/
public ArrayList<Contact> fetchAllContacts()
{
ArrayList<Contact> res = new ArrayList<Contact>();
Cursor resultSet = fetchAllEntries();
if (resultSet.moveToFirst() != false)
for(int i = 0; i < resultSet.getCount(); i++)
{
String name = resultSet.getString(resultSet.getColumnIndex(KEY_NAME));
String URI = resultSet.getString(resultSet.getColumnIndex(KEY_URI));
Contact c = new Contact(name, URI);
res.add(c);
if(resultSet.moveToNext() == false)
break;
}
resultSet.close();
return res;
}
public synchronized void reflectWith(ArrayList<Contact> contacts)
{
// deleteAllRows();
dbHelper.scratch(db);
contacts.trimToSize();
//empty contact
Contact empty = new Contact();
empty.empty();
for(Contact c : contacts)
{
if(!c.getName().equals(empty.getName()))
createRow(c); //if not empty, add it
}
}
private ContentValues createContentValue(Contact contact)
{
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_URI, contact.getURI());
return values;
}
}
this is how it's used:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
dbAdapter = new ContactDBAdapter(getApplicationContext());
dbAdapter.open();
setContentView(R.layout.main);
// list stuff
contacts = new ArrayList<Contact>();
contacts = dbAdapter.fetchAllContacts();
//empty placeholders
if (contacts.size() < 5) for (int i = 0; i < 5 - contacts.size(); i++)
{
Contact c = new Contact();
c.empty();
contacts.add(c);
}
// contacts.addAll(dbAdapter.fetchAllContacts());
...
}
If you have questions, do ask.
Android uses SQLite database and SQLite query syntax for database accessing.
For querying the database directly through the SQLiteDatabase db variable you can do:
String table = CONTACT_TABLE;
String columns = {CONTACT_COLUMN_NAME};
String selection = CONTACT_COLUMN_NAME + "=" + MY_NAME;
String[] selectionArgs = {"wangyif2"};
Cursor c = db.query(table, columns, selection, selectionArgs, null, null, null, null);
This will return you a Cursor object, which you can understand as an iterator that contains all the result matching your query. You can then step through the cursor like you would with any array that is converted to an iterator.
c.moveToFirst();
while (!c.isAfterLast())
{
arr[i] = cur.getString(0);
i++;
c.moveToNext();
}
So I've run into a peculiar problem. I am trying to write a data file to the device. I developed the app in eclipse under 2.2, my device is 2.3.3, so I made the emulator run at 2.3.3, it writes files fine. Why does this not work on the device? It also is coded to copy the database file on the device to a php server. On the server the file is essentially empty, i pulled the db file from the device as well and it's empty. The only time it works is on the emulator, i get a legit file on the server and when i pull the database it's got data in it. I'm so lost. If you want to see some code then ask, I would have posted some but with 40+ classes I really don't know where to begin.
Thanks in advance.
Here is code relating to the database creation
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "database";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table database (_id integer primary key autoincrement," +
"name text not null);";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method is called during creation of the database
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
// Method is called during an upgrade of the database, e.g. if you increase
// the database version
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
Log.w(DbHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS database");
onCreate(database);
}
}
here is the adapter..
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DbAdapter {
// Database fields
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
static final String DATABASE_TABLE = "database";
private Context context;
private SQLiteDatabase database;
private DbHelper dbHelper;
public DbAdapter(Context ctx) {
context = ctx;
}
public SQLiteDatabase openToRead() throws SQLException {
dbHelper = new DbHelper(context);
database = dbHelper.getReadableDatabase();
return database;
}
public SQLiteDatabase open() throws SQLException {
dbHelper = new DbHelper(context);
database = dbHelper.getWritableDatabase();
return database;
}
public void close() {
dbHelper.close();
}
//
/**
* Create a new todo If the todo is successfully created return the new
* rowId for that note, otherwise return a -1 to indicate failure.
*/
public long createRow(String name) {
ContentValues initialValues = createContentValues(name);
return database.insert(DATABASE_TABLE, null, initialValues);
}
/**
* Update the todo
*/
public boolean updateRows(long rowId,
String name) {
ContentValues updateValues = createContentValues(
name);
return database.update(DATABASE_TABLE, updateValues, KEY_ROWID + "="
+ rowId, null) > 0;
}
/**
* Deletes todo
*/
public boolean deleteRow(long rowId) {
return database.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
/**
* Return a Cursor over the list of all todo in the database
*
* #return Cursor over all notes
*/
public Cursor fetchAllRows() {
return database.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME}, null, null, null,
null, null);
}
/**
* Return a Cursor positioned at the defined todo
*/
public Cursor fetchRow(long rowId) throws SQLException {
Cursor mCursor = database.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID ,KEY_NAME},
KEY_ROWID + "=" + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
/**fetches keyword**/
public Cursor fetchKeyword(String keyword, String column, String[] columns) throws SQLException {
Cursor mCursor = database.query(DATABASE_TABLE, columns, column + "='" + keyword + "'",
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
private ContentValues createContentValues(String name){
ContentValues values = new ContentValues();
values.put(KEY_NAME, name);
return values;
}
//returns (an) entire column(s), all rows
public Cursor fetchColumns(String[] colnames) {
Cursor mCursor = database.query(DATABASE_TABLE, colnames, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
Ok, I've Isolated it to these three classes.. below is the class that creates the entry and uploads it to the server. as far as i can tell the database isn't being created the right way.. as in there are no tables in the file
public class CreateName extends Activity{
//variables
private DbAdapter mDbHelper;
EditText textField;
TextView txtEnter2;
TextView txtEnter;
Button btnSubmit;
Context context;
SharedPreferences prefs;
SharedPreferences.Editor spe;
SQLiteDatabase db;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.submit);
//constructors
context = getApplicationContext();
prefs = PreferenceManager.getDefaultSharedPreferences(context);
spe = prefs.edit();
init();
listen();
}
public void checker() {
Intent i = new Intent(this, MoveForward.class);
startActivity(i);
}
private void listen() {
btnSubmit.setOnClickListener(new Button.OnClickListener()
{
public void onClick (View v)
{
mDbHelper = new DbAdapter(context);
String words = textField.getText().toString();
Log.v(words, words);
mDbHelper.open();
mDbHelper.createRow(words);
mDbHelper.close();
spe.putString("name", words);
spe.commit();
PHPBuddy buddy = new PHPBuddy();
try {
buddy.uploadFile("database");
} catch (Exception e) {
// ask the user to retry
e.printStackTrace();
}
checker();
}
}
);
}
private void init() {
textField = (EditText)findViewById(R.id.edtTxt);
txtEnter2 = (TextView)findViewById(R.id.txtEnter2);
txtEnter = (TextView)findViewById(R.id.txtEnter);
btnSubmit =(Button)findViewById(R.id.btnSubmit);
txtEnter.setText("Enter your proper name");
txtEnter2.setText("ex: John Smith");
}
}
Maybe there is a cursor or db i'm forgetting to close?
Here is more code..
public class SBMain extends Activity {
Button btnSpinner;
String[] items;
String text;
Spinner s;
Intent i, j;
int activity;
SharedPreferences prefs;
SharedPreferences.Editor spe;
SQLiteDatabase db;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinnerscreen);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
spe = prefs.edit();
init();
fillSpinner();
btnSpinner.setOnClickListener(new Button.OnClickListener()
{
public void onClick (View v)
{
Cursor cc = (Cursor)(s.getSelectedItem());
if (cc != null) {
text = cc.getString(cc.getColumnIndex("name"));
}
checker();
}
});
}
public void checker() {
if (text .equals("Create Name")){
i = new Intent(this, GetName.class);
spe.putString("name", text);
spe.commit();
startActivity(i);
}else{
spe.putString("name", text);
spe.commit();
i = new Intent(this, MoveForward.class);
startActivity(i);
}
}
private void fillSpinner(){
DbAdapter mDbHelper = new DbAdapter(this);
mDbHelper.open();
Cursor c = mDbHelper.fetchColumns(new String[] {"_id","name"});;
if ( ! c.moveToFirst() ){
c.close();
mDbHelper.createRow("Create Name");
mDbHelper.close();
c = mDbHelper.fetchColumns(new String[] {"_id","name"});
}else{
mDbHelper.close();
}
// create an array to specify which fields we want to display
String[] from = new String[]{"name"};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
// create simple cursor adapter
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
s.setAdapter(adapter);
}
private void init() {
btnSpinner = (Button)findViewById(R.id.btnSpinner);
s = (Spinner) findViewById( R.id.spinner1 );
}
}
Here is the splash activity that downloads the file
public class Splash extends Activity{
String file_url = "http://ipaddress/xampp/uploads/";
Context context = this;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread splashThread = new Thread() {
#Override
public void run() {
float percent = 0;
try {
int waited = 0;
int time = 1000;
while (waited < time) {
sleep(100);
waited += 100;
String perc = Integer.toString(waited / time);
}
} catch (InterruptedException e) {
// do nothing
} finally {
//if this is the apps first time running, get a list of names.
if(isFirstRun()){
PHPBuddy buddy = new PHPBuddy();
try {
buddy.downloadFile("database");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//ToDo add spared prefs editor to set isfirstrun to true
Intent i = new Intent();
i.setClassName("com.project",
"com.project.SBMain");
startActivity(i);
}else{
//make registered user page
Intent i = new Intent();
//ToDo add spared prefs editor to set isfrstrun to false
//ToDo add intent for true
}
finish();
}
}
};
splashThread.start();
}
public boolean isFirstRun(){
String rb = "isfirstrun";
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor spe;
spe = prefs.edit();
//spe.putBoolean("isfirstrun", true);
//boolean test = prefs.getBoolean(rb, true);
return true;//prefs.getBoolean(rb, true);
}
}
here is the php
<?php
$myFile = "requestslog.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, "\n\n---------------------------------------------------------------\n");
foreach($_SERVER as $h=>$v)
if(ereg('HTTP_(.+)',$h,$hp))
fwrite($fh, "$h = $v\n");
fwrite($fh, "\r\n");
fwrite($fh, file_get_contents('php://input'));
fclose($fh);
echo "<html><head /><body><iframe src=\"$myFile\" style=\"height:100%; width:100%;\"> </iframe></body></html>"
?>
<?php
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $_FILES['userfile'] ['name']);
} else {
echo "Possible file upload attack: ";
echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
print_r($_FILES);
}
?>
my first guess is that you are trying to write the database somewhere where you don't have permission.
i would recommend using the method File getDir (String name, int mode) of your Activity to get a folder inside your app where you can read and write.
I think I figured it out.
First I set up a class that would copy the database to the SD card right after it was created; from there, I examined the file and saw that it was indeed intact.
Then, I moved the copy call to the place right before the database gets sent to the server. It didn't look fine in "SQLite Database Browser," so I opened it up in Firefox's SQLite manager and voila, all the data was there. So, with Firefox I go and look at the file that was uploaded to the server. What looked empty in the SQLite Database Browser has data in it!