此代码之前工作正常,数据库已在2017年制作了表格,但不知何故,这些表格不再有效,无法在数据库中创建表格并从中检索数据。安卓工作室没有引起任何错误。从最近1周开始,这就搞定了。
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private EditText inputName, inputEmail, inputPassword;
private TextInputLayout inputLayoutName, inputLayoutEmail, inputLayoutPassword;
private Button btnSignUp,btnLogout;
//private static final String SITE_URL="http://182.19.41.106/src/okcl/";
private static final String SITE_URL="http://www.wetswd.in/android-data";
private static final String CHECK_URL = SITE_URL+"sign-up.php";
private static final String REGISTER_URL = SITE_URL+"android-process.php";
private static final String UNREGISTER_URL = SITE_URL+"android-process_unregister.php";
private static final String LOGOUT_URL = SITE_URL+"sign-up.php;// logout.php";
private static final String VERSION="1.05";
private static final String pin = "1234";//SN:added for flexibility
private DBHelper mydb ;
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mydb = new DBHelper(this);
//Add from XML Later
//MyReceiver reMyreceive = new MyReceiver();
//IntentFilter filter = new IntentFilter("BROADCAST_ACTION");
//registerReceiver(reMyreceive, filter);
inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_name);
inputLayoutPassword = (TextInputLayout) findViewById(R.id.input_layout_password);
inputName = (EditText) findViewById(R.id.input_name);
inputPassword = (EditText) findViewById(R.id.input_password);
btnSignUp = (Button) findViewById(R.id.btn_signup);
Boolean isServiceRunning=isMyServiceRunning(MyService.class);
if(isServiceRunning)
btnSignUp.setBackgroundColor(Color.RED);
else btnSignUp.setBackgroundColor(Color.BLUE);
btnLogout = (Button) findViewById(R.id.btn_logout);
inputName.addTextChangedListener(new MyTextWatcher(inputName));
inputPassword.addTextChangedListener(new MyTextWatcher(inputPassword));
btnSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
submitForm(view);
}
});
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//logOut();
if (!validateName()) {
return;
}
if (!validatePassword()) {
return;
}
String macAdd = getMAC();
String dateTime = getDateTime();
String status = "out_"+inputName.getText().toString().trim();
if (isNetworkAvailable(getApplicationContext())) {
mydb.insertContact(macAdd , dateTime , "0", "0" , status , "N",pin);//inputName.getText().toString().trim(),
logOut(macAdd, inputName.getText().toString().trim(), inputPassword.getText().toString().trim(),pin);
//stopService(); is called inside logout
} else {
mydb.insertContact(macAdd , dateTime , "0", "0" , status.toUpperCase(), "N",pin);//,inputName.getText().toString().trim(),"9999"
btnLogout.setText(R.string.btn_LogOut);// "LOGOUT");
stopService(); //without Checking
Toast.makeText(getApplicationContext(), "LOG Stopped", Toast.LENGTH_LONG).show();
}
}
});
}
/**
* Validating form
*/
private void submitForm(View view) {
if (!validateName()) {
return;
}
if (!validatePassword()) {
return;
}
GPS_Slim gps = new GPS_Slim(MainActivity.this);
//gps.setUsrId(inputName.getText().toString().trim());
//gps.setPin(pin);
if (gps.canGetLocation()) {
double latitude = 20.37;//Near Park;
double longitude = 85.68;//Near Park
double acc=9999.0;//gps.getAccuracy();
String macAdd = getMAC();
String dateTime = getDateTime();
String status = "in_"+inputName.getText().toString().trim();
if(isNetworkAvailable(getApplicationContext())){
mydb.insertContact(macAdd , dateTime , String.valueOf(latitude), String.valueOf(longitude) , status , "N",pin);//,,String.valueOf(acc)
CheckUser(macAdd ,inputName.getText().toString().trim(),inputPassword.getText().toString().trim(),pin);
}else {
mydb.insertContact(macAdd , dateTime , String.valueOf(latitude), String.valueOf(longitude) , status.toUpperCase(), "N",pin);//,inputName.getText().toString().trim(),String.valueOf(acc)
Toast.makeText(getApplicationContext(), "Stored Internally", Toast.LENGTH_LONG).show();
btnLogout.setText(R.string.btn_LogOut+" #"+inputName.getText().toString().trim());
startService(); //without Checking//SN:Can I pass Pin here
Toast.makeText(getApplicationContext(), "LOG Started", Toast.LENGTH_LONG).show();
}
} else {
gps.showSettingsAlert();
}
//gps.locationManager.removeUpdates();//SN:Check if used?? GPS object is local here
//gps = null;
}
private boolean validateName() {
if (inputName.getText().toString().trim().isEmpty()) {
inputLayoutName.setError(getString(R.string.err_msg_name));
requestFocus(inputName);
return false;
} else {
inputLayoutName.setErrorEnabled(false);
}
return true;
}
private boolean validatePassword() {
if (inputPassword.getText().toString().trim().isEmpty()) {
inputLayoutPassword.setError(getString(R.string.err_msg_password));
requestFocus(inputPassword);
return false;
} else {
inputLayoutPassword.setErrorEnabled(false);
}
return true;
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.input_name: validateName(); break;
case R.id.input_password: validatePassword(); break;
}
}
}
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
private String getMAC(){
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
return wInfo.getMacAddress();
}
private String getDateTime(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(new Date());
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
private void register(String mac, String dateT, String lat, String lon,String pin,String usr,String ver) {
class RegisterUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait",null, true, true);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<>();
data.put("macid",params[0]);
data.put("datetime",params[1]);
data.put("lat",params[2]);
data.put("long",params[3]);
data.put("pin",params[4]);//SN:added for Flexibility
data.put("usr",params[5]);//SN:added for Flexibility
data.put("ver",params[6]);//SN:added for Flexibility
return ruc.sendPostRequest(REGISTER_URL,data);
}
}
RegisterUser ru = new RegisterUser();
ru.execute(mac,dateT,lat,lon,pin,usr,ver);
}
private void CheckUser(String mac_id,final String user_id,String password,final String pin) {
class CheckUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait",null, true, true);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),"Received:"+s,Toast.LENGTH_SHORT).show();
if(s.equalsIgnoreCase("Unauthorised User")){
Toast.makeText(getApplicationContext(),"Login Fail",Toast.LENGTH_LONG).show();
}else{ //Sucessfully Login
double latitude = 20.37;//Near Park;
double longitude = 85.68;//Near Park
String macAdd = getMAC();
String dateTime = getDateTime();
register(macAdd , dateTime , String.valueOf(latitude), String.valueOf(longitude),pin,user_id,VERSION);
Toast.makeText(getApplicationContext(), "Login Pass", Toast.LENGTH_LONG).show();
startService();
Toast.makeText(getApplicationContext(), "LOG Started", Toast.LENGTH_LONG).show();
btnLogout.setText(btnLogout.getText().toString()+" *"+inputName.getText().toString().trim());
}
}
@Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<>();
data.put("macid",params[0]);
data.put("userid",params[1]);
data.put("password",params[2]);
data.put("pin",params[3]);
return ruc.sendPostRequest(CHECK_URL,data);
}
}
CheckUser ru = new CheckUser();
ru.execute(mac_id,user_id,password,pin);
}
private void logOut(String mac_id,final String user_id,String password,final String pin) {
class LogOUt extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait",null, true, true);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),"Received:"+s,Toast.LENGTH_SHORT).show();
if(s.equalsIgnoreCase("Unauthorised User")){
Toast.makeText(getApplicationContext(),"Login Fail",Toast.LENGTH_LONG).show();
}else{ //Sucessfully Login
double latitude = 20.37;//Near Park;20.37 85.68
double longitude = 85.68;//Near Park
String macAdd = getMAC();
String dateTime = getDateTime();
register(macAdd , dateTime ,String.valueOf(latitude), String.valueOf(longitude),pin,user_id,VERSION);
Toast.makeText(getApplicationContext(), "Login Pass", Toast.LENGTH_LONG).show();
//Set Active=0 in android_data for macAdd
stopService();
HashMap<String, String> data = new HashMap<>();
data.put("macid",macAdd);
data.put("pin",pin);//SN:added for Flexibility
String result = ruc.sendPostRequest(UNREGISTER_URL,data);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
//Toast.makeText(getApplicationContext(), "LOG Stopped", Toast.LENGTH_LONG).show();//20170821:Sn Testing
btnLogout.setText(R.string.btn_LogOut);//"LOGOUT");
}
}
@Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<>();
data.put("macid",params[0]);
data.put("userid",params[1]);
data.put("password",params[2]);
data.put("pin",params[3]);
return ruc.sendPostRequest(LOGOUT_URL,data);
}
}
LogOUt ru = new LogOUt();
ru.execute(mac_id,user_id, password,pin);
}
private void doUpdate(String s) {
}
// Method to start the service
public void startService() {Intent i=new Intent(getBaseContext(), MyService.class);
i.putExtra("user",inputName.getText().toString().trim());
i.putExtra("SITE_URL",SITE_URL);
i.putExtra("pin",pin);
i.putExtra("mac",getMAC());
i.putExtra("ver",VERSION);
i.putExtra("REGISTER_URL",REGISTER_URL);
startService(i);
Intent iActivity=new Intent(getBaseContext(), logOut.class);
iActivity.putExtra("user",inputName.getText().toString().trim());
startActivity(iActivity);
}
// Method to start the service
public void stopService() {
stopService(new Intent(getBaseContext(), MyService.class));
}
}
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "attendance.db";
public static final String RECORD_TABLE_NAME = "Record";
public static final String RECORD_COLUMN_ID = "id";
public static final String RECORD_COLUMN_MACID = "macid";
public static final String RECORD_COLUMN_DATETIME = "datetime";
public static final String RECORD_COLUMN_LAT = "lat";
public static final String RECORD_COLUMN_LONG = "long";
private HashMap hp;
public DBHelper(Context context) {
super(context, DATABASE_NAME , null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
Boolean tableExist=isTableExists("Record",false,db);//SN:Not Tested Code Added from https://stackoverflow.com/questions/3058909/how-does-one-check-if-a-table-exists-in-an-android-sqlite-database
if(!tableExist) {
db.execSQL("create table Record " +
"(id integer primary key, macid text,datetime text,lat text, long text , status text , uploadstatus text, pin text)");
}
//TimeLog Added by SN to KeepTime of Last Update
Boolean timeLogExist=isTableExists("timeLog",false,db);//SN:Not Tested Code Added from https://stackoverflow.com/questions/3058909/how-does-one-check-if-a-table-exists-in-an-android-sqlite-database
if(!timeLogExist) {
db.execSQL("create table timeLog " + "(id integer primary key, macid text,datetime Long,comment text)");//??SN: Long
//insertTimeLog(0L,"MSG_UPDATE","macid");
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS Record");
//db.execSQL("DROP TABLE IF EXISTS timeLog");
onCreate(db);
}
public boolean insertContact (String macid, String datetime, String lat, String longi , String status, String uploadstatus,String pin) { //,String usr,String acc- removed
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//macId,dateTime, String.valueOf(getLatitude()),String.valueOf(getLongitude()),"way","N",pin,usrId,accText
contentValues.put("macid", macid);
contentValues.put("datetime", datetime);
contentValues.put("lat", lat);
contentValues.put("long", longi);
contentValues.put("status", status);
contentValues.put("uploadstatus", uploadstatus);
contentValues.put("pin", pin);
db.insert("Record", null, contentValues);
return true;
}
public boolean updateContactNotUsed (Integer id, String macid, String datetime, String lat, String longi, String status, String uploadstatus) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("macid", macid);
contentValues.put("datetime", datetime);
contentValues.put("lat", lat);
contentValues.put("long", longi);
contentValues.put("status", status);
contentValues.put("uploadstatus", uploadstatus);
db.update("Record", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
return db.rawQuery( "select * from Record where id="+id+"", null );
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
return (int) DatabaseUtils.queryNumEntries(db, RECORD_TABLE_NAME);
}
public boolean updateTimeLog ( Long datetime, String key) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("datetime", datetime);
db.update("timeLog", contentValues, "comment = ? ", new String[] { key } );
return true;
}
public boolean insertTimeLog ( Long datetime, String key,String macid) { //,String usr,String acc- removed
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("datetime", datetime);
contentValues.put("comment", key);
contentValues.put("macid", macid);
db.insert("timeLog", null, contentValues);
return true;
}
public Integer deleteContact (Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("Record", "id = ? ", new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts() {
ArrayList<String> array_list = new ArrayList<>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from Record", null );
res.moveToFirst();
while(!res.isAfterLast()){
array_list.add(res.getString(res.getColumnIndex(RECORD_TABLE_NAME)));
res.moveToNext();
}
res.close();
return array_list;
}
public boolean isTableExists(String tableName, boolean openDb,SQLiteDatabase mDatabase) {
if(openDb) {
if(mDatabase == null || !mDatabase.isOpen()) {
mDatabase = this.getReadableDatabase();
}
if(!mDatabase.isReadOnly()) {
mDatabase.close();
mDatabase = this.getReadableDatabase();
}
}
Cursor cursor = mDatabase.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+tableName+"'", null);
if(cursor!=null) {
if(cursor.getCount()>0) {
cursor.close();
return true;
}
cursor.close();
}
return false;
}
}
的logcat-HTTPS://drive.google.com/file/d/1J1vhdRpP0GOQaRoCycHXWkXi_HiKPxxE/view USP =共享
答案 0 :(得分:0)
尝试将数据库版本升级到2,因为您要向数据库添加新表,需要升级数据库版本。
public DBHelper(Context context) {
super(context, DATABASE_NAME , null, 2);
}