How to Access log in credentials in another activity - android

Here iam working with web services i need to access username and password variabes from my MainActivity to MainActivity2 below is the code.
public class MainActivity extends AppCompatActivity {
String username ;
String password;
public void doLgin(View view) {
if(Build.VERSION.SDK_INT >= 10){
StrictMode.ThreadPolicy policy = StrictMode.ThreadPolicy.LAX;
StrictMode.setThreadPolicy(policy);
}
username = ((EditText)findViewById(R.id.editTextUsername)).getText().toString();
password = ((EditText)findViewById(R.id.editTextPassword)).getText().toString();
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://182.18.163.39/train/m/login.php?username=" + username + "&key=" + password);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(responseString);
JSONObject jsonObj = new JSONObject();
jsonObj.put("Result", jsonarray);
String error = jsonObj.getJSONArray("Result").getJSONObject(0).toString();
String errormsg = "{\"Error\":\"Problem with authentication,Please login.\"}";
if (error.equalsIgnoreCase(errormsg)) {
Toast.makeText(getApplicationContext(), "Invalid username or password", Toast.LENGTH_SHORT).show();
} else {
// Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putExtra("Username",username);
intent.putExtra("Password",password);
startActivity(intent);
}
}
And In my MainActivity2 class i created an object for MainActivity but it returns null values
.

You should store it on a static global class, say
public static class Credentials{
public static String USERNAME = "myUsername";
public static String PASSWORD = "myPassword";
}
Then you can access it anywhere on your project using:
Credentials.USERNAME = "setyourusername";
Credntials.PASSWORD = "setYourPassword;
But I wouldn't recommend this kind of implementation because it is really not secure, but as for an answer for your question, this probably is the approach you'll need.
Edit:
If the information should only be shared between that two activities, then #Faysal Ahmed 's answer is the way to go.
After this line on your first activity:
username = ((EditText)findViewById(R.id.editTextUsername)).getText().toString();
password =((EditText)findViewById(R.id.editTextPassword)).getText().toString();
you can assign it directly to the static credentials class:
Credentials.USERNAME = username;
Credntials.PASSWORD = password;
then you can access it on your second activity the same way by calling Credentials.USERNAME and Credentials.PASSWORD

If you want to get the value from MainActivity then need to pass both values using putExtra.
//Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainActivity.this, Main2Activity.class);
i.putExtra("username",username);
i.putExtra("password",password);
startActivity(i);
And from Main2Activity class you can get the value like this. Use this lines under onCreate method.
String user = getIntent.getStringExtra("username");
String pass = getIntent.getStringExtra("password");
No need to use MainActivity m = new MainActivity(); this line.
UPDATE:
public class Main2Activity extends AppCompatActivity {
String user;
String pass;
String JSON_URL = "http://182.18.163.39/m/list.php?username=admin&key=admin";
ListView listView;
java.util.List<List> tktList;
String link;
Button logoutbt;
Button ubt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
// Get value from intent that passed from previous Activity
user = getIntent.getStringExtra("username");
pass = getIntent.getStringExtra("password");
// Now you can use this two variable in any place.
logoutbt = (Button)findViewById(R.id.lbt);
logoutbt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences SM = getSharedPreferences("userrecord", 0);
SharedPreferences.Editor edit = SM.edit();
edit.putBoolean("username", false);
edit.commit();
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
//initializing listview and hero list
listView = (ListView) findViewById(R.id.listView);
tktList = new ArrayList<>();
//this method will fetch and parse the data
loadHeroList();
}
private void loadHeroList() {
//getting the progressbar
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
//making the progressbar visible
progressBar.setVisibility(View.VISIBLE);
//creating a string request to send request to the url
StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("Sno");
String Tktid = jsonobject.getString("TKTID");
link = jsonobject.getString("Link");
List list = new List(jsonobject.getString("Sno"), jsonobject.getString("TKTID"),jsonobject.getString("Link"));
tktList.add(list);
Log.i("website content", name);
Log.i("website content", Tktid);
Log.i("website content", link);
}
//creating custom adapter object
ListViewAdapter adapter = new ListViewAdapter(tktList, getApplicationContext());
//adding the adapter to listview
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
com.android.volley.RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(stringRequest);
}
}

You can do something like this:
1) First, create a POJO class like this:
public class Info {
static Info info;
private String userName;
private String password;
public static Info getInstance() {
if (info == null) {
info = new Info();
}
return info;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName= userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password= password;
}
}
2) and then set your username and password like this:
Info.getInstance.setUserName("username");
Info.getInstance.setPassword("password");
3) and then get it like this in your other activities:
Info.getInstance.getUserName();
Info.getInstance.getPassword();
You can also pass your values to a intent and get those values in other activity.

