android How to load sqlite data in Asyntask in android - java

I'm new to java and android. I want to get sqlite rows in a asyntask class .but it return NullpointerException
i don't know how to pass the key can anybody tell me what is the correct way to achieve this.
class database
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION=1;
private static final String DATABASE_NAME="cloud_contacts";
public static final String TABLE_LOGIN="login";
public static final String KEY_ID="id";
private static final String KEY_USERNAME="uname";
private static final String KEY_PASSWORD="password";
public static final String KEY_USERNAME_DEVICE="unamedevice";
public static final String KEY_PASSWORD_DEVICE="passworddevice";
private static final String CREATE_LOGIN_TABLE="CREATE TABLE "+TABLE_LOGIN + " ("
+KEY_ID+" INTEGER PRIMARY KEY, "
+KEY_USERNAME + " TEXT, "
+KEY_PASSWORD + " TEXT, "
+KEY_USERNAME_DEVICE + " TEXT, "
+KEY_PASSWORD_DEVICE+" TEXT"+ ")";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* tao bang sql user
*
*/
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_LOGIN_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
onCreate(db);
}
public String getKeyUsernameDevice(int id) {
String infor = null;
SQLiteDatabase db=DatabaseHandler.this.getWritableDatabase();
Cursor cursor = db.rawQuery("select " + KEY_USERNAME_DEVICE + " from " + TABLE_LOGIN + " where " + KEY_ID
+ " =? ", new String[]{String.valueOf(1)});
if (cursor != null) {
// move cursor to first row
if (cursor.moveToFirst()) {
do {
// Get version from Cursor
infor = cursor.getString(cursor.getColumnIndex(KEY_USERNAME_DEVICE));
// add the bookName into the bookTitles ArrayList
// move to next row
} while (cursor.moveToNext());
}
}
return infor;
}
public String getKeyPasswordDevice(int id) {
String infor = null;
SQLiteDatabase db=DatabaseHandler.this.getWritableDatabase();
Cursor cursor = db.rawQuery("select " + KEY_PASSWORD_DEVICE + " from " + TABLE_LOGIN + " where " + KEY_ID
+ " =? ", new String[]{String.valueOf(1)});
if (cursor != null) {
// move cursor to first row
if (cursor.moveToFirst()) {
do {
// Get version from Cursor
infor = cursor.getString(cursor.getColumnIndex(KEY_PASSWORD_DEVICE));
// add the bookName into the bookTitles ArrayList
// move to next row
} while (cursor.moveToNext());
}
}
return infor;
}
class contain Asyntask
public class MyCommandTask extends AsyncTask<String,Void,Document>
{
String username;
String password;
DatabaseHandler databaseHandler;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Document doInBackground(String... params) {
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
try {
this.databaseHandler=new DatabaseHandler(getApplicationContext());
username=databaseHandler.getKeyUsernameDevice(1);
password="admin";
/* forming th java.net.URL object */
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
String basicAuth ="Basic " + Base64.encodeToString((username + ":" + password).getBytes(),Base64.NO_WRAP);
urlConnection.setRequestProperty("Authorization", basicAuth);
/* for Get request */
urlConnection.setRequestMethod("GET");
inputStream =urlConnection.getInputStream();
/* 200 represents HTTP OK */
Document responseXML = parseXmlDom(inputStream);
return responseXML;
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}

Well, first to improve performance don't search the same columnIndex in all iterations of the cursor.
You should do like :
if (cursor != null) {
Integer colIndex = cursor.getColumnIndex(KEY_USERNAME_DEVICE);
// move cursor to first row
if (cursor.moveToFirst()) {
do {
// Get version from Cursor
infor = cursor.getString( colIndex );
// add the bookName into the bookTitles ArrayList
// move to next row
} while (cursor.moveToNext());
}
}
Then can you show us your logCat to identify where the NullpointerException is?

I suspect the problem is with your cursor.getString(col_index), try this:
public String getKeyUsernameDevice(int id) {
String infor = null;
SQLiteDatabase db=DatabaseHandler.this.getWritableDatabase();
Cursor cursor = db.rawQuery("select " + KEY_USERNAME_DEVICE + " from " + TABLE_LOGIN + " where " + KEY_ID
+ " =? ", new String[]{String.valueOf(id)});
// move cursor to first row
if (cursor.moveToFirst()) {
// Get version from Cursor
infor = cursor.getString(0);
}
return infor;
}
Since your query is "select USERNAME ..." (but not select *) so the col_index for USERNAME for your query now should be the first column 0.

Related

Edittext Suggestion on android Studio

help me how to fix this code
from AutocompleteTextview i cant see the error code from this part
final String [] myData = myDB.SelectAllData();
final AutoCompleteTextView autoCom = (AutoCompleteTextView)findViewById(R.id.TVresult);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_singlechoice,myData);
autoCom.setAdapter(adapter);
and This Part
public String[] SelectAllData() {
try {
String ArrayData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
String strSQL = "SELECT * FROM " + DB_TABLE_NAME;
Cursor cursor = db.rawQuery(strSQL, null);
if(cursor != null)
{
if (cursor.moveToFirst()) {
ArrayData = new String[cursor.getCount()];
/***
* [x] = Name
*/
int i= 0;
do {
ArrayData[i] = cursor.getString(0);
i++;
} while (cursor.moveToNext());
}
}
cursor.close();
return ArrayData;
} catch (Exception e) {
return null;
}
}
This is my code of MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resulttext = (TextView) findViewById(R.id.TVresult);
rescebu = (TextView) findViewById(R.id.english);
trans = (Button) findViewById(R.id.translate);
respam = (TextView) findViewById(R.id.tagalog);
resilo = (TextView) findViewById(R.id.vis);
resbik = (TextView) findViewById(R.id.ilonngo);
myDB = new DatabaHelper(this);
tts = new TextToSpeech(this, this);
final String [] myData = myDB.SelectAllData();
final AutoCompleteTextView autoCom = (AutoCompleteTextView)findViewById(R.id.TVresult);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_singlechoice,myData);
autoCom.setAdapter(adapter);
autoCom.setThreshold(1);
autoCom.setTextColor(Color.RED);
This is The Dabasehelper and SelectAllData Method
public class DatabaHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "translator4.sqlite";
private static final String DB_TABLE_NAME = "wews";
public DatabaHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
public Cursor getAllData(String English, String Tagalog, String Visaya, String Ilonggo) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from wews where English like '" + English + "' or Tagalog like '" + Tagalog + "' or Visayan like '" + Visaya + "' or Ilonggo like '" + Ilonggo + "';", null);
return res;
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public String[] SelectAllData() {
try {
String ArrayData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
String strSQL = "SELECT * FROM " + DB_TABLE_NAME;
Cursor cursor = db.rawQuery(strSQL, null);
if(cursor != null)
{
if (cursor.moveToFirst()) {
ArrayData = new String[cursor.getCount()];
/***
* [x] = Name
*/
int i= 0;
do {
ArrayData[i] = cursor.getString(0);
i++;
} while (cursor.moveToNext());
}
}
cursor.close();
return ArrayData;
} catch (Exception e) {
return null;
}
}
This is The logs LogCat
Process: application.example.com.myapplication, PID: 20663
Theme: themes:{default=overlay:system, iconPack:system, fontPkg:system, com.android.systemui=overlay:system, com.android.systemui.navbar=overlay:system}
java.lang.RuntimeException: Unable to start activity ComponentInfo{application.example.com.myapplication/application.example.com.myapplication.MainActivity}: java.lang.NullPointerException: storage == null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2462)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5475)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:102)
Caused by: java.lang.NullPointerException: storage == null
at java.util.Arrays$ArrayList.<init>(Arrays.java:38)
at java.util.Arrays.asList(Arrays.java:155)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:137)
at application.example.com.myapplication.MainActivity.onCreate(MainActivity.java:56)
at android.app.Activity.performCreate(Activity.java:7125)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2415)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5475) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:102)
Possible Modification in this code block as you missed to created string object ArrayData[i] = new String() in do...while loop.
public String[] SelectAllData() {
try {
String ArrayData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
String strSQL = "SELECT * FROM " + DB_TABLE_NAME;
Cursor cursor = db.rawQuery(strSQL, null);
if(cursor != null)
{
if (cursor.moveToFirst()) {
ArrayData = new String[cursor.getCount()];
/***
* [x] = Name
*/
int i= 0;
do {
ArrayData[i] = new String();
ArrayData[i] = cursor.getString(0);
i++;
} while (cursor.moveToNext());
}
}
cursor.close();
return ArrayData;
} catch (Exception e) {
return null;
}
}
I'd suggest changing :-
public String[] SelectAllData() {
try {
String ArrayData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
String strSQL = "SELECT * FROM " + DB_TABLE_NAME;
Cursor cursor = db.rawQuery(strSQL, null);
if(cursor != null)
{
if (cursor.moveToFirst()) {
ArrayData = new String[cursor.getCount()];
/***
* [x] = Name
*/
int i= 0;
do {
ArrayData[i] = cursor.getString(0);
i++;
} while (cursor.moveToNext());
}
}
cursor.close();
return ArrayData;
} catch (Exception e) {
return null;
}
}
to :-
public String[] SelectAllData() {
try {
String ArrayData[];
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
String strSQL = "SELECT * FROM " + DB_TABLE_NAME;
Cursor cursor = db.rawQuery(strSQL, null);
ArrayData = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
ArrayData[i++] = cursor.getString(0);
//ArrayData[cursor.getPosition()] = cursor.getString(0); //Could be an alternative
}
cursor.close();
return ArrayData;
} catch (Exception e) {
return new String[0];
}
}
In short, the check for a null cursor is useless it DOES NOT signify no data, rather an empty cursor with a count of 0 is returned when there is no data.
Thus when there is no data cursor.moveToFirst will be false and none of the code within the if will be executed. As such ArrayData will be null (the likely reason for the null pointer exception).
The modified code will return an empty array (0 elements) if there is no data or if there is another exception captured in the try block.
You could also do away with using a counter/index, by using cursor.getPosition(), which is effectively the same (as per commented out line).

