I am sending my Server side JSON data into database,after that i am display in an listview. But while changing in an server side or my json data will increase, it will not reflect or change in my db,Actually after changing my JSON, i want my db also update like Old+new. It has to save the new one also in db while any data add in server side also.
This my JSON part:
{
"post": [
{
"id": 249,
"title": "Career",
"content": "Last ten days ,work is not going well",
"count": 0
},
{
"id": 248,
"title": "Career",
"content": "Last ten days ,work is not going well",
"count": 0
},
]
}
This JSON value has to store in db,if next time in website some thing will add,my json will also increase,My db also wants to add that data,Rightnow is not adding that data,only one time its fetching and displaying.
This is my Mainactivity.java
#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.getCount()>0)
{
fillData(projectsCursor);
Log.i("filling", "...");
}
else
{
new GetDataAsyncTask().execute();
}
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
}
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();
mDbHelper=new GinfyDbAdapter(MainActivity.this); // initialize mDbHelper before.
mDbHelper.open();
Cursor projectsCursor = mDbHelper.fetchAllProjects();
if(projectsCursor.getCount()>0)
{
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("http://192.168.1.18:3001/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");
}
}
Here i mention my dpclass also.
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;
}
public boolean updateProject(long _id, String title, String content, String count) {
ContentValues args = new ContentValues();
args.put(CATEGORY_COLUMN_TITLE, title );
args.put(CATEGORY_COLUMN_CONTENT, content );
args.put(CATEGORY_COLUMN_COUNT, count );
return mDb.update(DATABASE_TABLE_PROJ, args, CATEGORY_COLUMN_ID + "=" + _id, null) > 0;
}
}
My problem is:For first time it fetches my JSON data and save in db,next time while launching its not getting newly added part of json data,I want that old and new JSON data should be store in db.
please use insert or replase raw query instead this look this.
SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"
String query = INSERT OR REPLACE INTO DATABASE_TABLE_PROJ
(CATEGORY_COLUMN_ID,CATEGORY_COLUMN_TITLE,CATEGORY_COLUMN_CONTENT,CATEGORY_COLUMN_COUNT)
VALUES
('1', 'Muhammad','xyz','2');
db.execSQL(query);
public class Mainactivity extends Activity{
ArrayList<String> ID = new ArrayList<String>();
ArrayList<String> TITLE= new ArrayList<String>();
ArrayList<String> CONTENT= new ArrayList<String>();
ArrayList<String> COUNT= new ArrayList<String>();
protected onCreate(Bundle savedInastanceState){
}
public void getData() {
//your json code
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");
ID.add(id);
TITLE.add(title);
CONTENT.add(content);
COUNT.add(count);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private class GetDataAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
//
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Dialog.dismiss();
//
}
#Override
protected Void doInBackground(Void... params) {
getData();
return null;
}
#Override
protected void onPostExecute(Void result) {
for(int i=0; i<ID.size(); i++){
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
mDbHelper.saveCategoryRecord(new Category(ID.get(i),TITLE.get(i),CONTENT.get(i),COUNTER.get(i)));
}
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
am trying to delete all records from the database and insert records which i get from remote db , every time the activity loads.
I am able to insert the data. but when i try to delete the all the records from the table i get the error.
my code
Main Menu class
public class mainmenu extends Activity {
private ScheduleDAO mscheduleDAo;
private VisitsDAO mvisitsDAO;
private String storedkey;
private String jsonfromapi;
//schedule table variables
private String schedule_id = null;
private String schedule_name = null;
private String schedule_date= null;
//visits table variables
private String visit_id = null;
private String visit_schedule_id = null;
private String visit_name = null;
private String visit_time = null;
private String visit_place = null;
private String visit_address = null;
private String visit_location_lat = null;
private String visit_location_lng = null;
private String visit_status = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainmenu);
//Delete all records from visits and schedule tables
// mscheduleDAo.deleteAllSchedule();
mvisitsDAO.deleteAllVisits();
//loading schedule list
Button btn_sche = (Button) findViewById(R.id.btn_schedule);
btn_sche.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(mainmenu.this, Schedule_Activity.class));
}
});
//loading reset password
Button reset = (Button) findViewById(R.id.btn_reset_password);
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(mainmenu.this, resetpassword.class));
}
});
//loading google maps
Button location = (Button) findViewById(R.id.btn_location);
location.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(mainmenu.this, My_Location.class));
}
});
try {
String user_name = getdate_from_local();
TextView user = (TextView) findViewById(R.id.lbl_name);
user.setText("Welcome : "+user_name+"\n");
} catch (IOException e) {
e.printStackTrace();
}
// getting the list of schedules from the remote api
get_schedule_list();
try{
JSONObject jsonObject = new JSONObject(jsonfromapi); //Here reponse is the yours server response
JSONObject result = jsonObject.getJSONObject("result");
JSONArray sehedule = result.getJSONArray("sehedule");
//save all schedules
for(int i=0;i<sehedule.length();i++)
{
schedule_id = sehedule.getJSONObject(i).getString("schedule_id");
schedule_date = sehedule.getJSONObject(i).getString("schedule_date");
String[] parts = schedule_date.split(" ");
String string1 = parts[0];
schedule_date = string1;
schedule_name = sehedule.getJSONObject(i).getString("schedule_name");
insert_schedule();
// Toast.makeText(this, schedule_date,Toast.LENGTH_LONG).show();
}
//save all visits
JSONArray visits = result.getJSONArray("visit");
for(int i=0;i<visits.length();i++)
{
visit_id = visits.getJSONObject(i).getString("visit_id");
visit_schedule_id = visits.getJSONObject(i).getString("schedule_id");
visit_name = visits.getJSONObject(i).getString("visit_name");
visit_time = visits.getJSONObject(i).getString("visit_time");
visit_place = visits.getJSONObject(i).getString("visit_place");
visit_address = visits.getJSONObject(i).getString("visit_address");
visit_location_lat = visits.getJSONObject(i).getString("visit_location_lat");
visit_location_lng = visits.getJSONObject(i).getString("visit_location_lng");
visit_status = visits.getJSONObject(i).getString("visit_status");
insert_visits();
}
//Save all items
JSONArray items = result.getJSONArray("item");
for(int i=0;i<items.length();i++)
{
String item_id = items.getJSONObject(i).getString("item_id");
String visit_id = items.getJSONObject(i).getString("visit_id");
String item_name = visits.getJSONObject(i).getString("item_name");
String item_check_status ="1";
String item_comment = "";
String item_latitude = "";
String item_longitude = "";
String item_submit_time = "";
String item_remote_status = "1";
}
}catch(Exception e)
{ }
}
private boolean insert_schedule(){
mscheduleDAo =new ScheduleDAO(getApplicationContext());
Schedule createdschedule = mscheduleDAo.createschedule(Integer.parseInt(String.valueOf(schedule_id)),
schedule_name,
schedule_date);
return true;
}
private boolean insert_visits(){
mvisitsDAO = new VisitsDAO(getApplicationContext());
Visits createvisits =mvisitsDAO.createvisits(Integer.parseInt(String.valueOf(visit_id)),
Integer.parseInt(String.valueOf(visit_schedule_id)),
visit_name, visit_time, visit_place, visit_address, visit_location_lat, visit_location_lng,
Integer.parseInt(String.valueOf(visit_status)));
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private String readkeyfromfille() throws IOException {
FileInputStream fis = openFileInput("myappkey.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
StringBuffer b = new StringBuffer();
while(bis.available() !=0){
char c = (char) bis.read();
b.append(c);
}
String Key =b.toString();
return Key;
}
public String getdate_from_local() throws IOException {
String storedkey = readkeyfromfille();
byte[] data = Base64.decode(storedkey, Base64.DEFAULT);
String key_in_text = new String(data, "UTF-8");
String[] parts = key_in_text.split(Pattern.quote("|"));
String string1 = parts[0]; // 004
String string2 = parts[1];
return string1;
}
private void get_schedule_list(){
try {
jsonfromapi = new MySchedules().execute(storedkey).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
//async task to get the schedule, visits, items details from remote database
class MySchedules extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg0) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://172.16.110.3/agent_tracking/index.php/api/rest/get-schedules/");
try {
// Add your data
List<BasicNameValuePair> nameValuePairs = new ArrayList<>(1);
nameValuePairs.add(new BasicNameValuePair("key", arg0[0]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String schedule_list = EntityUtils.toString(entity, "UTF-8");
return schedule_list;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
#Override
protected void onPostExecute(String data) {
if(data != null){
jsonfromapi = data; //you would get json data here
//then do parse your json data
}
}
}
// end of async task
}
VisitsDOA class
public class VisitsDAO {
public static final String TAG = "visitsDAO";
// Database fields
private SQLiteDatabase mDatabase;
private DBHelper mDbHelper;
private Context mContext;
private String[] mAllColumns = {
DBHelper.COLUMN_VISITS_ID,
DBHelper.COLUMN_VISITS_SCHEDULE_ID,
DBHelper.COLUMN_VISITS_NAME,
DBHelper.COLUMN_VISITS_TIME,
DBHelper.COLUMN_VISITS_PLACE,
DBHelper.COLUMN_VISITS_ADDRESS,
DBHelper.COLUMN_VISITS_LOCATION_LAT,
DBHelper.COLUMN_VISITS_LOCATION_LNG,
DBHelper.COLUMN_VISITS_STATUS };
public VisitsDAO(Context context) {
this.mContext = context;
mDbHelper = new DBHelper(context);
// open the database
try {
open();
} catch (SQLException e) {
Log.e(TAG, "SQLException on openning database " + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDbHelper.getWritableDatabase();
}
public void close() {
mDbHelper.close();
}
public Visits createvisits(int vid, int v_sid, String vname, String vtime, String vplace, String address, String vlat, String vlong, int vstatus) {
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_VISITS_ID, vid);
values.put(DBHelper.COLUMN_VISITS_SCHEDULE_ID, v_sid);
values.put(DBHelper.COLUMN_VISITS_NAME, vname);
values.put(DBHelper.COLUMN_VISITS_TIME, vtime);
values.put(DBHelper.COLUMN_VISITS_PLACE, vplace);
values.put(DBHelper.COLUMN_VISITS_ADDRESS, address);
values.put(DBHelper.COLUMN_VISITS_LOCATION_LAT, vlat);
values.put(DBHelper.COLUMN_VISITS_LOCATION_LNG, vlong);
values.put(DBHelper.COLUMN_VISITS_STATUS, vstatus);
long insertId = mDatabase
.insert(DBHelper.TABLE_VISITS, null, values);
Cursor cursor = mDatabase.query(DBHelper.TABLE_VISITS, mAllColumns,
DBHelper.COLUMN_VISITS_ID + " = " + insertId, null, null,
null, null);
Visits newvisits = null;
if (cursor != null&& cursor.moveToFirst()) {
cursor.moveToFirst();
newvisits = cursorTovisits(cursor);
}
cursor.close();
return newvisits;
}
public List<Visits> getAllvisits() {
List<Visits> listVisits = new ArrayList<Visits>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_VISITS, mAllColumns,
null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Visits visits = cursorTovisits(cursor);
listVisits.add(visits);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listVisits;
}
public List<Visits> getAllvisitsforSchedule(int id) {
List<Visits> listVisits = new ArrayList<Visits>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_VISITS, mAllColumns,
DBHelper.COLUMN_VISITS_SCHEDULE_ID + " = ?",
new String[]{String.valueOf(id)}, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Visits visits = cursorTovisits(cursor);
listVisits.add(visits);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listVisits;
}
public Visits getvisitById(int id) {
Cursor cursor = mDatabase.query(DBHelper.TABLE_VISITS, mAllColumns,
DBHelper.COLUMN_VISITS_ID + " = ?",
new String[]{String.valueOf(id)}, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
Visits visits = cursorTovisits(cursor);
return visits;
}
protected Visits cursorTovisits(Cursor cursor) {
Visits schedule = new Visits();
schedule.setvId(cursor.getInt(0));
schedule.setVschID(cursor.getInt(1));
schedule.setVname(cursor.getString(2));
schedule.setVtime(cursor.getString(3));
schedule.setVplace(cursor.getString(4));
schedule.setVaddress(cursor.getString(5));
schedule.setVlat(cursor.getString(6));
schedule.setVlong(cursor.getString(7));
schedule.setVstatus(cursor.getInt(8));
return schedule;
}
public void deleteVisits(Visits visits) {
long id = visits.getvId();
mDatabase.delete(DBHelper.TABLE_VISITS, DBHelper.COLUMN_VISITS_ID + " = " + id, null);
}
public void deleteAllVisits() {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
db.delete(DBHelper.TABLE_VISITS, null, null);
}
}
dbhelper class
public class DBHelper extends SQLiteOpenHelper {
public static final String TAG = "DBHelper";
// columns of the schedule table
public static final String TABLE_SCHEDULE= "schedule";
public static final String COLUMN_SCHEDULE_ID = "schedule_id";
public static final String COLUMN_SCHEDULE_NAME = "schedule_name";
public static final String COLUMN_SCHEDULE_DATE = "schedule_date";
// columns of the items table
public static final String TABLE_ITEM= "items";
public static final String COLUMN_ITEM_ID = "item_id";
public static final String COLUMN_ITEM_VISIT_ID = "visit_id";
public static final String COLUMN_ITEM_NAME = "item_name";
public static final String COLUMN_ITEM_CHECK_STATUS= "item_check_status";
public static final String COLUMN_ITEM_COMMENT = "item_comment";
public static final String COLUMN_ITEM_LAT = "item_latitude";
public static final String COLUMN_ITEM_LNG = "item_longitude";
public static final String COLUMN_ITEM_SUB_TIME = "item_submit_time";
public static final String COLUMN_ITEM_REMOTE_status = "item_remote_status";
// columns of the employees table
public static final String TABLE_VISITS = "visits";
public static final String COLUMN_VISITS_ID = "visit_id";
public static final String COLUMN_VISITS_SCHEDULE_ID = "schedule_id";
public static final String COLUMN_VISITS_NAME = "visit_name";
public static final String COLUMN_VISITS_TIME = "visit_time";
public static final String COLUMN_VISITS_PLACE = "visit_place";
public static final String COLUMN_VISITS_ADDRESS ="visit_address";
public static final String COLUMN_VISITS_LOCATION_LAT = "visit_location_lat";
public static final String COLUMN_VISITS_LOCATION_LNG = "visit_location_lng";
public static final String COLUMN_VISITS_STATUS = "visit_status";
private static final String DATABASE_NAME = "certisagent";
private static final int DATABASE_VERSION = 7;
// SQL statement of the visits table creation
private static final String SQL_CREATE_TABLE_VISITS = "CREATE TABLE " + TABLE_VISITS + "("
+ COLUMN_VISITS_ID + " INTEGER PRIMARY KEY, "
+ COLUMN_VISITS_SCHEDULE_ID + " INTEGER, "
+ COLUMN_VISITS_NAME + " TEXT NOT NULL, "
+ COLUMN_VISITS_TIME + " TEXT NOT NULL, "
+ COLUMN_VISITS_PLACE + " TEXT NOT NULL, "
+ COLUMN_VISITS_ADDRESS + " TEXT NOT NULL, "
+ COLUMN_VISITS_LOCATION_LAT + " TEXT NOT NULL, "
+ COLUMN_VISITS_LOCATION_LNG + " TEXT NOT NULL, "
+ COLUMN_VISITS_STATUS + " INTEGER "
+");";
// SQL statement of the schedule table creation
private static final String SQL_CREATE_TABLE_SCHEDULE = "CREATE TABLE " + TABLE_SCHEDULE + "("
+ COLUMN_SCHEDULE_ID + " INTEGER PRIMARY KEY, "
+ COLUMN_SCHEDULE_NAME + " TEXT NOT NULL, "
+ COLUMN_SCHEDULE_DATE + " TEXT NOT NULL "
+");";
// SQL statement of the item table creation
private static final String SQL_CREATE_TABLE_ITEMS = "CREATE TABLE " + TABLE_ITEM + "("
+ COLUMN_ITEM_ID + " INTEGER PRIMARY KEY, "
+ COLUMN_ITEM_VISIT_ID + " INTEGER, "
+ COLUMN_ITEM_NAME + " TEXT NOT NULL, "
+ COLUMN_ITEM_CHECK_STATUS + " INTEGER, "
+ COLUMN_ITEM_COMMENT + " TEXT, "
+ COLUMN_ITEM_LAT + " TEXT, "
+ COLUMN_ITEM_LNG + " TEXT, "
+ COLUMN_ITEM_SUB_TIME + " TEXT, "
+ COLUMN_ITEM_REMOTE_status + " INTEGER "
+");";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(SQL_CREATE_TABLE_SCHEDULE);
database.execSQL(SQL_CREATE_TABLE_VISITS);
database.execSQL(SQL_CREATE_TABLE_ITEMS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG,
"Upgrading the database from version " + oldVersion + " to " + newVersion);
// clear all data
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCHEDULE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_VISITS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEM);
// recreate the tables
onCreate(db);
}
}
Error Stack
Process: lk.agent.certislanka.certisagenttracking, PID: 15681
java.lang.RuntimeException: Unable to start activity ComponentInfo{lk.agent.certislanka.certisagenttracking/lk.agent.certislanka.certisagenttracking.mainmenu}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2429)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.access$800(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at lk.agent.certislanka.certisagenttracking.mainmenu.onCreate(mainmenu.java:79)
at android.app.Activity.performCreate(Activity.java:5442)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.access$800(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
You need to add
mvisitsDAO = new VisitsDAO(getApplicationContext());
before you perform the delete in onCreate()
I am new to android, I am trying to retrieve values from a sqlite database based on the listview values. I tried to retrieve values using string variable. I can do this if I directly substitute the value in the place of variable.
Following this I post my codes kindly help me to sort out this.
DBhelper.java
public class DBHelper extends SQLiteOpenHelper{
public SQLiteDatabase DB;
public String DBPath;
public static String DBName = "VERIFY ME1.sqlite3";
public static final int version = '1';
public static Context currentContext;
public static String tableName = "FORM2";
public DBHelper(Context context) {
super(context, DBName, null, version);
currentContext = context;
DBPath = "/data/data/" + context.getPackageName() + "/databases";
createDatabase();
Oninsert(DB);
}
#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
}
private void createDatabase() {
boolean dbExists = checkDbExists();
if (dbExists) {
// do nothing
}
else {
DB = currentContext.openOrCreateDatabase(DBName, 0, null);
DB.execSQL("CREATE TABLE IF NOT EXISTS " +tableName +" (AppNo VARCHAR, AppName VARCHAR," +
" Area VARCHAR, FHcode INT(3));");
}}
private boolean checkDbExists() {
SQLiteDatabase checkDB = null;
try {
String myPath = DBPath + DBName;
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 Oninsert(SQLiteDatabase dB2) {
// TODO Auto-generated method stub
DB = currentContext.openOrCreateDatabase(DBName, 0, null);
DB.execSQL("INSERT INTO " +
tableName +
" Values ('M001','shumi','India',250);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('C002','sarah','India',251);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('D003','Lavya','USA',252);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('V004','Avi','EU',253);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('T005','Shenoi','Bangla',254);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('L006','Lamha','Australia',255);");
DB.close();
}
}
ListActivity.java
public class login2 extends ListActivity implements OnItemClickListener {
private static final login2 ListActivity = null;
private static final AdapterView<?> parent = null;
private static int mPosition = 0;
private static final long id = 0;
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DBHelper.tableName;
private SQLiteDatabase newDB;
private String AppName1,ApplID,FHcode,Area;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
getListView().setOnItemClickListener(this);
}
private String openAndQueryDatabase() {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT * FROM " +tableName +"", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
AppName1 = c.getString(c.getColumnIndex("AppName"));
results.add(AppName1 );
}while (c.moveToNext());
}
}
c.close();
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
//if (newDB == null)
// newDB.execSQL("DELETE FROM " + tableName);
//newDB.close();
}
return AppName1;
}
public void onClick(View arg0) {
login2 det = (login2)ListActivity;
det.onItemClick(parent, arg0, mPosition, id);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
String data=(String)parent.getItemAtPosition(position);
//showMessage("Successfully", data);
if (data != null ) {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c1 = newDB.rawQuery("SELECT DISTINCT AppNo, AppName, FHcode, Area FROM "
+tableName +" where AppName ="+data+"" ,null);
if (c1 != null ) {
if (c1.moveToFirst()) {
do {
ApplID= c1.getString(c1.getColumnIndex("AppNo"));
String AppName =c1.getString(c1.getColumnIndex("AppName"));
Area = c1.getString(c1.getColumnIndex("Area"));
FHcode =c1.getString(c1.getColumnIndex("FHcode"));
Intent intent = new Intent(getApplicationContext(), form.class);
//Create a bundle object
Bundle b = new Bundle();
//Inserts a String value into the mapping of this Bundle
b.putString("AppName", AppName.toString());
b.putString("Apprefno", ApplID.toString());
b.putString("FHcode", FHcode.toString());
b.putString("Area", Area.toString());
//Add the bundle to the intent.
intent.putExtras(b);
//start the DisplayActivity
startActivity(intent);
}
while (c1.moveToNext());
}
}
}
catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
//if (newDB == null)
//newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
public void showMessage (String title, String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
You have taken this column as an integer FHcode INT(3)
and trying to fetch values as an string that is wrong
c1.getString(c1.getColumnIndex("FHcode")
change to c1.getInt**(c1.getColumnIndex("FHcode")
I keep getting the error message Close() was never explicitly called on database. From what I've read I'm not closing the database once the activity is destroyed, but I don't know how to implement it:
Database Helper:
public class ResultsDatabase extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "results.db";
private static final int DATABASE_VERSION = 2;
public static final String TABLE_NAME = "results";
public static final String _ID = BaseColumns._ID;
public static final String SAVED_NAME = "name";
public static final String COLUMN_NAME_CREATE_DATE = "date";
public static final String RIGHT_EAR = "right_ear";
public static final String LEFT_EAR = "left_ear";
public ResultsDatabase(Context context) {
// calls the super constructor, requesting the default cursor factory.
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
+ _ID + " INTEGER PRIMARY KEY,"
+ SAVED_NAME + " TEXT,"
+ COLUMN_NAME_CREATE_DATE + " INTEGER,"
+ RIGHT_EAR + " BLOB,"
+ LEFT_EAR + " BLOB"
+ ");");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
}
public void storeResults(String name, List<EarSrt> leftAnswerList, List<EarSrt> rightAnswerList){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(SAVED_NAME, name);
Long now = Long.valueOf(System.currentTimeMillis());
values.put(COLUMN_NAME_CREATE_DATE, now);
values.put(RIGHT_EAR, serializeObject(rightAnswerList ));
values.put(LEFT_EAR, serializeObject(leftAnswerList ));
db.insert(TABLE_NAME, null, values);
}
public static byte[] serializeObject(Object o) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(o);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
return buf;
} catch(IOException ioe) {
Log.e("serializeObject", "error", ioe);
return null;
}
}
public static Object deserializeObject(byte[] b) {
try {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b));
Object object = in.readObject();
in.close();
return object;
} catch(ClassNotFoundException cnfe) {
Log.e("deserializeObject", "class not found error", cnfe);
return null;
} catch(IOException ioe) {
Log.e("deserializeObject", "io error", ioe);
return null;
}
}
}
I call this helper in my Tabbed Results Activity which displays the data in two different fragments as follows:
public class TabbedResultsActivity extends SherlockFragmentActivity{
TabHost mTabHost;
TabManager mTabManager;
public static final String IS_RIGHT_EAR = "is_right_ear";
private ArrayList<EarSrt> leftAnswerList;
private ArrayList<EarSrt> rightAnswerList;
private final static String TAG = "HearingTest";
private boolean isRightEarTab = true;
private boolean bothEarsBad;
private boolean leftEarBad;
private boolean rightEarBad;
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_layout);
ActionBar ab = this.getSupportActionBar();
SherlockHelper.setupActionBar(ab, this);
View infoButton = findViewById(R.id.info_button);
infoButton.setVisibility(View.VISIBLE);
Intent intent = getIntent();
int rowId = intent.getIntExtra(ResultsDatabase._ID, -1);
if ( rowId != -1 ) {
ResultsDatabase db = new ResultsDatabase(this);
String select = "(" + ResultsDatabase._ID + " == " + rowId + ")";
Cursor c = db.getReadableDatabase().query(ResultsDatabase.TABLE_NAME, null, select, null, null, null,null);
if ( c.moveToFirst() ) {
int leftEarColumn = c.getColumnIndex(ResultsDatabase.LEFT_EAR);
byte[] leftEarByteArray = c.getBlob(leftEarColumn);
int rightEarColumn = c.getColumnIndex(ResultsDatabase.RIGHT_EAR);
byte[] rightEarByteArray = c.getBlob(rightEarColumn);
leftAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(leftEarByteArray);
rightAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(rightEarByteArray);
}
} else {
byte[] leftEarByteArray = getIntent().getByteArrayExtra(ResultsDatabase.LEFT_EAR);
byte[] rightEarByteArray = getIntent().getByteArrayExtra(ResultsDatabase.RIGHT_EAR);
leftAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(leftEarByteArray);
rightAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(rightEarByteArray);
}
isRightEarTab = getIntent().getBooleanExtra(IS_RIGHT_EAR, true);
GraphView graphView = new GraphView(this);
graphView.setPoints(rightAnswerList);
float leftAverage = calculateAverage(rightAnswerList);
graphView.setAverage(leftAverage);
graphView.setPoints(leftAnswerList);
float rightAverage = calculateAverage(leftAnswerList);
graphView.setAverage(rightAverage);
setResults(leftAnswerList, rightAnswerList);
String results = setResultCaption(bothEarsBad, leftEarBad, rightEarBad).toString();
Log.d(TAG, "The results were " + results);
Bundle leftbundle = new Bundle();
leftbundle.putString("results", results);
leftbundle.putParcelableArrayList("graph", leftAnswerList);
leftbundle.putFloat("average", leftAverage);
Bundle rightbundle = new Bundle();
rightbundle.putString("results", results);
rightbundle.putParcelableArrayList("graph", rightAnswerList);
rightbundle.putFloat("average", rightAverage);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
mTabManager = new TabManager(this, mTabHost, R.id.realtabcontent);
mTabManager.addTab(mTabHost.newTabSpec(getString(R.string.Left_ear)).setIndicator(getString(R.string.Left_ear)),
LeftEarResults.class, leftbundle);
mTabManager.addTab(mTabHost.newTabSpec("contacts").setIndicator(getString(R.string.Right_ear)),
RightEarResults.class, rightbundle);
if (savedInstanceState != null) {
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("tab", mTabHost.getCurrentTabTag());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return MenuActivity.createMenu(this, menu);
}
private float calculateAverage(List<EarSrt> steps) {
float srt = 0.0f;
int length = steps.size();
for (int i = (int)Math.ceil( (float)length/(float)2); i < length; i++) {
EarSrt es = steps.get(i);
srt += es.getSrt();
}
srt = srt / (length-(float)Math.ceil( (float)length/(float)2));
return srt;
}
private void setResults(List<EarSrt> leftEar, List<EarSrt> rightEar) {
float esLeft = calculateAverage(leftEar);
float esRight = calculateAverage(rightEar);
leftEarBad = (esLeft > 24.0);
rightEarBad = (esRight > 24.0);
bothEarsBad = (leftEarBad && rightEarBad);
}
private StringBuilder setResultCaption(boolean bothEarsBad, boolean leftEarBad, boolean rightEarBad) {
String resultCaption;
StringBuilder resultsText = new StringBuilder();
if (bothEarsBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
}else{
if (leftEarBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss_for_your_left_ear));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
} else if (rightEarBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss_for_your_Right_ear));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
}else {
resultsText.append(getString(R.string.There_is_no_indication_of_hearing_loss));
}
}
resultsText.append(getString(R.string.The_results_of_the_hearing_test_are_not_to_be_utilized_as_an_official_outcome_for_assessing_levels_of_hearing_loss_True_hearing_loss_assessments_can_only_be_determined_by_a_licensed_hearing_healthcare_provider));
Log.d(TAG, "The results were " + resultsText);
return resultsText;
}
public void infoView(View aView) {
Intent intent = new Intent(this, InfoActivity.class);
startActivity(intent);
}
}
My quesiton is how and where should I close the connection?
Thanks
Just alter your storeResults method as follows
public void storeResults(String name, List<EarSrt> leftAnswerList, List<EarSrt> rightAnswerList){
SQLiteDatabase db = getWritableDatabase(); // opens the database connection
try {
ContentValues values = new ContentValues();
values.put(SAVED_NAME, name);
Long now = Long.valueOf(System.currentTimeMillis());
values.put(COLUMN_NAME_CREATE_DATE, now);
values.put(RIGHT_EAR, serializeObject(rightAnswerList ));
values.put(LEFT_EAR, serializeObject(leftAnswerList ));
db.insert(TABLE_NAME, null, values);
}
catch(Exception e) {
e.printStackTrace();
// furher error handling
}
finally {
db.close(); // closes the database every time after access
}
}
I am sending a data via JSON to my apps,it displays in my ListView, without internet is not working,so i want to make an database to store the JSON parsing data alone.I tried to create a database for JSON storing but its not properly done. How can I solve this problem?
Myadapterclass.java
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 my mainactivity which contains listview of data
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();
String url = "http://www.ginfy.com/api/v1/posts.json";
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(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);
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);
}
I changed my code like this it shwoing error in JSONparser line
I have a SQLLite DB that stores an ftp site's login information (name,address,username,password,port,passive). When an item (site) is clicked in the list, it's supposed to load the name, address, username, password etc. into the corresponding EditTexts. What's happening is that the password value is getting loaded into the address EditText and the address isn't getting loaded anywhere.
My Activity's addRecord function looks like this:
public void addRecord() {
long newId = myDb.insertRow(_name, _address, _username, _password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
The order of the parameters in insertRow() correspond to the order in my DBAdapter, however when I change the order of the parameters I can get the address and password values to end up in the correct EditTexts, just never all of them at once. What am I doing wrong?
public class DBAdapter {
// ///////////////////////////////////////////////////////////////////
// Constants & Data
// ///////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_PORT = "port";
public static final String KEY_PASSIVE = "passive";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_ADDRESS = 2;
public static final int COL_USERNAME = 3;
public static final int COL_PASSWORD = 4;
public static final int COL_PORT = 5;
public static final int COL_PASSIVE = 6;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_NAME,
KEY_ADDRESS, KEY_USERNAME, KEY_PASSWORD, KEY_PORT, KEY_PASSIVE };
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Sites";
public static final String DATABASE_TABLE = "SiteTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL = "create table "
+ DATABASE_TABLE
+ " ("
+ KEY_ROWID
+ " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a
// value).
// NOTE: All must be comma separated (end of line!) Last one must
// have NO comma!!
+ KEY_NAME + " string not null, " + KEY_ADDRESS
+ " string not null, " + KEY_USERNAME + " string not null, "
+ KEY_PASSWORD + " string not null, " + KEY_PORT
+ " integer not null," + KEY_PASSIVE + " integer not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
// ///////////////////////////////////////////////////////////////////
// Public methods:
// ///////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, String address, String user,
String pass, int port, int passive) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_ADDRESS, address);
initialValues.put(KEY_USERNAME, user);
initialValues.put(KEY_PASSWORD, pass);
initialValues.put(KEY_PORT, port);
initialValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, String address,
String username, String password, int port, int passive) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
newValues.put(KEY_PASSWORD, password);
newValues.put(KEY_PORT, port);
newValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
// ///////////////////////////////////////////////////////////////////
// Private Helper Classes:
// ///////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading. Used to
* handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
public class SiteManager extends Activity {
DBAdapter myDb;
public FTPClient mFTPClient = null;
public EditText etSitename;
public EditText etAddress;
public EditText etUsername;
public EditText etPassword;
public EditText etPort;
public CheckBox cbPassive;
public ListView site_list;
public Button clr;
public Button test;
public Button savesite;
public Button close;
public Button connect;
String _name;
String _address;
String _username;
String _password;
int _port;
int _passive = 0;
List<FTPSite> model = new ArrayList<FTPSite>();
ArrayAdapter<FTPSite> adapter;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.site_manager);
site_list = (ListView) findViewById(R.id.siteList);
adapter = new SiteAdapter(this, R.id.ftpsitename, R.layout.siterow,
model);
site_list.setAdapter(adapter);
etSitename = (EditText) findViewById(R.id.dialogsitename);
etAddress = (EditText) findViewById(R.id.dialogaddress);
etUsername = (EditText) findViewById(R.id.dialogusername);
etPassword = (EditText) findViewById(R.id.dialogpassword);
etPort = (EditText) findViewById(R.id.dialogport);
cbPassive = (CheckBox) findViewById(R.id.dialogpassive);
close = (Button) findViewById(R.id.closeBtn);
connect = (Button) findViewById(R.id.connectBtn);
clr = (Button) findViewById(R.id.clrBtn);
test = (Button) findViewById(R.id.testBtn);
savesite = (Button) findViewById(R.id.saveSite);
addListeners();
openDb();
displayRecords();
}
public void addListeners() {
connect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent returnResult = new Intent();
returnResult.putExtra("ftpname", _name);
returnResult.putExtra("ftpaddress", _address);
returnResult.putExtra("ftpusername", _username);
returnResult.putExtra("ftppassword", _password);
returnResult.putExtra("ftpport", _port);
setResult(RESULT_OK, returnResult);
finish();
}
});
test.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = etSitename.getText().toString();
_address = etAddress.getText().toString();
_username = etUsername.getText().toString();
_password = etPassword.getText().toString();
_port = Integer.parseInt(etPort.getText().toString());
if (cbPassive.isChecked()) {
_passive = 1;
} else {
_passive = 0;
}
boolean status = ftpConnect(_address, _username, _password,
_port);
ftpDisconnect();
if (status == true) {
Toast.makeText(SiteManager.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
savesite.setVisibility(0);
} else {
Toast.makeText(SiteManager.this,
"Connection Failed:" + status, Toast.LENGTH_LONG)
.show();
}
}
});
savesite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = etSitename.getText().toString();
_address = etAddress.getText().toString();
_username = etUsername.getText().toString();
_password = etPassword.getText().toString();
_port = Integer.parseInt(etPort.getText().toString());
if (cbPassive.isChecked()) {
_passive = 1;
} else {
_passive = 0;
}
addRecord();
adapter.notifyDataSetChanged();
}
});
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
clr.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clearAll();
}
});
site_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final FTPSite item = (FTPSite) parent
.getItemAtPosition(position);
String tmpname = item.getName();
String tmpaddress = item.getAddress();
String tmpuser = item.getUsername();
String tmppass = item.getPassword();
int tmpport = item.getPort();
String tmp_port = Integer.toString(tmpport);
int tmppassive = item.isPassive();
etSitename.setText(tmpname);
etAddress.setText(tmpaddress);
etUsername.setText(tmpuser);
etPassword.setText(tmppass);
etPort.setText(tmp_port);
if (tmppassive == 1) {
cbPassive.setChecked(true);
} else {
cbPassive.setChecked(false);
}
}
});
}
public void addRecord() {
long newId = myDb.insertRow(_name, _username, _address,_password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
public void displayRecords() {
Cursor cursor = myDb.getAllRows();
displayRecordSet(cursor);
}
protected void displayRecordSet(Cursor c) {
// String msg = "";
if (c.moveToFirst()) {
do {
// int id = c.getInt(0);
_name = c.getString(1);
_address = c.getString(2);
_username = c.getString(3);
_password = c.getString(4);
_port = c.getInt(5);
FTPSite sitesFromDB = new FTPSite();
sitesFromDB.setName(_name);
sitesFromDB.setAddress(_address);
sitesFromDB.setUsername(_username);
sitesFromDB.setAddress(_password);
sitesFromDB.setPort(_port);
sitesFromDB.setPassive(_passive);
model.add(sitesFromDB);
adapter.notifyDataSetChanged();
} while (c.moveToNext());
}
c.close();
}
public void clearAll() {
myDb.deleteAll();
adapter.notifyDataSetChanged();
}
public boolean ftpConnect(String host, String username, String password,
int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch (Exception e) {
// Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
public boolean ftpDisconnect() {
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch (Exception e) {
// Log.d(TAG,
// "Error occurred while disconnecting from ftp server.");
}
return false;
}
class SiteAdapter extends ArrayAdapter<FTPSite> {
private final List<FTPSite> objects;
private final Context context;
public SiteAdapter(Context context, int resource,
int textViewResourceId, List<FTPSite> objects) {
super(context, R.id.ftpsitename, R.layout.siterow, objects);
this.context = context;
this.objects = objects;
}
/** #return The number of items in the */
public int getCount() {
return objects.size();
}
public boolean areAllItemsSelectable() {
return false;
}
/** Use the array index as a unique id. */
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.siterow, parent, false);
TextView textView = (TextView) rowView
.findViewById(R.id.ftpsitename);
textView.setText(objects.get(position).getName());
return (rowView);
}
}
I think you should try to use :
int keyNameIndex = c.getColumnIndex(DBAdapter.KEY_NAME);
_name = c.getString(keyNameIndex);
Instead of using direct number.I am not sure it cause the bug, but it gonna be better exercise. Hope it's help.
There is mismatch in your arguments see below
public long insertRow(String name, String address, String user,
String pass, int port, int passive) {
public void addRecord() {
long newId = myDb.insertRow(_name, _username, _address,_password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
you are passing username to address and address to user
This is embarrassing. I had sitesFromDB.setAddress(_password); instead of sitesFromDB.setPassword(_password);