The code I've written is to connect my android studio to wamp server mysql. I try to retrieve login information from mysql to android. However it keep showing me unexpected response code 400. How should i change my code?
#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
Intent intent = new Intent(LoginActivity.this,
PofileActivity.class);
startActivity(intent);
}
}
private void login(){
//Getting values from edit texts
final String email = editTextEmail.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
//Creating a string request
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Config.LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//If we are getting success from server
if(response.equalsIgnoreCase(Config.LOGIN_SUCCESS)){
//Creating a shared preference
SharedPreferences sharedPreferences =
LoginActivity.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.EMAIL_SHARED_PREF, email);
//Saving values to editor
editor.commit();
//Starting profile activity
Intent intent = new Intent(LoginActivity.this,
PofileActivity.class);
startActivity(intent);
}else{
//If the server response is not success
//Displaying an error message on toast
Toast.makeText(LoginActivity.this, "Invalid username
or password", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
//You can handle error here if you want
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
//Adding parameters to request
params.put("Content-Type", "application/json");
params.put(Config.KEY_EMAIL, email);
params.put(Config.KEY_PASSWORD, 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
login();
}
This is common issue when using volley library. You may not be setting the right headers when you are making the request that is why it gives us 400 Bad Request error.
You may need to override the getBodyContentType() method in order to get the Content-Type header to update correctly.
public String getBodyContentType()
{
return "application/xml";
}
I have written a blog explaining the issue and how to resolve the same. Please refer here for resolution.
Related
I am building an android app and I am trying to send basic info on a phpmyadmin DB. I wrote a script (working, tested it with postman) and I used volley in my andorid app to send params to script. Here is my code.
public class Info extends AppCompatActivity {
EditText e_mail, age, group_size;
Button next;
static final String insertURL = "http://www.studenti.famnit.upr.si/~89161009/IGIPAN/insertUser.php";
static final String insertGroupURL = "http://www.studenti.famnit.upr.si/~89161009/IGIPAN/insertGroupUser.php";
String id_user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
next = (Button) findViewById(R.id.next);
e_mail = (EditText) findViewById(R.id.e_mail);
age = (EditText) findViewById(R.id.age);
group_size = (EditText) findViewById(R.id.group_size);
Intent intent = getIntent();
id_user = intent.getStringExtra("id");
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
insertUser();
Intent intent = new Intent(getApplicationContext(), LocationSearch.class);
startActivity(intent);
}
});
}
public void insertUser() {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.POST, insertURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parametar = new HashMap<String, String>();
parametar.put("id_user", id_user);
parametar.put("age", String.valueOf(age.getText()));
parametar.put("email", String.valueOf(e_mail.getText()));
return parametar;
}
};
requestQueue.add(request);
}
}
The problem is that I don't get any errors. And I did a previous project that was very similar, and did it exactly like this and it worked. Now I can't figure out why it won't work.
Every answer is appreciated. Thank you!
EDIT
My script is:
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
require 'connection.php';
insertUser();
}
function insertUser(){
global $connect;
$id_user = $_POST["id_user"];
$age = $_POST["age"];
$email = $_POST["email"];
$query = "INSERT INTO user ( id_user, age, email)
VALUES ( '$id_user', '$age', '$email');";
mysqli_query($connect, $query) or die (mysqli_error($connect));
mysqli_close($connect);
}
?>
I figured it out thanks to Nabil Mohammed Nalakath's suggestion to use log in onResponse(). Which gave me an value to long for column error.
Since I used uniqueID = UUID.randomUUID().toString(); i got an id of length 36 and in my table i only set varchar(35). So I changed that and it worked!
I think whenever you get success response then you want to open LocationSearch screen for that you need to keep this code:
Intent intent = new Intent(getApplicationContext(), LocationSearch.class);
startActivity(intent);
Inside onResponse() method and there you need to check have you got success response or not.If success then above code should be executed.
I think you should use requestQueue.enque(request);
Its important to configure AndroidMenifest.xml file
by
and
android:usesCleartextTraffic="true"
In my app I am using rest api to get json object for users and information. The authentication system is Oauth2. At first to use the app, user need to write their email address and password. and if the user existing email and pasword in web, they can succesfully login and see all the information. Now, I used cookiemanager to keep and pass the cookie to use that in other rest api. I am very new in handligh that situation. THe problem is the cookie is not refreshed with username and password. I would like to keep the session forever by refreshing the coockie each time. But do not now how can I do that. I am explaining with the following code
The login code where user give username and password. I used Volley Library. and the method is POST.
public class LoginPage extends AppCompatActivity {
public static final String MyPREFERENCES = "MyPrefs";
public static final String LOGIN_URL = "url_of_my_app";
public static final String KEY_EMAIL = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_IS_USER_LOGED_IN = "is-user-logged-in";
private String mEmail;
private String mPassword;
public static CookieManager cookieManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
//login credential
mEmail = sharedpreferences.getString(KEY_EMAIL, null);
mPassword = sharedpreferences.getString(KEY_PASSWORD, null);
if (mEmail != null && mPassword != null && sharedpreferences.getBoolean(KEY_IS_USER_LOGED_IN, false)) {
final GlobalClass globalClass = new GlobalClass();
globalClass.setEmail_info(mEmail);
Intent loginIntent = new Intent(LoginPage.this, MainOptionPage.class);
loginIntent.putExtra(KEY_EMAIL, mEmail);
startActivity(loginIntent);
finish();
} else {
});
}
}
private void attemptLogin() {
...
}
//volley library to hit the request
private void loginUser(final String mEmail, final String mPassword) {
final GlobalClass globalClass = new GlobalClass();
globalClass.setEmail_info(mEmail);
setFilePath();
this.trustAllCertificates();
cookieManager = new CookieManager(new PersistentCookieStore(getApplicationContext()), CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
RequestQueue queue = Volley.newRequestQueue(LoginPage.this);
StringRequest strReq = new StringRequest(Request.Method.POST,
LOGIN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
//parse your response here
if (response.contains("overview")) {
showProgress(true);
if (!globalClass.ifUserDataExist(mEmail)) {
Log.d("----After Login---", "After Login");
....
}
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(KEY_EMAIL, mEmail);
editor.putString(KEY_PASSWORD, mPassword);
editor.putBoolean(KEY_IS_USER_LOGED_IN, true);
editor.commit();
loginIntent.putExtra(KEY_EMAIL, mEmail);
startActivity(loginIntent);
finish();
} else {
userEmail.setError(getString(R.string.error_incorrect_login));
userEmail.requestFocus();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Log.e(TAG, "Inside getParams");
Map<String, String> params = new HashMap<>();
params.put(KEY_EMAIL, mEmail);
Log.d("email address", mEmail);
params.put(KEY_PASSWORD, mPassword);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
Log.d("headers", String.valueOf(headers));
return headers;
}
};
// Adding request to request queue
queue.add(strReq);
}
Now in UserActivity I am getting user information from Rest API if the login is successful. Hence I am getting those information. Bur after a certain time the session is expires and the recyclerview is blank.
I am giving only the Volley part of this activity class. I have used a alett dialog if the cookie is null. But in practise I do not want to do this. How can I keep the login credential forever which give me access to use all the api all the time.
public void sendRequest() {
trustAllCertificates();
CookieHandler.setDefault( cookieManager );
if (cookieManager==null) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Your session has expired");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dialog.dismiss();
Intent intent = new Intent( MyColleaguesPage.this, LoginPage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
//editor.remove("username");
//editor.remove("password");
editor.remove(LoginPage.KEY_IS_USER_LOGED_IN);
editor.apply();
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest( Request.Method.GET, UPLOAD_URL + "/api/users", null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
MyColleagueModel mycolleague = new MyColleagueModel();
try {
JSONObject object = response.getJSONObject( i );
mycolleague.setName( object.optString( "name" ) );
mycolleague.setGivenName( object.optString( "givenName" ) );
mycolleague.setCompany( object.optString( "company" ) );
mycolleague.setTitle( object.optString( "title" ) );
mycolleague.setMail( object.optString( "mail" ) );
mycolleague.setMobile( object.optString( "mobile" ) );
mycolleague.setDepartment( object.optString( "department" ) );
} catch (JSONException e) {
e.printStackTrace();
}
myColleagueList.add( mycolleague );
}
adapter = new MyColleaguesAdapter( myColleagueList, MyColleaguesPage.this );
recyclerView.setAdapter( adapter );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i( "Volley Error: ", error.toString() );
}
} );
rq.add( jsonArrayRequest );
}
}
I just wanted help in my android app actually scene is like ,I have made an android app that stores and fetch data from mysql database,so the twist is whenever I run app on android emulator it runs fine but as soon as I try to run it on actual device there seem to be nothing is happening however the login and register buttons seem to be doing nothing they don't call the api,I am using wamp as local server and my device and laptop is on same wifi network router so I am not getting it,btw the logcat shows no error at all and it also runs perfectly on emulator
my register activity to add user into database
public class Register extends AppCompatActivity {
private static final String TAG = Register.class.getSimpleName();
ProgressDialog progressDialog;
private EditText signupInputName, signupInputEmail, signupInputPassword;
public Button btnSignUp;
public Button btnLinkLogin;
private SQLiteHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
SessionManager session = new SessionManager(getApplicationContext());
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(Register.this,
Matchboard.class);
startActivity(intent);
finish();
}
signupInputName = (EditText) findViewById(R.id.name);
signupInputEmail = (EditText) findViewById(R.id.email);
signupInputPassword = (EditText) findViewById(R.id.password);
btnSignUp = (Button) findViewById(R.id.btnRegister);
btnLinkLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = signupInputName.getText().toString().trim();
String email = signupInputEmail.getText().toString().trim();
String password = signupInputPassword.getText().toString().trim();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_SHORT).show();
}
}
});
btnLinkLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),Login.class);
startActivity(i);
finish();
}
});
}
private void registerUser(final String name, final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
progressDialog.setMessage("Adding you ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_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 error = jObj.getBoolean("error");
if (!error) {
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);
Toast.makeText(getApplicationContext(), "Hi "+name+",You are successfully Added!", Toast.LENGTH_SHORT).show();
// Launch login activity
Intent intent = new Intent(
Register.this,
Login.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_SHORT).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_SHORT).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);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
I believe when you are on your local machine the call to made to the localhost but when the app is on your actual device there might be some IP issue.You might be accessing it wrongly.
The thing is that your actual device and the system should be on the same network.
Check your IP using ipconfig command and then retry on same network.
I have a django rest api as the backend for my android application. I want my app users to be able to sign in and sign up for my app. When users sign up, or when a new user is added to the user table, an authentication token for that user should be generated. I do this with the following code in the user model:
# This code is triggered whenever a new user has been created and saved to the database
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
Now when I try to sign in as the newly created user, when using Token Authentication, all I need to do is POST the email and password in the body of the request for the user. I do this like so using retrofit 2:
public interface UserService {
#POST("users/api-token-auth/")
Call<String> loginInToken(#Body LoginCredentials loginCredentials);
}
The LoginCredentials class looks like this:
public class LoginCredentials {
private String email;
private String password;
public LoginCredentials() { }
public LoginCredentials(String email, String password) {
this.email = email;
this.password = password;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
}
In my app I then make the following call to the django rest api using this interface method contained in UserService:
#Override
public void loginEmailUser(LoginCredentials loginCredentials) {
Call<String> call = userServiceApi.loginInToken(loginCredentials);
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
Log.d("USER_REPOSITORY", response.toString());
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.d("USER_REPOSITORY", t.toString());
}
});
}
If successful, the email and password have been POSTed to the backend in exchange for the corresponding user's authentication token, hence I should receive a token by making this request. However when this endpoint api-token-auth is called the onFailure method is called with the following throwable:
USER_REPOSITORY: Response{protocol=http/1.0, code=400, message=Bad Request, url=http://XXX.YYY.Z.AAA:8000/users/api-token-auth/}
Here is my django urls.py file which corresponds to the called url from the android client:
from django.conf.urls import url
from users import views as user_views
from rest_framework.authtoken import views as auth_views
urlpatterns = [
url(r'^api-token-auth/', auth_views.obtain_auth_token),
url(r'^create/', user_views.UserCreate.as_view(), name="create"),
url(r'^$', user_views.UserList.as_view(), name="users_list"),
url(r'^(?P<pk>[0-9]+)/$', user_views.UserDetail.as_view(), name="user_detail"),
]
The django rest docs say that calling the api-token-auth url with the email and password POSTed should result in the token being returned and a status code 200.
Why am I getting a bad request and status code 400 when I seem to be doing as instructed for a successful request?
I am Addding Sample LOGIN Class Using OAUth .I am using Volley library
public class Login extends AppCompatActivity implements View.OnClickListener {
EditText userName, Password;
Button login;
public static final String LOGIN_URL = "http://192.168.100.5:84/Token";
public static final String KEY_USERNAME = "UserName";
public static final String KEY_PASSWORD = "Password";
String username, password;
String accesstoken, tokentype, expiresin, masterid, name, access, issue, expires, masterid1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userName = (EditText) findViewById(R.id.login_name);
Password = (EditText) findViewById(R.id.login_password);
userName.setHint(Html.fromHtml("<font color='#008b8b' style='italic'>Username</font>"));
Password.setHint(Html.fromHtml("<font color='#008b8b'>Password</font>"));
login = (Button) findViewById(R.id.login);
login.setOnClickListener(this);
}
private void UserLogin() {
username = userName.getText().toString().trim();
password = Password.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
accesstoken = jsonObject.getString("access_token");
tokentype = jsonObject.getString("token_type");
expiresin = jsonObject.getString("expires_in");
username = jsonObject.getString("userName");
masterid = jsonObject.getString("MasterID");
masterid = masterid.replaceAll("[^\\.0123456789]", "");
masterid1 = jsonObject.getString("MasterID");
name = jsonObject.getString("Name");
access = jsonObject.getString("Access");
issue = jsonObject.getString(".issued");
expires = jsonObject.getString(".expires");
SessionManagement session = new SessionManagement(Login.this);
session.createLoginSession(accesstoken, tokentype, expiresin, username, masterid, name, access, issue, expires);
// session.createLoginSession(masterid1);
openProfile();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Fetch failed!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(Login.this, error.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(Login.this, "Please enter valid username and Password", Toast.LENGTH_SHORT).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
//params.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
return params;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
map.put(KEY_USERNAME, username);
map.put(KEY_PASSWORD, password);
//map.put("access_token", accesstoken);
map.put("grant_type", "password");
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void openProfile() {
Intent intent = new Intent(this, Home.class);
intent.putExtra(KEY_USERNAME, username);
startActivity(intent);
startActivity(intent);
}
#Override
public void onClick(View v) {
UserLogin();
}
}
this is Sample .please transform it as your requirement
I want to ask if is it possible to store a string globally for me to call in any other activity? Like for example the String email in my code, I want to save it globally so I can call it from other activity.
I tried using intent to carry data but it does not seem to work for my code.
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
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);
}
You can use global variable, but most of the time you shouldn't use this.
Are global variables bad?
You have to know if this variable is used in most of your application (lot of class need an access to it, and be careful about threads to not have a concurrency issue). If it's the case you can maybe use a global, which is a bad idea in my opinion. You also can do a singleton class.
But if you just try to send your variable between two view, I think you should use this
You can use SharedPreferences to save data to preference and use it any Activity.
You can use this method to save your email String into SharedPreferences.
public void saveValueToPrefrence(Context mContext, String key, String value) {
SharedPreferences pref = mContext.getSharedPreferences("UserData", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString(key, value);
editor.apply();
}
You can get email String in any other Activity using below method:
public String getValueFromPrefrence(Context mContext, String key) {
SharedPreferences pref = mContext.getSharedPreferences("UserData", 0);
return pref.getString(key, "");
}
You can use this method to save your email String:
saveValueToPrefrence(ActivityName.this,"email",email)
You can get email String like this:
String email = getValueFromPrefrence(ActivityName.this,"email")
Basically you need Activity's Context to save and get value from SharedPreferences.
I hope it helps you.
#FreeYourSoul is correct.
But as an answer to this question, there are multiple ways to do this. The easiest way would be to simply create a Static class that has a hashmap inside it that you can manipulate with any class.
Likely not your best choice, but it certainly is possible