no such table SQLite error could not compile

i have three classes where the flow is..
entering the entry to be searched: (from MainActivity)
try {
String input = etSearch.getText().toString();
Intent i = new Intent(this, SearchViewList.class);
i.putExtra("input", input);
Log.i("input", input + "");
startActivity(i);
} catch (Exception e) {
// TODO: handle exception
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Row Empty or ID not found!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
break;
}
then the class SearchViewList would display the list by the searched value from the intent
Intent i = getIntent();
input = i.getStringExtra("input");
String l = input;
datasource = new DatabaseHelper(this);
datasource.openDataBase();
List<Definition> values = datasource.getSearchedDefinition(l);
// use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Definition> adapter = new ArrayAdapter<Definition>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
String str = ((TextView) view).getText().toString();
Log.i(str, str + "");
Intent i = new Intent(getApplicationContext(),
SearchedView.class);
i.putExtra("value", str);
startActivity(i);
}
});
then after clicking the searched entry from the list then the error commence
Intent i = getIntent();
l = i.getStringExtra("value");
TextView entry = (TextView) findViewById(R.id.tvEntry);
datasource = new DatabaseHelper(this);
datasource.openDataBase();
String dataEntry = datasource.getEntry(l);
datasource.close();
entry.setText(dataEntry);
}
here is my getEntry() method from the DatabaseHelper class
public String getEntry(String l) throws SQLException {
Cursor c = myDataBase.rawQuery(
"SELECT entry FROM defintionstbl where entry = '"
+ l + "'", null);
if (c != null) {
c.moveToFirst();
if (c.getCount() <= 0) {
return null;
}
String entry = c.getString(0);
return entry;
}
return null;
}
this next method is also from the DatabaseHelper class
public List<Definition> getSearchedDefinition(String l) throws SQLException {
List<Definition> entries = new ArrayList<Definition>();
Cursor cursor = myDataBase.rawQuery(
"SELECT entry FROM definitionstbl where entry like '" + l + "%'", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Definition entry = cursorToDefinition(cursor);
entries.add(entry);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return entries;
}
private Definition cursorToDefinition(Cursor cursor) {
Definition entry = new Definition();
entry.setId(cursor.getLong(0));
entry.setEntry(cursor.getString(0));
return entry;
}
this method compile just fine but the i am getting a "no such table definitionstbl" error from the method getEntry().
additional note:
database = dictionary.sqlite
table = definitionstbl
column1 = _id
column2 = entry
column3 = definitions
here is the code for the copying of the database from an external source:
public class DatabaseHelper extends SQLiteOpenHelper {
// The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.gtxradeon.newversioncomputerdictionary/databases/";
private static String DB_NAME = "dictionary.sqlite";
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 DatabaseHelper(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");
}
}
}
/**
* 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 + DB_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(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + 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;
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);
}
#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) {
}
create table from MainActivity
try {
myDbHelper.createDataBase();
myDbHelperTrivia.createDataBase();
Log.i("CREATING", "DATABASE CREATED");
} catch (Exception e) {
Log.i("CREATE", "Exception Caught! ", e);
}
try {
myDbHelper.openDataBase();
Log.i("OPENING", "DATABASE OPENED");
} catch (SQLException e) {
Log.i("OPEN", "Exception Caught! ", e);
}
thanks for helping guys but i just changed the getEntry method to this.. rawQuery gave alot of error but this new method is good to go..
public String getEntry(String l) throws SQLException {
String[] columns = new String[] { "_id",
"entry", "definition" };
Cursor c = myDataBase.query("definitionstbl", columns,
"entry" + "='" + l + "'", null, null, null, null);
if (c != null) {
c.moveToFirst();
if (c.getCount() <= 0) {
return null;
}
String entry = c.getString(1);
return entry;
}
return null;
}

My Database is not updated,if my JSON data will increase also

I am parsing JSON data to database,that data shows in my lisview.But in the first time it get data from my JSON and stores in db,its not upgrading if i add anything in my website,the json also will increase but its not reflect in db,the database part also not upgrading.Just its simply the display the first fetched data only.
Ginfydbadapter.java
public class GinfyDbAdapter {
private static final String DATABASE_NAME = "test";
private static final String DATABASE_TABLE_PROJ = "projects";
private static final int DATABASE_VERSION = 3;
public static final String CATEGORY_COLUMN_ID = "_id";
public static final String CATEGORY_COLUMN_TITLE = "title";
public static final String CATEGORY_COLUMN_CONTENT = "content";
public static final String CATEGORY_COLUMN_COUNT = "count";
private static final String TAG = "GinfyDbAdapter";
private DatabaseHelper mDbHelper;
private static SQLiteDatabase mDb;
private final Context mCtx;
public void saveCategoryRecord(String id, String title, String content, String count) {
ContentValues contentValues = new ContentValues();
contentValues.put(CATEGORY_COLUMN_ID, id);
contentValues.put(CATEGORY_COLUMN_TITLE, title);
contentValues.put(CATEGORY_COLUMN_CONTENT, content);
contentValues.put(CATEGORY_COLUMN_COUNT, count);
mDb.insert(DATABASE_NAME, null, contentValues);
}
public Cursor getTimeRecordList() {
return mDb.rawQuery("select * from " + DATABASE_NAME, null);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
private static final String DATABASE_CREATE_PROJ =
"create table " + DATABASE_TABLE_PROJ + " ("
+ CATEGORY_COLUMN_ID + " integer primary key , "
+ CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer );" ;
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String DATABASE_CREATE_PROJ = "CREATE TABLE " + DATABASE_TABLE_PROJ + "( "
+ CATEGORY_COLUMN_ID + " integer primary key, "
+ CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer );" ;
db.execSQL(DATABASE_CREATE_PROJ);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS"+ DATABASE_TABLE_PROJ);
onCreate(db);
}
}
public void saveCategoryRecord(Category category) {
ContentValues values = new ContentValues();
values.put(CATEGORY_COLUMN_TITLE , category.getTitle());
values.put(CATEGORY_COLUMN_CONTENT, category.getContent());
values.put(CATEGORY_COLUMN_COUNT, category.getCount());
// Inserting Row
mDb.insert(DATABASE_TABLE_PROJ, null, values);
mDb.close(); // Closing database connection
}
public Cursor fetchAllProjects() {
// TODO Auto-generated method stub
return mDb.query(DATABASE_TABLE_PROJ, new String[] {CATEGORY_COLUMN_ID, CATEGORY_COLUMN_TITLE, CATEGORY_COLUMN_CONTENT, CATEGORY_COLUMN_COUNT }, null, null, null, null, null);
}
public GinfyDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public GinfyDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
}
this is my MainActivity.java
here only i mention my url of json also
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
Cursor projectsCursor = mDbHelper.fetchAllProjects();
if(projectsCursor!=null)
{
fillData(projectsCursor);
Log.i("filling", "...");
}
else
{
new GetDataAsyncTask().execute();
}
//lv1 =(ListView)findViewById(R.id.list);
//lv =(ListView)findViewById(R.id.list);
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
myFilter = (EditText) findViewById(R.id.myFilter);
//praycount.setOnClickListener(this);
//initView();
}
/*private void initView(){
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://www.ginfy.com/api/v1/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
} */
private class GetDataAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
Dialog.setMessage("Loading.....");
Dialog.show();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Dialog.dismiss();
Cursor projectsCursor = mDbHelper.fetchAllProjects();
if(projectsCursor!=null)
{
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
fillData(projectsCursor);
}
}
#Override
protected Void doInBackground(Void... params) {
getData();
return null;
}
}
public void getData() {
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("https://ancient-caverns-4909.herokuapp.com/api/v1/posts.json");
// HttpGet request = new HttpGet("http://gdata.youtube.com/feeds/api/users/mbbangalore/uploads?v=2&alt=jsonc");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity); // content will be consume only once
Log.i("................",_response);
httpclient.getConnectionManager().shutdown();
JSONObject jsonObject = new JSONObject(_response);
JSONArray contacts = jsonObject.getJSONArray("post");//(url);
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String title = c.getString("title");
String content = c.getString("content");
String count = c.getString("count");
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
mDbHelper.saveCategoryRecord(new Category(id,title,content,count));
}
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void fillData(Cursor projectsCursor) {
//mDbHelper.open();
if(projectsCursor!=null)
{
String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE, GinfyDbAdapter.CATEGORY_COLUMN_CONTENT, GinfyDbAdapter.CATEGORY_COLUMN_COUNT};
int[] to = new int[]{R.id.text2, R.id.text1, R.id.count};
dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_row,
projectsCursor,
from,
to,
0);
setListAdapter(dataAdapter);
}else
{
Log.i("...........","null");
}
}
My Database is not upgrading due to JSON change,it will take only one time of json data only.

