Show username value from Database to textview - java

I am new in Java, I want to show the username value from my Table in SQLite Database after successful login into my TextView in layout activity_home.xml
I don't know how to get username value with my code here.
The code for my TextView in my activity_home.xml layout's
<TextView
android:id="#+id/nameuser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="18dp"
android:layout_marginTop="32dp"/>
And here's the code :
DBHelper
public class DbHelper extends SQLiteOpenHelper {
public static final String TAG = DbHelper.class.getSimpleName();
public static final String DB_NAME = "myapp.db";
public static final int DB_VERSION = 1;
public static final String USER_TABLE = "users";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_USERNAME = "username";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_PASS = "password";
/*
create table users(
id integer primary key autoincrement,
email text,
password text);
*/
public static final String CREATE_TABLE_USERS = "CREATE TABLE " + USER_TABLE + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_USERNAME + " TEXT,"
+ COLUMN_EMAIL + " TEXT,"
+ COLUMN_PASS + " TEXT);";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USERS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + USER_TABLE);
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String username,String email,String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USERNAME, username);
values.put(COLUMN_EMAIL, email);
values.put(COLUMN_PASS, password);
long id = db.insert(USER_TABLE, null, values);
db.close();
Log.d(TAG, "user inserted" + id);
}
public boolean getUser(String username, String email, String pass){
//HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "select * from " + USER_TABLE + " where " +
COLUMN_USERNAME + " = " + "'"+username+"'" + " and " + COLUMN_PASS + " = " + "'"+pass+"'";
if(email != null)
selectQuery += "and " + COLUMN_EMAIL + " = " + "'"+email+"'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
return true;
}
cursor.close();
db.close();
return false;
}
}
HomeActivity
public class HomeActivity extends AppCompatActivity {
TextView nameuser, walletuser, mainmenus,
pagetitle, pagesubtitle;
Button btnguide;
Animation atg, atgtwo, atgthree;
ImageView imageView3;
SharedPreferences sharedpreferences;
Intent intent;
private Session session;
TextView btnLogout, btnDaftarBarang, btnTambah;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
session = new Session(this);
if(!session.loggedin()){
logout();
}
atg = AnimationUtils.loadAnimation(this, R.anim.atg);
atgtwo = AnimationUtils.loadAnimation(this, R.anim.atgtwo);
atgthree = AnimationUtils.loadAnimation(this, R.anim.atgthree);
nameuser = findViewById(R.id.nameuser);
walletuser = findViewById(R.id.walletuser);
btnDaftarBarang = (TextView) findViewById(R.id.btnDaftarBarang);
btnTambah = (TextView) findViewById(R.id.btnTambah);
btnLogout = (TextView) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logout();
}
});
imageView3 = findViewById(R.id.imageView3);
mainmenus = findViewById(R.id.mainmenus);
pagetitle = findViewById(R.id.pagetitle);
pagesubtitle = findViewById(R.id.pagesubtitle);
btnguide = findViewById(R.id.btnguide);
btnguide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent a = new Intent(HomeActivity.this,PackageAct.class);
startActivity(a);
}
});
// pass an animation
imageView3.startAnimation(atg);
pagetitle.startAnimation(atgtwo);
pagesubtitle.startAnimation(atgtwo);
btnguide.startAnimation(atgthree);
btnTambah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent tambah = new Intent(HomeActivity.this, CrudActivity.class);
startActivity(tambah);
}
});
btnDaftarBarang.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//start recordlist activity
startActivity(new Intent(HomeActivity.this, RecordListActivity.class));
}
});
}
private void logout(){
session.setLoggedin(false);
finish();
startActivity(new Intent(HomeActivity.this,LoginActivity.class));
}
}
Session.java
public class Session {
SharedPreferences prefs;
SharedPreferences.Editor editor;
Context ctx;
public Session(Context ctx){
this.ctx = ctx;
prefs = ctx.getSharedPreferences("myapp", Context.MODE_PRIVATE);
editor = prefs.edit();
}
public void setLoggedin(boolean logggedin){
editor.putBoolean("loggedInmode",logggedin);
editor.commit();
}
public boolean loggedin(){
return prefs.getBoolean("loggedInmode", false);
}
}
LoginActivity.java
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
private Button login;
private EditText etUsername, etPass;
private DbHelper db;
private Session session;
TextView RegisterDisini;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
db = new DbHelper(this);
session = new Session(this);
login = (Button)findViewById(R.id.btnLogin);
etUsername = (EditText)findViewById(R.id.etUsername);
etPass = (EditText)findViewById(R.id.etPass);
login.setOnClickListener(this);
RegisterDisini = (TextView) findViewById(R.id.RegisterDisini);
RegisterDisini.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent registerHere = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(registerHere);
}
});
if(session.loggedin()){
startActivity(new Intent(LoginActivity.this,HomeActivity.class));
finish();
}
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnLogin:
login();
break;
default:
}
}
private void login(){
String username = etUsername.getText().toString();
String pass = etPass.getText().toString();
if(db.getUser(username,null,pass)){
session.setLoggedin(true);
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
finish();
}else{
Toast.makeText(getApplicationContext(), "Wrong username/password",Toast.LENGTH_SHORT).show();
}
}
}