Using the Intent you can pass the credentials through like this:
Intent i = new Intent(this, ActivityYouArePassingInformationTo.class);
i.putExtra("username", userNameValue);
i.putExtra("password", passwordValue);
Then in the activity that you want to receive the information you can get it through this way:
String userNameVal = intent.getStringExtra("username");
String passwordVal = intent.getStringExtra("password");
Now the variables in the MainActivity will have the username and password stored in a variable. Hope this helps :)

If username and password are only used in second activity only then you can pass these values in Intent.
In MainActivity
Intent i = new Intent(MainActivity.this, Main2Activity.class);
i.putExtra("user_name", userName);
i.putExtra("password", password);
startActivity(i);
in Main2Activity onCreate() after setContentView() you can read data like this
Intent i = getIntent();
user = i.getStringExtra("user_name");
pass = i.getStringExtra("password");
Other ways are to save username and password in SharedPreferences in MainActivity and read Main2Activity. This might be useful when you want to auto fill previous username and password on next app launch.

There are many ways to solve this problem.
You can use below code in MainActivity class.
Intent i = new Intent(MainActivity.this,Main2Activity.class);
i.putExtra("UserName",username);
i.putExtra("Password",password);
startActivity(i);
And in Main2Activity, you will get by using below code,
Intent i = getIntent();
String userName = i.getString("UserName");
String password = i.getString("Password");
Use below snippet code in MainActivity after you will get userName and
passsword.
SharedPreferences
pref=getApplicationContext().getSharedPreferences("MyPref",Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("UserName", username);
editor.putString("Password", password);
editor.commit();
And after this, you will get these values in Main2Activity by below code.
SharedPreferences
pref=getApplicationContext().getSharedPreferences("MyPref",Context.MODE_PRIVATE);
String userName = pref.getString("UserName", null);
String password = pref.getString("Password", null);
You can use static UserName and Password and get static value in other
Activity. like,
In MainActivity
public static String userName, password;
and set value after getting userName and password
userName = "abc"
password = "***"
Now In Main2Activity you will get these values directly by class name
String userName = MainActivity.userName;
String password = MainActivity.password;
You can use setter and getter method. In MainActivity, When you will find the
values you have to set userName and password.
Now, In Main2Activity you will get those values(UserName and Password) by
getter methods

Related

Onetime login is not working and second time also showing LoginActivity in android

Hi in the below code I was implemented ontime login feature but it is not working with below code.If login is successful then it will redirecting to MainActivity.Next time want to skip login page directly it should show main activity.
SplashActivity.java:
final boolean needLogin = getIntent().getBooleanExtra("need login extra", true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
if(!needLogin) {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
finish();
}else {
Intent i = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
}
},
Once the login is successfull it will redirect to MAninactivity.java.Entire app I am using session.
LoginActivity.java:
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
LoginAndFetchModules loginAndFetchModules = response.body();
String success = loginAndFetchModules.getSuccess();
if (success.equals("true")) {
Results results = loginAndFetchModules.getResult();
//parse login details
GetLoginListDetails loginDetails = results.getLogin();
String userId = loginDetails.getUserid();
String sessionId = loginDetails.getSession();
String firstname = loginDetails.getFirst_name();
String lastname = loginDetails.getLast_name();
String mobile = loginDetails.getMobile();
String role = loginDetails.getRole();
String reportto = loginDetails.getReportto();
//parse modules
ArrayList<LoginListForModules> modules = results.getModules();
//parse module information
for (LoginListForModules module : modules) {
module_id = module.getId();
String name = module.getName();
String isEntity = module.getIsEntity();
String label = module.getLabel();
String singular = module.getSingular();
}
if (username.equals(username1.getText().toString()) && password.equals(password1.getText().toString())) {
// fetchUserJSON(sessionId,username);
Toast.makeText(getApplicationContext(), "Login Successfully", Toast.LENGTH_LONG).show();
i = new Intent(LoginActivity.this, MainActivity.class);
// loader.setVisibility(View.GONE);
progressDialog.dismiss();
// llProgressBar.setVisibility(View.GONE);
i.putExtra("sessionId", sessionId);
i.putExtra("module_id", module_id);
i.putExtra("username", username);
i.putExtra("firstname", firstname);
i.putExtra("lastname", lastname);
i.putExtra("mobile", mobile);
i.putExtra("role", role);
i.putExtra("reportto", reportto);
startActivity(i);
finish();
} else {
Toast.makeText(getApplicationContext(), "Invalid Username and Password", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "Invalid Username and Password", Toast.LENGTH_LONG).show();
}
}
You can use SharedPreferences.
A SharedPreferences object points to a file containing key-value
pairs and provides simple methods to read and write them.
DEMO CODE
public class SharedPreferenceClass
{
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "Test";
public static final String KEY_SET_LOGIN_STATUS= "KEY_SET_LOGIN_STATUS";
public SharedPreferenceClass(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, 0);
editor = pref.edit();
}
public void setLoginStatus(String status)
{
editor.remove(KEY_SET_LOGIN_STATUS);
editor.putString(KEY_SET_LOGIN_STATUS, status);
editor.commit();
}
public String getLoginStatus()
{
String status= pref.getString(KEY_SET_LOGIN_STATUS, "");
return status;
}
}
Now you can store login status ( setLoginStatus("Login")) when ever login success And check your login status getLoginStatus(). If return "Login" then return to your desire activity.