Keep getting "SQLiteException: no such table" exception

I trying to create SQLiteDatabase for keeping my data which I get from JSONObject from post request.
My main class:
public class MainActivity extends Activity {
static JSONObject result;
public Context mContext;
public SQLiteDatabase db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = getApplicationContext();
new UpdateData().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class UpdateData extends AsyncTask<String, Void, JSONObject>{
private JSONObject object;
#Override
protected JSONObject doInBackground(String... params) {
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://test.com";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> crc = new ArrayList<NameValuePair>();
crc.add(new BasicNameValuePair("crc", "test"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(crc,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity entit = responsePOST.getEntity();
String retSrc = EntityUtils.toString(entit);
object = new JSONObject(retSrc);
} catch (Exception e) {
e.printStackTrace();
}
return object;
}
#Override
protected void onPostExecute(JSONObject result) {
MainActivity.this.result = result;
DataBase dbHelper = new DataBase(mContext) ;
db = dbHelper.getWritableDatabase();
dbHelper.createDB(db, result);
/*Cursor cursor = db.query("departments", null , null,
null, null, null, null, null);
System.out.println(cursor.getString(1));*/
}
}
}
and DataBaseHelper
public class DataBaseHelper extends SQLiteOpenHelper {
public boolean isDownloaded = false;
public boolean shutdown = false;
private Context mContext;
private JSONObject exams;
private JSONObject specs;
private JSONObject deps;
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "data.db";
private static final String EXAMS_TABLE_NAME = "exams";
private static final String EXAMS_TABLE_CREATE =
"CREATE TABLE " + EXAMS_TABLE_NAME + " (" +
"id VARCHAR (255), " + //0
"name VARCHAR (255)," + //1
"type VARCHAR (100)," + //2
"level VARCHAR (100)," + ");" ; //3
private static final String SPEC_TABLE_NAME = "specializations";
private static final String SPEC_TABLE_CREATE =
"CREATE TABLE " + SPEC_TABLE_NAME + " (" +
"id VARCHAR (255), " + //0
"name VARCHAR (255)," + //1
"name_en VARCHAR (255)," + //2
"description VARCHAR (255)," + ");" ; //3
private static final String DEP_TABLE_NAME = "departments";
private static final String DEP_TABLE_CREATE =
"CREATE TABLE " + DEP_TABLE_NAME + " (" +
"id VARCHAR (255), " + //0
"name VARCHAR (255)," + //1
"name_en VARCHAR (255)," + //2
"www VARCHAR (255)," + //3
"email VARCHAR (255)," + //4
"phone VARCHAR (100)," + ");" ; //5
public DataBase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public boolean doesDBexist() {
File db;
db = new File("/data/data/my.package/databases/data.db");
return db.exists();
}
public boolean createDB(SQLiteDatabase db, JSONObject jsonObject) {
try { // if not working create new one
exams = jsonObject.getJSONObject("exams");
specs = jsonObject.getJSONObject("spec");
deps = jsonObject.getJSONObject("department");
db.execSQL(EXAMS_TABLE_CREATE); // here I get exception (described below)
db.execSQL(SPEC_TABLE_CREATE);
db.execSQL(DEP_TABLE_CREATE);
putContentValues(db);
isDownloaded = true;
return true;
} catch (SQLiteException e1) {
db = null;
return false;
} catch (Exception e3) {
shutdown = true;
return false;
}
}
public void putContentValues(SQLiteDatabase db) throws JSONException {
ContentValues cv = new ContentValues();
for (Iterator<String> it = exams.keys(); it.hasNext(); it.next()) {
JSONObject exam = exams.getJSONObject(it.toString());
cv.put("id", it.toString());
cv.put("name", exam.getString("name"));
cv.put("type", exam.getString("type"));
cv.put("level", exam.getString("level"));
db.insert(EXAMS_TABLE_NAME, null, cv);
cv.clear();
}
for (Iterator<String> it = specs.keys(); it.hasNext(); it.next()) {
JSONObject spec = specs.getJSONObject(it.toString());
cv.put("id", it.toString());
cv.put("name", spec.getString("name"));
cv.put("name_en", spec.getString("name_en"));
cv.put("desription", spec.getString("desription"));
db.insert(SPEC_TABLE_NAME, null, cv);
cv.clear();
}
for (Iterator<String> it = deps.keys(); it.hasNext(); it.next()) {
JSONObject dep = deps.getJSONObject(it.toString());
cv.put("id", it.toString());
cv.put("name", dep.getString("name"));
cv.put("name_en", dep.getString("name_en"));
cv.put("www", dep.getString("www"));
cv.put("email", dep.getString("email"));
cv.put("phone", dep.getString("phone"));
db.insert(DEP_TABLE_NAME, null, cv);
cv.clear();
}
}
}
I can't debug it. When I create Cursor in MainActivity, I get exception after line db.execSQL(EXAMS_TABLE_CREATE); android.database.sqlite.SQLiteException: no such table: departments: , while compiling: SELECT * FROM departments and when I don't create cursor it's just stops there while debugging. I can't check if there is anything in my database and if it's corectly made.
I tried to rename my database like someone said in this question :
android.database.sqlite.SQLiteException: no such table but it didn't solve this.
that cannot be correct:
"CREATE TABLE " + EXAMS_TABLE_NAME + " (" +
"id VARCHAR (255), " + //0
"name VARCHAR (255)," + //1
"type VARCHAR (100)," + //2
"level VARCHAR (100)," + ");" ;
remove the last "," in that create-statement and try it again.
btw... you did that fault in all create statements.

Android login to mysql

i am working in an application, i seen that guide: http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/ and i make it working on mine app...
Now the login part is this:
public class LoginActivity extends Activity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
TextView testo;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
testo = (TextView) findViewById(R.id.testo);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
Log.d("Button", "Login");
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
}
the json parser is:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
and the database handler:
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "android_api";
// Login table name
private static final String TABLE_LOGIN = "login";
// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE,"
+ KEY_UID + " TEXT,"
+ KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_LOGIN_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String name, String email, String uid, String created_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Name
values.put(KEY_EMAIL, email); // Email
values.put(KEY_UID, uid); // Email
values.put(KEY_CREATED_AT, created_at); // Created At
// Inserting Row
db.insert(TABLE_LOGIN, null, values);
db.close(); // Closing database connection
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails(){
HashMap<String,String> user = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("uid", cursor.getString(3));
user.put("created_at", cursor.getString(4));
}
cursor.close();
db.close();
// return user
return user;
}
/**
* Getting user login status
* return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
/**
* Re crate database
* Delete all tables and create them again
* */
public void resetTables(){
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_LOGIN, null, null);
db.close();
}
}
now i want to put in a textview the username of the user logged in, but i have no idea on how to do it... i have to use the parser? i have to read the sqlite database? can someone help me? thanks, i'm newbie in that thing...
you can do this by passing the user name to the DashboardActivity. You have to add the following line just before the line startActivity(dashboard); in your LoginActivity class.
dashboard.putExtra("username", json_user.getString(KEY_NAME));
This line passes the username to your DashboardActivity.
Then, in the method onCreate of your DashboardActivity we will get the user name and put it on a variable called username (a String) with the code:
Intent intent = getIntent();
String username = "";
if(intent != null) {
username = intent.getStringExtra(name);
}

Categories