1. Add the line, as per the comment, as below to the LoginActivity
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
public static final String INTENTEXTRAKEY_LOGGEDINUSERNAME = "iek_loggedinusername"; //<<<<<<<<<< ADDED THIS LINE
private Button login;
2. In LoginActivity Change your login method as below :-
private void login(){
String username = etUsername.getText().toString();
String pass = etPass.getText().toString();
if(db.getUser(username,null,pass)){
session.setLoggedin(true);
//startActivity(new Intent(LoginActivity.this, HomeActivity.class)); <<<<<<<<< OLD CODE
Intent intent = new Intent(LoginActivity.this,HomeActivity.class); //<<<<<<<<<< NEW CODE
intent.putExtra(INTENTEXTRAKEY_LOGGEDINUSERNAME,username); //<<<<<<<<<< NEW CODE
startActivity(intent); //<<<<<<<<<< NEW CODE
finish();
}else{
Toast.makeText(getApplicationContext(), "Wrong username/password",Toast.LENGTH_SHORT).show();
}
}
3. In the HomeActivity add the line as commented :-
public class HomeActivity extends AppCompatActivity {
TextView nameuser, walletuser, mainmenus,
pagetitle, pagesubtitle;
Button btnguide;
Animation atg, atgtwo, atgthree;
ImageView imageView3;
SharedPreferences sharedpreferences;
Intent intent;
private Session session;
TextView btnLogout, btnDaftarBarang, btnTambah;
String loggedinusername; //<<<<<<<<<< ADDED
4. Also in HomeActivity add the line as commented :-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
session = new Session(this);
loggedinusername = this.getIntent().getStringExtra(LoginActivity.INTENTEXTRAKEY_LOGGEDINUSERNAME); //<<<<<<<<<<ADDED
5. Again also in HomeActivity add the line as commented :-
atg = AnimationUtils.loadAnimation(this, R.anim.atg);
atgtwo = AnimationUtils.loadAnimation(this, R.anim.atgtwo);
atgthree = AnimationUtils.loadAnimation(this, R.anim.atgthree);
nameuser = findViewById(R.id.nameuser);
nameuser.setText(loggedinusername); //<<<<<<<<<< ADDED
Explanation
adds a constant for a value that will be used to define the key part of a key/value pair.
Adds an Intent Extra that has the constant as defined in 1 as the key and the username as the value.
Adds a class variable, loggedinusername, for the username (optional as you could get the Inten Extra directly, but this allows the username to be utilised elsewhere if need be.)
sets the loggedinusername variable according to the Intent Extra
sets the TextView to display the username as per the loggedinusername variable.
This is the recommended way of passing data from one activity to the next. You can pass many Intent Extras of varying types.

After login success pass username to your HomeActivity using intent
private void login(){
String username = etUsername.getText().toString();
String pass = etPass.getText().toString();
if(db.getUser(username,null,pass)){
session.setLoggedin(true);
Intent intent=new Intent(this,HomeActivity.class);
intent.putExtra("username",username);
startActivity(intent);
finish();
}else{
Toast.makeText(getApplicationContext(), "Wrong username/password",Toast.LENGTH_SHORT).show();
}
}
// now get Username in HomeActivity like this
String username=getIntent().getStringExtra("username");
if(!TextUtils.isEmpty(username)){
// and set on your textview here
nameuser.setText(""+username);
}

Related

how to implement SHARED PREFERENCE (java, sql database LOGIN) [duplicate]

This question already has answers here:
How to use SharedPreferences in Android to store, fetch and edit values [closed]
(30 answers)
Closed 5 years ago.
hey guys so i got a login activity that checks username and password with server to authenticate users. i want to use sharedpermissions to store username and password so that the user wont have log in every time. i also want to create a login button.
i tried to implement it but itjust skips login acitivity and takes me to my second activity. i left some of sharedpermission codes as comments (//)
can anyone show/tell me the best i can do it?
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//String username = "";
//String password = "";
//SharedPreferences pre;
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final TextView tvRegisterLink = (TextView) findViewById(R.id.tvRegisterhere);
final Button bLogin = (Button) findViewById(R.id.bLogin);
if(TextUtils.isEmpty(etUsername.getText().toString())||TextUtils.isEmpty(etPassword.getText().toString())){
Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
LoginActivity.this.startActivity(intent);
} else {
Intent registerIntent = new Intent(LoginActivity.this, LoginActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
final String username1 = SharedPreferenceUtils.getUsername(this);
final String password1 = SharedPreferenceUtils.getPassword(this);
// pre = getSharedPreferences("pref",MODE_PRIVATE);
//if(pre.getBoolean("username",true) && pre.getBoolean("password",true)){
tvRegisterLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
});
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String name = jsonResponse.getString("name");
SharedPreferenceUtils.createSP(LoginActivity.this,username1,password1);
Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
intent.putExtra("name", name);
intent.putExtra("username", username);
LoginActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(username, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
}
}
public class UserAreaActivity extends AppCompatActivity {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
final TextView etusername = (TextView) findViewById(R.id.textView2);
final TextView etwelcome = (TextView) findViewById(R.id.textView);
final ImageButton red = (ImageButton) findViewById(R.id.imageButton);
final ImageButton messages = (ImageButton) findViewById(R.id.imageButton2);
final ImageButton blue = (ImageButton) findViewById(R.id.imageButton3);
final ImageButton ping = (ImageButton) findViewById(R.id.imageButton4);
final TextView etuname = (TextView) findViewById(R.id.textView3);
final Button Logout = (Button) findViewById(R.id.logout);
//String Name = SharedPreferenceUtils.getName(this);
//etwelcome.setText(Name);
red.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(UserAreaActivity.this, Report.class);
UserAreaActivity.this.startActivity(registerIntent);
}
});
messages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(UserAreaActivity.this, Messages.class);
UserAreaActivity.this.startActivity(registerIntent);
}
});
Logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isClear = SharedPreferenceUtils.clearSP(UserAreaActivity.this);
if(isClear){
Intent registerIntent = new Intent(UserAreaActivity.this, LoginActivity.class);
UserAreaActivity.this.startActivity(registerIntent);
}
}
});
Intent intent = getIntent();
String name = intent.getStringExtra("name");
String username = intent.getStringExtra("username");
String message = "Welcome " + name;
etwelcome.setText(message);
etusername.setText(username);
//Intent in = new Intent(getApplicationContext(), Messages.class);
//in.putExtra("username", username);
//UserAreaActivity.this.startActivity(in);
}
}
You can use SharedPreferences in your code .
Try this .
public class SharedPreferenceUtils {
private static final String SP_NAME = "sp";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
// create
public static boolean createSP(Context context, String username, String password) {
SharedPreferences.Editor editor = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE).edit();
editor.putString(USERNAME, username);
editor.putString(PASSWORD, password);
return editor.commit();
}
// clear
public static boolean clearSP(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
return editor.clear().commit();
}
// get access info
public static String getUsername(Context context) {
SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sp.getString(USERNAME, "");
}
// get branch info
public static String getPassword(Context context) {
SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sp.getString(PASSWORD, "");
}
}
Use in LoginActivity
SharedPreferenceUtils.createSP(this,username,password);
And use in other Activity
String username = SharedPreferenceUtils.getUsername(this);
String password = SharedPreferenceUtils.getPassword(this);
Edit
if (success) {
String name = jsonResponse.getString("name");
SharedPreferenceUtils.createSP(this, username, password);
}
Edit
private EditText etUsername, etPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
String username = SharedPreferenceUtils.getUsername(this);
String password = SharedPreferenceUtils.getPassword(this);
etUsername.setText(username);
etPassword.setText(password);
}
Edit
if(TextUtils.isEmpty(etUsername.getText().toString())||TextUtils.isEmpty(etPassword.getText().toString())){
Intent intent = new Intent(LoginActivity.this, A.class);
LoginActivity.this.startActivity(intent);
} else {
Intent registerIntent = new Intent(LoginActivity.this, B.class);
LoginActivity.this.startActivity(intent);
}
Edit
boolean isClear = SharedPreferenceUtils.clearSP(UserAreaActivity.this);
if(isClear){
Intent registerIntent = new Intent(UserAreaActivity.this, LoginActivity.class);
UserAreaActivity.this.startActivity(registerIntent);
}