How to use a value across all activities?

For example: I have a String value "A". and I have activities : activity_a, activity_b, activity_C.
Can I use value "A" across all activities? If yes how to achieve this?
And not through Intent or send data to another activity.
I am sorry that I am not fluent in English.
I moved a token value in login activity to main activity.
I used Intent and move token login activity. this is my login activity code.
StringRequest stringRequest = new StringRequest(Request.Method.POST, serverURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONArray jsonArray = new JSONArray(response);
JSONObject json_code = jsonArray.getJSONObject(0);
JSONObject json_token = jsonArray.getJSONObject(1);
String code = json_code.getString("code");
String token = json_token.getString("token");
Intent myIntent = new Intent(loginActivity.this, mainActivity.class);
myIntent.putExtra("token", token);
startActivity(myIntent);
finish();
overridePendingTransition(R.xml.madefadein, R.xml.splashfadeout);
}catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
switch(error.networkResponse.statusCode)
{
case 409:
Toast.makeText(loginActivity.this, error.networkResponse.toString(), Toast.LENGTH_SHORT).show();
break;
}
}
but in main Activity, I tried to declare static like this.
Intent i = new Intent(getIntent());
public static final String token = i.getStringExtra("token");
but it doesn't work.
1.just declare your String as public static String strTmp="A"; in your activity than you can use any where in your project
like this
String strTmp = yourActivity.str;
2. create a new class like this
public class ServiceClass {
public static String strTmp="Data";
}
now you can access this string anywhere in your project like this
String mystr= ServiceClass.strTmp;
3.if you want use hard String than store your string in res/values/string.xml like this
<resources>
<string name="app_name">PatternView</string>
</resources>
than you can use like this
String str = getResources().getString(R.string.app_name);
4. save it in SharedPreferences like this
code for save data in SharedPreferences like this
SharedPreferences myPref;
SharedPreferences.Editor prefEditor;
myPref = getSharedPreferences("TOKENNAME", MODE_PRIVATE);
prefEditor = myPref.edit();
prefEditor.putString("TOKEN", "your token");
prefEditor.apply();
code for retrieve data from SharedPreferences
SharedPreferences myPref;
myPref = getSharedPreferences("TOKENNAME",
MODE_PRIVATE);
String name = myPref.getString("TOKEN", "");

Nothing Being Passed via $_Post to Php from login code?

I've been working on a log-in/register for an android app and have the register up and running but the log-in doesnt seem to be passing anything over to the php script via post like the register was? , I'm pretty sure the php script is fully functional as I've tested it with Postman, If anyone could point me in the right direction it would be much appreciated, Cheers
public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL="http://192.168.0.17/WebD/HASSAPP/login.php";
private Map<String, String> params;
public LoginRequest(String username,String password , Response.Listener<String> listener) {
super(Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("username",username);
params.put("password",password);
}
#Override
public Map<String,String> getParams() {
return params;
}
}
public class Login extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);//Edit to change title text
setSupportActionBar(toolbar);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bLogin = (Button) findViewById(R.id.bLogin);
bLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
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 businessname = jsonResponse.getString("businessname");
String username = jsonResponse.getString("username");
Intent intent = new Intent(Login.this, MainActivity.class);
intent.putExtra("businessname", businessname);
intent.putExtra("username", username);
Login.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Login.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(Login.this);
queue.add(loginrequest);
}
});
}
I cannot understand how me sending via Post on my register is working fine but On Log-in it's non responsive , Log-in button does nothing , not even send me to mainactivity like the intent's purpose,
Kind Regards,
Andrew
This overriden method should be protected. You have it as public.
#Override
protected Map<String,String> getParams() {
return params;
}
Also, for debugging purposes, you might want to override the error listener as well.

My Data is Not Stored in Database

