我正在存储令牌和放大器sqlite中的userId,其中包含以下一项活动:
名称 - 获取“userId”&存储在sqlite数据库中的“令牌”。
SQLiteHandler - 存储“userID”& “令牌”。
注册 - 在此活动中,我想获取“userId”& “token”,它已经通过Name活动存储在Sqlite中。
我该怎么做?
名称
public class Name extends AppCompatActivity {
private static final String TAG = Name.class.getSimpleName();
private Button btn_name_next;
EditText emailid,editTextUserName;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name);
btn_name_next = (Button) findViewById(R.id.btn_name_next);
//emailid = (EditText) findViewById(R.id.emailid);
editTextUserName=(EditText) findViewById(R.id.editTextUserName);
final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
final String tmDevice, tmSerial, androidId;
tmDevice = "" + tm.getDeviceId();
tmSerial = "" + tm.getSimSerialNumber();
androidId = "" + Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
final String deviceId = deviceUuid.toString();
Log.e(TAG, "Device Id: " + deviceId);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(Name.this,
MakemeHealthy.class);
startActivity(intent);
finish();
}
btn_name_next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// String id = emailid.getText().toString();
String name=editTextUserName.getText().toString();
if (name.length()==0) {
editTextUserName.setError("Tell us your name atleast");
}
else
{
//launchAgeScreen();
registerUser(name, deviceId);
}
}
});
}
private void registerUser(final String name, final String deviceId) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.NAME_REGISTER, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean success = jObj.getBoolean("success");
//boolean error = jObj.getBoolean("error");
if (success) {
// User successfully stored in MySQL
// Now store the user in sqlite
//String uid = jObj.getString("uid");
String userId =jObj.getString("userId");
String token = jObj.getString("token");
db.addUser( token,userId);
//db.addUser(userId);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(
Name.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
//params.put("email", email);
// params.put("password", password);
params.put("deviceId", deviceId);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
private void launchAgeScreen() {
startActivity(new Intent(Name.this, Age.class));
finish();
}
}
SQLiteHandler
public class SQLiteHandler extends SQLiteOpenHelper {
private static final String TAG = SQLiteHandler.class.getSimpleName();
//public static final String KEY_USERID = ;
private static String DB_PATH = "/data/data/com.a98fit.neeraj.a98fit/databases/";
private SQLiteDatabase myDataBase;
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "android_api";
// Login table name
private static final String TABLE_USER = "user";
// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
public static final String KEY_TOKEN = "token";
public static final String KEY_USERID = "userId";
private static final String KEY_CREATED_AT = "created_at";
public SQLiteHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_USER + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_TOKEN + " TEXT,"
+ KEY_USERID + " TEXT" + ")";
db.execSQL(CREATE_LOGIN_TABLE);
Log.d(TAG, "Database tables created");
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* public void addUser(String name, String email, String uid, String created_at
* */
public void addUser(String token , String userId ) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
//values.put(KEY_NAME, name); // Name
values.put(KEY_TOKEN, token);
values.put(KEY_USERID, userId);
// Email
// Email
//values.put(KEY_CREATED_AT, created_at); // Created At
// Inserting Row
long id = db.insert(TABLE_USER, null, values);
db.close(); // Closing database connection
Log.d(TAG, "New user inserted into sqlite: " + id);
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + TABLE_USER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
//user.put("name", cursor.getString(1));
//user.put("email", cursor.getString(2));
user.put("token", cursor.getString(1));
user.put("userId", cursor.getString(2));
//user.put("created_at", cursor.getString(4));
}
cursor.close();
db.close();
// return user
Log.d(TAG, "Fetching user from Sqlite: " + user.toString());
return user;
}
public void openDataBase() throws SQLException {
//Open the database
String myPath = DB_PATH + DATABASE_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
/**
* Re crate database Delete all tables and create them again
* */
public void deleteUsers() {
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_USER, null, null);
db.close();
Log.d(TAG, "Deleted all user info from sqlite");
}
/* public String getYourData() {
{
final String TABLE_USER = "user";
String selectQuery = "SELECT * FROM " + TABLE_USER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String data = null;
if (cursor.moveToFirst()) {
do {
// get the data into array, or class variable
} while (cursor.moveToNext());
}
cursor.close();
return getYourData();
}
}*/
}
注册:
// Make Me Awesome Button Click event
btn_name_make.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = editTextEmailid.getText().toString();
String password = passwordentry.getText().toString();
SQLiteHandler myDatabaseHelper = new SQLiteHandler(Signup.this);
myDatabaseHelper.openDataBase();
HashMap<String, String> rs = myDatabaseHelper.getUserDetails();
myDatabaseHelper.close();
if (email.length() == 0) {
editTextEmailid.setError("Please Enter Email id");
} else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches())
{
editTextEmailid.setError("Please enter Valid Email id");
} else if (password.length() == 0) {
passwordentry.setError("Please Enter password");
} else if (password.length() < 6) {
passwordentry.setError("Please Enter minimum 6 character");
} else {
registerUser(token,userId,email,password);
}
}
});
设备ID,令牌:
private void registerUser(final String name, final String deviceId) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.NAME_REGISTER, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean success = jObj.getBoolean("success");
//boolean error = jObj.getBoolean("error");
if (success) {
// User successfully stored in MySQL
// Now store the user in sqlite
//String uid = jObj.getString("uid");
String userId =jObj.getString("userId");
String token = jObj.getString("token");
db.addUser( token,userId);
//db.addUser(userId);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(
Name.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
//params.put("email", email);
// params.put("password", password);
params.put("deviceId", deviceId);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
答案 0 :(得分:0)
要将数据传递给另一个Activity,您可以像这样实现
Intent intent = new Intent(Name.this, SignUP.class);
intent.putExtra("id", id);
intent.putExtra("token",token);
startActivity(intent);
接收 SignUp
int id,token // declare them in global
id = getIntent().getIntExtra("id",0);
token = getIntent().getIntExtra("token",0);