How to restart Handler after changing data value?

Good morning StackOverFlow i'm having some issues with Handler i'm trying to start in the MainActivity my Client.java after 50 seconds and also send the message and stop the client and that's work but i have to reopen the connection on every change of ip_txt or term_txt in settings.java
(data is saved from a EditText to DB by clicking on a button )
here is my MainActivity :
public class MainActivity extends AppCompatActivity {
Server server;
Client client;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
new ConnectTask().execute("");
if (client != null) {
client.sendMessage("IP#" + ipp + " " + "N#" + trm);
}
if (client != null) {
client.stopClient();
}
}
};
settings Settings;
public static TextView terminale, indr, msg;
TextView log;
String ipp,trm;
DataBaseHandler myDB;
allert Allert;
SharedPreferences prefs;
String s1 = "GAB Tamagnini SRL © 2017 \n" +
"Via Beniamino Disraeli, 17,\n" +
"42124 Reggio Emilia \n" +
"Telefono: 0522 / 38 32 22 \n" +
"Fax: 0522 / 38 32 72 \n" +
"Partita IVA, Codice Fiscale \n" +
"Reg. Impr. di RE 00168780351 \n" +
"Cap. soc. € 50.000,00 i.v. \n" + "" +
"REA n. RE-107440 \n" +
"presso C.C.I.A.A. di Reggio Emilia";
ImageButton settings, helps, allerts, home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Utils.darkenStatusBar(this, R.color.colorAccent);
server = new Server(this);
myDB = DataBaseHandler.getInstance(this);
msg = (TextView) findViewById(R.id.msg);
log = (TextView) findViewById(R.id.log_avviso);
settings = (ImageButton) findViewById(R.id.impo);
helps = (ImageButton) findViewById(R.id.aiut);
allerts = (ImageButton) findViewById(R.id.msge);
home = (ImageButton) findViewById(R.id.gab);
terminale = (TextView) findViewById(R.id.terminal);
indr = (TextView) findViewById(R.id.indr);
final Cursor cursor = myDB.fetchData();
if (cursor.moveToFirst()) {
do {
indr.setText(cursor.getString(1));
terminale.setText(cursor.getString(2));
Client.SERVER_IP = cursor.getString(1);
trm = cursor.getString(2);
} while (cursor.moveToNext());
}
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
ipp = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
handler.postDelayed(runnable,5000);
cursor.close();
server.Parti();
home.setOnClickListener(new View.OnClickListener() {
int counter = 0;
#Override
public void onClick(View view) {
counter++;
if (counter == 10) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setMessage(s1);
builder.show();
counter = 0;
}
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent impostazioni = new Intent(getApplicationContext(), settingsLogin.class);
startActivity(impostazioni);
}
});
helps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent pgHelp = new Intent(getApplicationContext(), help.class);
startActivity(pgHelp);
}
});
allerts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Server.count = 0;
SharedPreferences prefs = getSharedPreferences("MY_DATA", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.apply();
msg.setVisibility(View.INVISIBLE);
Intent pgAlert = new Intent(getApplicationContext(), allert.class);
startActivity(pgAlert);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
server.onDestroy();
}
public class ConnectTask extends AsyncTask<String, String, Client> {
#Override
protected Client doInBackground(String... message) {
client = new Client(new Client.OnMessageReceived() {
#Override
public void messageReceived(String message) {
publishProgress(message);
}
});
client.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d("test", "response " + values[0]);
}
}
}
Here is my settings.java:
public class settings extends AppCompatActivity {
TextView indr;
Client client;
EditText ip_txt,term_txt;
ImageButton home;
Button save;
DataBaseHandler myDB;
MainActivity activity;
String ipp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDB = DataBaseHandler.getInstance(this);
setContentView(R.layout.activity_settings);
Utils.darkenStatusBar(this, R.color.colorAccent);
home = (ImageButton) findViewById(R.id.stgbtn);
indr = (TextView) findViewById(R.id.ipp);
ip_txt = (EditText) findViewById(R.id.ip);
term_txt = (EditText) findViewById(R.id.nTermin);
save = (Button) findViewById(R.id.save);
Cursor cursor = myDB.fetchData();
if(cursor.moveToFirst()){
do {
ip_txt.setText(cursor.getString(1));
term_txt.setText(cursor.getString(2));
}while(cursor.moveToNext());
}
cursor.close();
AddData();
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
ipp = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
indr.setText(ipp);
}
public void AddData() {
save.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
myDB.insertData(ip_txt.getText().toString(),
term_txt.getText().toString());
MainActivity.indr.setText(ip_txt.getText().toString());
MainActivity.terminale.setText(term_txt.getText().toString());
Client.SERVER_IP = ip_txt.getText().toString();
finish();
}
}
);
}
}
( If I did not explain it i want to start the handler on the start of the app and also to start it again or immediatly after i change the data in EditText ip_txt or in EditText term_txt )
I would create Variables to store the handler and the runnable, then when you want to restart it just use:
yourHandler.removeCallback(yourRunnable);
yourHandler.postDelayed(yourRunnable,time);
and to start it, just do it as you did,
yourHandler.postDelayed(yourRunnable,5000);
Hope is what you are looking for.
How to create them:
public class ClassName{
Handler yourHandler = new Handler();
Runnable yourRunnable = new Runnable(){
#Override
public void run() {
//yourCode
}
};
// Rest of class code
}
Is just same as you did in your code but in a variable.