I am making a simple register app where user sign up and data store in the My Mydatabase like usename, name, age, passsword
I already created database table in phpMyAdmin and I uploaded Register.php file into my server I check Register.php file their is no error it works great (I use postman app that act as app to send sign up details to the server it actually work my database is storing the values send by the postman app but when I use android app and sign up data is not storing in my database)
They should be some mistake in my code but error is not showing I take entire day to solve the problem not still not found.
I am referring to this tutorial https://www.youtube.com/watch?v=T7Z4GVFaT4A&list=PLe60o7ed8E-TztoF2K3y4VdDgT6APZ0ka&index=4
I am using volley networking library in my gradle file
Here Register Activity where user enter username, name, age, password is store and send back to another activity to send server
It is linked with xml file whre user can sign up
public class RegisterActivity extends AppCompatActivity {
EditText username , name , pass , age;
Button r_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
username = (EditText)findViewById(R.id.username_et);
name = (EditText)findViewById(R.id.name_et);
pass = (EditText)findViewById(R.id.pass_et);
age = (EditText)findViewById(R.id.age_et);
r_button = (Button)findViewById(R.id.register_button);
r_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String usname = username.getText().toString();
String nam = name.getText().toString();
String password = pass.getText().toString();
int ages = Integer.parseInt(age.getText().toString());
Response.Listener<String> responselistner = new Response.Listener<String>(){
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if(success)
{
Intent intent = new Intent(RegisterActivity.this,LoginActivity.class);
startActivity(intent);
//after successfull sign up it redirect to login page
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Registration failed")
.setNegativeButton("retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(nam, usname,ages,password , responselistner);
RequestQueue requestQueue = Volley.newRequestQueue(RegisterActivity.this);
requestQueue.add(registerRequest);
}
});
}
}
Here is my class RegisterRequest
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL ="http://fgeeges.esy.es/Register.php";
private Map<String, String> params;
public RegisterRequest(String name , String username , int age , String password , Response.Listener<String> listener)
{
super(Method.POST, REGISTER_REQUEST_URL , listener ,null);
params = new HashMap<>();
params.put("name ",name);
params.put("username",username);
params.put("age" ,age+"");
params.put("password",password);
}
}
Add
#Override
public Map<String, String> getParams(){
return params;
}
in the RegisterRequest Class.

Getting volley response is null on first call

This my class for network calls. Here executing a method networkCallByVolley then saving the information on shared preferences.
public class NetworkCall extends Activity {
Context context;
String res = "something";
SharedPreferences userDetails;
ArrayList<String> type = new ArrayList<String>();
ArrayList<String> value = new ArrayList<String>();
public NetworkCall(Context context){
this.context = context;
}
public void networkCallByVolley(final ArrayList<String> type, final ArrayList<String> value){
this.type = type;
this.value = value;
Log.i("type", type.toString());
Log.i("value", value.toString());
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest myReq = new StringRequest(Method.POST,
"http://My URL",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("rrrrr", response);
res = response;
userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);
Editor edit = userDetails.edit();
edit.clear();
edit.putString("response", response);
edit.commit();
//Log.i("rrrrr", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
//for(int i = 0; i<= params1.size(); i++)
for(int i =0 ; i< type.size(); i++){
params.put(type.get(i), value.get(i));
//params.put("password", "aaaaaa");
Log.i("typpppp", type.get(i));
}
return params;
};
};
queue.add(myReq);
}
public String getCharlie(){
userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);
return userDetails.getString("response", "no value found");
}
public void clearCharlie(){
SharedPreferences.Editor edit = userDetails.edit();
edit.clear();
edit.commit();
}
}
when i am trying to use this class from login activity i am getting message for the below log "pref response" is "no value found". if run it again i am getting proper response which i am expecting. I don't know how to fix this bug. any help is appreciated.
this is my main activity
public class Login extends Activity {
Button signup,submit;
EditText email,password;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final NetworkCall net = new NetworkCall(getApplicationContext());
final ArrayList<String> type = new ArrayList<String>();
final ArrayList<String> value = new ArrayList<String>();
submit = (Button) findViewById(R.id.submit);
email = (EditText) findViewById(R.id.edittext_email);
password = (EditText) findViewById(R.id.edittext_pwd);
type.add("user_email");
type.add("user_password");
value.add(email.getText().toString().trim());
value.add(password.getText().toString().trim());
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
net.networkCallByVolley(type, value);
String response = net.getCharlie();
Log.i("pref resonse", response);
}
});
}
}
You need to use ASYNC task or handler.
What you are doing is calling getCharlie() method right after you made the call net.networkCallByVolley(type, value); It takes some time to get response from the sever after which only it will write the response to the shared prefrences. You are getting no result found because at that time there is no response. Respone is being calculated on some another parallel thread. As soon as that thread gets the response it show that to you but until then you will be having null. So wait for the thread to get response using ASYNC task.
#Override
public void onClick(View v) {
net.networkCallByVolley(type, value);
String response = net.getCharlie();
while(response.equalsIgnorecase("no result found")){}
Log.i("pref resonse", response);
}
Actually you need to wait until getting response from Volley.
You can use a BroadcastReceiver in your Login Activity
and send a broadcast from NetworkCall Activity after you get a response from the server, and when you receive a broadcast do what you want to do e.g checking SharedPreferences.
Alternative way you can use is Observer Pattern to get notice when you get response from server.

Categories

Resources