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.
Related
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Hi i'm completely new to Android. Very used to .Net and SQL Server. Hence, having issue adopting to SQLite. I'm currently able to display the result in a listView from a URL via HttpGet. Kindly be gentle with me. Helps are greatly appreciated, as I'm stuck in SQLite for the past week.
Just want check if it's possible to set it such that
HttpGet will retrieve and insert into SQLite table.
listView retrieve All columns data from SQLite table.
The HttpGet AsyncTask will run only if 48hrs has pass. So for example if the the download happens on Monday, the database should not be updated if the person use the app on Tuesday. However, the data will be updated on Wed when the user on it.
It will delete all column in the table before inserting into SQlite table.
EncounterActivity.Java
public class EncounterActivity extends Activity {
ListView list;
TextView eid;
TextView eclerkship;
TextView ename;
TextView etype;
TextView erequiredattempts;
EncounterDbAdapter encounterDB;
Context myContext;
Button Btngetdata;
ArrayList<HashMap<String, String>> encouterlist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "SorryHadToRemoveThisDueToSomeReason";
//JSON Node Names
private static final String TAG_ENCOUNTERS = "encounters";
private static final String TAG_E_ID = "e_id";
private static final String TAG_E_CLERKSHIP = "clerkship";
private static final String TAG_E_NAME = "encounter_name";
private static final String TAG_E_TYPE = "type";
private static final String TAG_E_REQUIRED_ATTEMPTS = "required_attempts";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_encounter);
encouterlist = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
eid = (TextView)findViewById(R.id.eid);
eclerkship = (TextView)findViewById(R.id.eclerkship);
ename = (TextView)findViewById(R.id.ename);
etype = (TextView)findViewById(R.id.etype);
erequiredattempts = (TextView)findViewById(R.id.erequiredattempts);
pDialog = new ProgressDialog(EncounterActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_ENCOUNTERS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String eid = c.getString(TAG_E_ID);
String eclerkship = c.getString(TAG_E_CLERKSHIP);
String ename = c.getString(TAG_E_NAME);
String etype = c.getString(TAG_E_TYPE);
String erequiredattempts = c.getString(TAG_E_REQUIRED_ATTEMPTS);
// Opening of database
encounterDB = new EncounterDbAdapter(myContext);
encounterDB.open();
encounterDB.insertEncounterEntry(eid, eclerkship, ename, etype, erequiredattempts);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_E_ID, eid);
map.put(TAG_E_CLERKSHIP, eclerkship);
map.put(TAG_E_NAME, ename);
map.put(TAG_E_TYPE, etype);
map.put(TAG_E_REQUIRED_ATTEMPTS, erequiredattempts);
encouterlist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(EncounterActivity.this, encouterlist,
R.layout.list_v,
new String[] { TAG_E_ID, TAG_E_CLERKSHIP, TAG_E_NAME, TAG_E_TYPE, TAG_E_REQUIRED_ATTEMPTS }, new int[] {
R.id.eid, R.id.eclerkship, R.id.ename, R.id.etype, R.id.erequiredattempts});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(EncounterActivity.this, "You Clicked at "+encouterlist.get(+position).get("type"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JsonParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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();
} 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;
}
}
EncounterDbAdapter.java
public class EncounterDbAdapter {
private static final String DATABASE_NAME = "mediLearner.db";
private static final String DATABASE_TABLE = "EncounterDb";
private static final int DATABASE_VERSION = 2;
private SQLiteDatabase _db;
private final Context context;
public static final String E_ID = "_id";
public static final int COLUMN_KEY_ID = 0;
public static final String CLERKSHIP = "entry_clerkship";
public static final int COLUMN_CLERKSHIP_ID = 1;
public static final String ENCOUNTER_NAME = "entry_encounter";
public static final int COLUMN_ENCOUNTER_NAME = 2;
public static final String TYPE = "entry_type";
public static final int COLUMN_TYPE = 3;
public static final String REQUIRED_ATTEMPTS = "entry_requiredAttempts";
public static final int COLUMN_REQUIRED_ATTEMPTS = 4;
protected static final String DATABASE_CREATE = "create table "
+ DATABASE_TABLE + " (" + E_ID
+ " PRIMARY KEY, " + CLERKSHIP + " Text, "
+ ENCOUNTER_NAME + " text, " + TYPE + " Text, "
+ REQUIRED_ATTEMPTS + " Text);";
private String encounterDBADAPTER_LOG_CAT = "MY_LOG";
private myDBOpenHelper dbHelper;
public EncounterDbAdapter(Context _context) {
this.context = _context;
dbHelper = new myDBOpenHelper(context, DATABASE_NAME, null,
DATABASE_VERSION);
}
public void close() {
_db.close();
Log.w(encounterDBADAPTER_LOG_CAT, "DB closed");
}
public void open() throws SQLiteException {
try{
_db=dbHelper.getWritableDatabase();
Log.w(encounterDBADAPTER_LOG_CAT, "DB opened as writable database");
}catch(SQLiteException ex){
_db=dbHelper.getReadableDatabase();
Log.w(encounterDBADAPTER_LOG_CAT, "DB opened as readable database");
}
}
//insertion
public long insertEncounterEntry(String ID , String clerkship, String encounter, String type, String requiredAttempts ) {
//insert new task
ContentValues newEntryValues=new ContentValues();
newEntryValues.put(E_ID, ID);
newEntryValues.put(CLERKSHIP,clerkship);
newEntryValues.put(ENCOUNTER_NAME,encounter);
newEntryValues.put(TYPE, type);
newEntryValues.put(REQUIRED_ATTEMPTS, requiredAttempts);
//Insert the row
Log.w(encounterDBADAPTER_LOG_CAT, "Inserted E_ID="+ID+" CLERKSHIP="+clerkship + "Inserted ENCOUNTER_NAME="+encounter + "Inserted TYPE="+type + "Inserted REQUIRED_ATTEMPTS="+requiredAttempts +"into table"+DATABASE_TABLE);
return _db.insert(DATABASE_TABLE, null, newEntryValues);
}
public boolean removeEntry(long _rowIndex) {
if(_db.delete(DATABASE_TABLE, E_ID+"="+_rowIndex, null)<=0)
{
Log.w(encounterDBADAPTER_LOG_CAT,"Removing Entrying where id="+_rowIndex+"Failed");
return false;
}
Log.w(encounterDBADAPTER_LOG_CAT,"Removing Entrying where id="+_rowIndex+"Success");
return true;
}
//updating
public boolean updateEntry(int ID , String clerkship, String encounter_name, String type, String requiredAttempts ) {
return false;
}
//retrival
public Cursor retrieveAllEntriesCursor() {
Cursor c=null;
try{
c=_db.query(DATABASE_TABLE,new String[]{E_ID, CLERKSHIP, ENCOUNTER_NAME, TYPE, REQUIRED_ATTEMPTS}, null,null,null,null,null);
}catch(SQLException sle){
Log.w(encounterDBADAPTER_LOG_CAT,"Retrieve fail!!");
}
return c;
}
public class myDBOpenHelper extends SQLiteOpenHelper {
public myDBOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
Log.w(encounterDBADAPTER_LOG_CAT, "Helper : DB " + DATABASE_TABLE
+ " Created!!");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
} // End of myDBOpenHelper
}// End of myDBAdapter
I would not use a Timer for the updates, but instead use a Service that starts on an interval set up by the AlarmManager. Like this:
public void setScheduling() {
Date now = new Date();
// Set the time to download to 18:00
Calendar cal = Calendar.getInstance();
cal.setTime(now);
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 0);
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, StartDownloadReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
mgr.cancel(pi);
// 1 * 24 * 60 * 60 * 1000 = repeat this every day
mgr.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(), 1 * 24 * 60 * 60 * 1000, pi);
}
Handle the pending intent in a BroadcastReceiver:
public class StartDownloadReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
boolean autoDownload = sharedPreferences.getBoolean("auto_download", false);
if (autoDownload) {
context.startService(new Intent(context, DownloaderService.class));
}
}
}
In your download service you would then use an AsyncTask to do the downloading, parsing and updating of the database.
I recently finished an app with somewhat the exact same requirements;
every day at 18:00 download an RSS feed
If the download and parsing was successful wipe the database tables and update the data
Send a broadcast to let any Activity that might be open to refresh its ListView
That's basically it, though the implementation is not exactly like that.
Have a look at it here: https://github.com/slidese/SGU
Also: I'm using OrmLite when working with SQLite. I find it to be far easier and quicker to work with than dealing with the SQL directly.
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.
I want to store an json data to db,it has to display my apps has to display some previous data without internet time also.For that i want to create an db for json data to store.
This is the db part i created for json data.
public class GinfyDbAdapter {
private static final String DATABASE_NAME = "ginfy.db";
private static final String DATABASE_TABLE_PROJ = "prayers";
private static final int DATABASE_VERSION = 2;
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 = "ProjectDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
public GinfyDbAdapter(MainActivity mainActivity) {
// TODO Auto-generated constructor stub
}
public GinfyDbAdapter GinfyDbAdapter(Context context){
mDbHelper = new DatabaseHelper(context);
mDb = mDbHelper.getWritableDatabase();
return this;
}
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 autoincrement, "
+ CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer primary key autoincrement );" ;
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE_PROJ + "( "
+ CATEGORY_COLUMN_ID + " INTEGER PRIMARY KEY, "
+ CATEGORY_COLUMN_TITLE + " TEXT, " + CATEGORY_COLUMN_CONTENT + " TEXT, " + CATEGORY_COLUMN_COUNT + " INTEGER PRIMARY KEY )" );
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS"+ DATABASE_NAME);
onCreate(db);
}
}
}
this is mainactivity which is showing listview
public class MainActivity extends Activity implements FetchDataListener,OnClickListener{
private static final int ACTIVITY_CREATE=0;
private static final String TAG_CATEGORY = "post";
private static final String CATEGORY_COLUMN_ID = "id";
private static final String CATEGORY_COLUMN_TITLE = "title";
private static final String CATEGORY_COLUMN_CONTENT = "content";
private static final String CATEGORY_COLUMN_COUNT = "count";
private static final int Application = 0;
private ProgressDialog dialog;
ListView lv;
ListView lv1;
private List<Application> items;
private Button btnGetSelected;
private Button praycount;
public int pct;
private String stringVal;
private TextView value;
private int prayers;
private int prayerid;
EditText myFilter;
ApplicationAdapter adapter;
private GinfyDbAdapter mDbHelper;
JSONArray contacts = null;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
mDbHelper=new GinfyDbAdapter(MainActivity.this);
lv1 =(ListView)findViewById(R.id.list);
lv =(ListView)findViewById(R.id.list);
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
//JSONParser jParser = new JSONParser();
JSONObject jsonObject = new JSONObject();
//JSONArray aJson = jsonObject.getJSONArray("post");
String url = "http://www.ginfy.com/api/v1/posts.json";
// getting JSON string from URL
JSONArray aJson = jsonObject.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = aJson.getJSONObject(TAG_CATEGORY);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(CATEGORY_COLUMN_ID);
String title = c.getString(CATEGORY_COLUMN_TITLE);
String content = c.getString(CATEGORY_COLUMN_CONTENT);
String count = c.getString(CATEGORY_COLUMN_COUNT);
mDbHelper.saveCategoryRecord(id,title,content,count);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(CATEGORY_COLUMN_ID, id);
map.put(CATEGORY_COLUMN_TITLE, title);
map.put(CATEGORY_COLUMN_CONTENT, content);
map.put(CATEGORY_COLUMN_COUNT, count);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
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);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
createProject();
return super.onMenuItemSelected(featureId, item);
}
private void createProject() {
Intent i = new Intent(this, AddPrayerActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
initView();
}
#Override
public void onFetchComplete(List<Application> data){
this.items = data;
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
/*dataAdapter adapter = new SimpleCursorAdapter(this,
R.layout.activity_row,
new String[] { CATEGORY_COLUMN_TITLE, CATEGORY_COLUMN_CONTENT, CATEGORY_COLUMN_COUNT }, new int[] {
R.id.text2, R.id.text1, R.id.count });*/
//lv.setListAdapter(adapter);
// set the adapter to list
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckBox chk = (CheckBox) view.findViewById(R.id.checkbox);
Application bean = items.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
}
// Toast is here...
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onFetchFailure(String msg){
if ( dialog != null )
dialog.dismiss();
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
Before using db it shows in listview also,rite now i want to make db also,for that i wrote some code in mainactivity.
Fetchdatatask.java
public class FetchDataTask extends AsyncTask<String, Void, String>
{
private final FetchDataListener listener;
private OnClickListener onClickListener;
private String msg;
public FetchDataTask(FetchDataListener listener)
{
this.listener = listener;
}
#Override
protected String doInBackground(String... params)
{
if ( params == null )
return null;
// get url from params
String url = params[0];
try
{
// create http connection
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
// connect
HttpResponse response = client.execute(httpget);
// get response
HttpEntity entity = response.getEntity();
if ( entity == null )
{
msg = "No response from server";
return null;
}
// get response content and convert it to json string
InputStream is = entity.getContent();
return streamToString(is);
}
catch ( IOException e )
{
msg = "No Network Connection";
}
return null;
}
#Override
protected void onPostExecute(String sJson)
{
if ( sJson == null )
{
if ( listener != null )
listener.onFetchFailure(msg);
return;
}
try
{
// convert json string to json object
JSONObject jsonObject = new JSONObject(sJson);
JSONArray aJson = jsonObject.getJSONArray("post");
// create apps list
List<Application> apps = new ArrayList<Application>();
for ( int i = 0; i < aJson.length(); i++ )
{
JSONObject json = aJson.getJSONObject(i);
Application app = new Application();
app.setContent(json.getString("content"));
app.setTitle(json.getString("title"));
app.setCount(Integer.parseInt(json.getString("count")));
app.setId(Integer.parseInt(json.getString("id")));
// add the app to apps list
apps.add(app);
}
//notify the activity that fetch data has been complete
if ( listener != null )
listener.onFetchComplete(apps);
}
catch ( JSONException e )
{
e.printStackTrace();
msg = "Invalid response";
if ( listener != null )
listener.onFetchFailure(msg);
return;
}
}
/**
* This function will convert response stream into json string
*
* #param is
* respons string
* #return json string
* #throws IOException
*/
public String streamToString(final InputStream is) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ( (line = reader.readLine()) != null )
{
sb.append(line + "\n");
}
}
catch ( IOException e )
{
throw e;
}
finally
{
try
{
is.close();
}
catch ( IOException e )
{
throw e;
}
}
return sb.toString();
}
}
This fetchdatatask fetch from json and showing in listview,i want that without internet time it has to show in listview also for that i am creating db.
can you check my code is correct,actually it showing error in mainactivity line JSONArray aJson = jsonObject.getJSONFromUrl(url);
Create a class which act's as the intermediate between your Db class and the main activity to insert the data into the db and vice versa
public class Category {
String id;
String title;
String content;
String count;
public Category(String id, String title, String content, String count) {
super();
this.id = id;
this.title = title;
this.content = content;
this.count = count;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
}
In your main activity where you do the json parsing create an object of DB class and call one the save record method at there like i did below
DatabaseHelper mDbHelper;
public class ABC extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.abc);
mDbHelper= new DatabaseHelper (this);
new GetSyncDataAsyncTask().execute();
}
}
private class GetDataAsyncTask extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog Dialog = new ProgressDialog(ABC.this);
protected void onPreExecute() {
Dialog.setMessage("Loading.....");
Dialog.show();
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Dialog.dismiss();
Intent intent = new Intent(ABC.this, XYZ.class);
startActivity(intent);
}
#Override
protected Boolean doInBackground(Void... params) {
getData();
return null;
}
}
public void getProdData() {
// getting JSON string from URL
JSONParser parser = new JSONParser();
JSONObject jsonObject = new JSONObject();
//JSONArray aJson = jsonObject.getJSONArray("post");
String url = "http://www.ginfy.com/api/v1/posts.json";
// getting JSON string from URL
JSONArray aJson = jsonObject.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = aJson.getJSONObject(TAG_CATEGORY);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(CATEGORY_COLUMN_ID);
String title = c.getString(CATEGORY_COLUMN_TITLE);
String content = c.getString(CATEGORY_COLUMN_CONTENT);
String count = c.getString(CATEGORY_COLUMN_COUNT);
mDbHelper.saveCategoryRecord(new Category(id,title,content,count));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
At last in your db class insert the values like below
public void saveCategoryRecord(Category category) {
String query = "insert into"+ TABLE_NAME+ values( ?, ?, ?, ?, ?, ? )";
SQLiteStatement stmt = mDb.compileStatement(query);
stmt.bindString(1, category.getId());
stmt.bindString(2, category.getTitle());
stmt.bindString(3, category.getContent());
stmt.bindString(4, category.getCount());
stmt.execute();
}
I have tried to use the same things as you have used. This is the way i think now you got the concept to do that
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);
}