How to pass User_Id to every activity in android?

I am trying to build an android application. After logged in to the application I want to use User_Id for all activities for getting unique data based on that user_id. How it is possible? And what changes i want to make in this code to get user_id in all activities?
LoginActivity.java
public class LoginActivityMerchant extends AppCompatActivity implements View.OnClickListener {
//Defining views
private AutoCompleteTextView ACTUser;
private EditText etPassword;
private Button buttonLogin;
private TextView linkToRegister;
private ProgressDialog loading;
public static final String KEY_firstName = "First_Name";
public static final String KEY_LastName = "Last_Name";
public static final String KEY_Mob = "Mobile";
public static final String KEY_ShopName = "Shop_Name";
public static final String KEY_Location = "Location";
public static final String KEY_Radius = "UserId";
public static final String JSON_ARRAY = "result";
public static final String KEY_UserName = "User_Name";
public static final String KEY_Password = "Password";
public TextView test;
//boolean variable to check user is logged in or not
//initially it is false
private boolean loggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_activity_merchant);
//Initializing views
ACTUser = (AutoCompleteTextView) findViewById(R.id.email);
etPassword = (EditText) findViewById(R.id.password);
buttonLogin = (Button) findViewById(R.id.email_sign_in_button);
linkToRegister = (TextView) findViewById(R.id.Reg_TextView);
test=(TextView)findViewById(R.id.test);
//Adding click listener
buttonLogin.setOnClickListener(this);
linkToRegister.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(config.LOGGEDIN_SHARED_PREF, false);
//If we will get true
if(loggedIn){
//We will start the Profile Activity
//Config.KEY_USERNAME=Config.USERNAME_SHARED_PREF;
SharedPreferences sharedPreferences1 = getSharedPreferences(config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String username = sharedPreferences1.getString(config.SHARED_PREF_NAME,"Not Available");
setInfos(username);
Intent intent = new Intent(LoginActivityMerchant.this, MainActivity.class);
startActivity(intent);
}
}
private void login(){
//Getting values from edit texts
final String user = ACTUser.getText().toString().trim();
final String password = etPassword.getText().toString().trim();
if(user.isEmpty()||password.isEmpty())
{
Toast.makeText(LoginActivityMerchant.this, "Please fill all the fields", Toast.LENGTH_LONG).show();
}
//Creating a string request
else{
StringRequest stringRequest = new StringRequest(Request.Method.POST, config.LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//test.setText(response);
//If we are getting success from server
if(response.contains("success")){
//Creating a shared preference
// Toast.makeText(LoginActivityMerchant.this, "Success", Toast.LENGTH_LONG).show();
SharedPreferences sharedPreferences = LoginActivityMerchant.this.getSharedPreferences(config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences.edit();
//Adding values to editor
editor.putBoolean(config.LOGGEDIN_SHARED_PREF, true);
editor.putString(config.SHARED_PREF_NAME, user);
config.KEY_USERNAME = user;
//Saving values to editor
editor.commit();
//Starting profile activity
//Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
setInfos(user);
Intent intent = new Intent(LoginActivityMerchant.this, MainActivity.class);
startActivity(intent);
}else{
//If the server response is not success
//Displaying an error message on toast
Toast.makeText(LoginActivityMerchant.this, "Invalid username or password", Toast.LENGTH_LONG).show();
ACTUser.setText(user);
etPassword.setText(password);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//You can handle error here if you want
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
//Adding parameters to request
params.put(KEY_UserName, user);
params.put(KEY_Password, password);
//test.setText(password);
//returning parameter
return params;
}
};
//Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}}
#Override
public void onClick(View v) {
//Calling the login function
if(v==buttonLogin){
login();
}
if(v==linkToRegister){
Intent intent = new Intent(LoginActivityMerchant.this, Registration.class);
startActivity(intent);
}
}
public void setInfos(String username){
String url = config.LOGIN_URL+username;
loading = ProgressDialog.show(this, " Please wait...", "Fetching...", false, false);
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivityMerchant.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
String FirstName="";
String LastName="";
String UserName="";
String Mobile="";
String Location="";
String Radius="";
// String stringid="";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(JSON_ARRAY);
JSONObject userData = result.getJSONObject(0);
FirstName = userData.getString(KEY_firstName);
UserName = userData.getString(KEY_UserName);
LastName = userData.getString(KEY_LastName);
Mobile = userData.getString(KEY_Mob);
Location = userData.getString(KEY_Location);
//stringid=userData.getString(KEY_USERID);
} catch (JSONException e) {
e.printStackTrace();
}
config.KEY_NAME=FirstName + " "+LastName;
config.KEY_USERNAME=UserName;
}
}
loginold.php
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$username = $_POST['User_Name'];
$password = $_POST['Password'];
//Creating sql query
$sql = "SELECT * FROM User_Profile WHERE User_Name='$username' AND Password='$password'";
//importing dbConnect.php script
require_once('include/dbConnect.php');
//executing query
$result = mysqli_query($con,$sql);
//fetching result
$check = mysqli_fetch_array($result);
//if we got some result
if(isset($check)){
//displaying success
echo "success";
}else{
//displaying failure
echo "failure";
}
mysqli_close($con);
}
else
{echo "error";}
You can use SharedPreference :
public class SaveId {
static final String ID = "ID";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setId(Context ctx, int value) {
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
editor.putInt(ID, value);
editor.commit();
}
public static String getId(Context ctx) {
return getSharedPreferences(ctx).getString(ID, "");
}
}
When you want to set the id call SaveId.setId(yourID); and when you want to get the id call SaveId.getId();
Instead of read and write to SharedPreferences I would prefer a more efficient way to store a simple data like an ID.
There are two ways:
If you are using an MVP approach, you could delegate the setter and getter of the ID to your central manager, instead go for option 2
Set the id in your custom application and get it through it.
You have to override default application and set it in the manifest.
public class MyApplication extends Application {
private Integer id;
public void setId(int id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
In your activities you can get it through:
((MyApplication) getApplication()).getId();

How can i show the database data and show the login details in another Activity?

I want to print the whole database data so that I can check if my SQLite code is working or not.
I am fetching the user login details from login.java and want to show that at loggedin.java
login.java
public class login extends AppCompatActivity {
EditText e1, e2;
ImageView i1, i2;
Retrofit retrofit;
TextView t;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText) findViewById(R.id.editText);
if( e1.getText().toString().length() == 0 ){
e1.setError( "email is required" );}
e2 = (EditText) findViewById(R.id.editText2);
if( e2.getText().toString().length() == 0 ){
e2.setError( "password is required" );}
i1 = (ImageView) findViewById(R.id.email);
i2 = (ImageView) findViewById(R.id.password);
Button b1= (Button) findViewById(R.id.button);
t=(TextView)findViewById(R.id.textView5);
retrofit = new Retrofit.Builder()
.baseUrl("http://funnytadka.com:8060")
.addConverterFactory(GsonConverterFactory.create())
.build();
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
db.insertEntry(e1.getText().toString(),e2.getText().toString());
loginApi thisapi = retrofit.create(loginApi.class);
Call<Pvideos> call = thisapi.loadData(e1.getText().toString(), e2.getText().toString());
call.enqueue(new Callback<Pvideos>() {
#Override
public void onResponse(Response<Pvideos> response, Retrofit retrofit) {
if (response.isSuccess())
{
Intent intent = new Intent(login.this, loggedin.class);
startActivity(intent);
}
else
{
Toast.makeText(getApplicationContext(),"login unsuccessful",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Throwable t) {
Toast.makeText(getApplicationContext(),"login unsuccessful",Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
loggedin.java
public class loggedin extends AppCompatActivity
{
View view;
// public static final String DEFAULT = "N/A";
TextView t1, t2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accinfo);
t1 = (TextView) findViewById(R.id.textView3);
t2 = (TextView) findViewById(R.id.textView4);
}
databasehandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DICTIONARY_TABLE_NAME = "logindb";
static SQLiteDatabase db;
private static final String DICTIONARY_TABLE_CREATE =
"CREATE TABLE " + DICTIONARY_TABLE_NAME + "(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,email text,password text);";
DatabaseHandler(Context context) {
super(context, "logindb", null, DATABASE_VERSION);
db = getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DICTIONARY_TABLE_CREATE);
db = this.db;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void closeDb() {
db.close();
;
}
public static boolean insertEntry(String email, String password) {
ContentValues cv = new ContentValues();
cv.put("email", email);
cv.put("password", password);
Log.e("email", email);
Log.e("pass", password);
long rowsEffected = db.insert(DICTIONARY_TABLE_NAME, null, cv);
return rowsEffected > 0 ? true : false;
}}
Write a Method to retrieve data from DB table in
databasehandler.java
public Cursor getUserDetails( ) throws SQLException {
logger.debug("MYDATABASE_TABLE :- "+MYDATABASE_TABLE );
String q = "SELECT * FROM "+MYDATABASE_TABLE+" ;";
logger.debug("query :- "+q);
Cursor mCursor = db.rawQuery(q, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
db.close();
return mCursor;
}
public DBTariffHandler openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
db = sqLiteHelper.getReadableDatabase();
return this;
}
loggedin.java
databasehandler handler = new databasehandler(context);
handler.openToRead();
Cursor cursor_next = handler.getUserDetails();
handler.close() ;
if(cursor_next != null && cursor_next.moveToFirst())
{
cursor_next.getColumnIndex(databasehandler.KEY_USERNAME)
//..ETC
}

responsed data not displayed

After Login, I get back a JSON response from the server with the real name of the user. But it won't be displayed in TextView txtName. What is wrong with the code?
MainActivity.java:
public class MainActivity extends Activity {
private TextView txtName;
private TextView txtEmail;
private Button btnLogout;
private Button btnNeu;
private Button btnAlle;
private SQLiteHandler db;
private SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
txtName = (TextView) findViewById(R.id.name);
txtEmail = (TextView) findViewById(R.id.email);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnNeu = (Button) findViewById(R.id.neu);
btnAlle = (Button) findViewById(R.id.alle);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
String email = user.get("email");
// Displaying the user details on the screen
txtName.setText(name);
txtEmail.setText(email);
...
}
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
SQLiteHandler.java:
public class SQLiteHandler extends SQLiteOpenHelper {
private static final String TAG = SQLiteHandler.class.getSimpleName();
// 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_LOGIN = "login";
// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";
public 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_LOGIN + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE," + KEY_UID + " TEXT,"
+ KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_LOGIN_TABLE);
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_LOGIN);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String name, String email, String uid, String created_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Name
values.put(KEY_EMAIL, email); // Email
values.put(KEY_UID, uid); // Email
values.put(KEY_CREATED_AT, created_at); // Created At
// Inserting Row
long id = db.insert(TABLE_LOGIN, 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_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("uid", cursor.getString(3));
user.put("created_at", cursor.getString(4));
}
cursor.close();
db.close();
// return user
Log.d(TAG, "Fetching user from Sqlite: " + user.toString());
return user;
}
/**
* Getting user login status return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
/**
* Re crate database Delete all tables and create them again
* */
public void deleteUsers() {
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_LOGIN, null, null);
db.close();
Log.d(TAG, "Deleted all user info from sqlite");
}
}
LoginActivity.java:
public class LoginActivity extends Activity {
// LogCat tag
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(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(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Bitte Benutzername und Passwort eintragen!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Login ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", email);
params.put("password", password);
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();
}
}
Finally I found the code i have forgotten to insert in LoginActivity.java:
Now it is working
public class LoginActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(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(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Bitte Benutzername und Passwort eintragen!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Login ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", email);
params.put("password", password);
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();
}
}

Categories

Resources