我试图从数据库中删除所有记录,并插入每次活动加载时从远程数据库获取的记录。
我可以插入数据。但是当我尝试从表中删除所有记录时,我得到了错误。
我的代码
主菜单类
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课程
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类
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);
}
}
错误堆栈
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)
答案 0 :(得分:1)
您需要添加
mvisitsDAO = new VisitsDAO(getApplicationContext());
在onCreate()