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 );
}
}
Related
facing problem in posting data to mysql database using rest api which is done in magento 2 from my android app.
RegisterActivity extends AppCompatActivity {
private static final String TAG = "RegisterActivity";
private static final String URL_FOR_REGISTRATION = "https://xyz/restapi/registration";
ProgressDialog progressDialog;
private EditText signupInputName, signupInputEmail, signupInputPassword, signupInputCnfPassword, signupInputAge;
private Button btnSignUp;
private Button btnLinkLogin;
private RadioGroup genderRadioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
// Progress dialog
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
signupInputName = (EditText) findViewById(R.id.signup_input_name);
signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
signupInputCnfPassword = (EditText) findViewById(R.id.signup_input_passwords);
signupInputAge = (EditText) findViewById(R.id.signup_input_age);
btnSignUp = (Button) findViewById(R.id.btn_signup);
btnLinkLogin = (Button) findViewById(R.id.btn_link_login);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
submitForm();
}
});
btnLinkLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(i);
}
});
}
private void submitForm() {
registerUser(signupInputName.getText().toString(),
signupInputEmail.getText().toString(),
signupInputPassword.getText().toString(),
signupInputCnfPassword.getText().toString(),
signupInputAge.getText().toString());
}
private void registerUser(final String name, final String email, final String password, final String cnfpassword, final String dob) {
// Tag used to cancel the request
String cancel_req_tag = "register";
progressDialog.setMessage("Adding you ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_REGISTRATION, 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 user = jObj.getJSONObject("user").getString("name");
Toast.makeText(getApplicationContext(), "Hi " + user +", You are successfully Added!", Toast.LENGTH_SHORT).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("cust_username", name);
params.put("cust_firstname", email);
params.put("cust_pass", password);
params.put("cust_confirmpass", cnfpassword);
params.put("cust_phoneno", dob);
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
I am using Volley library for request.
I am getting this error
BasicNetwork.performRequest: Unexpected response code 503 for
https://xyz/restapi/registration.
My question is am I missing any thing or will there be constrain that should be checked in mysql to post the data.
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 started learning Android and Java a week ago and now I am trying to make an login application. I am using Volley libary to communicate with my server. I have done the login part. Now, what I want to do is to check the database every minute to see if the password or the username somehow changed. If the information in the database is changed, app will automaticly logout the user.
If you can explain which tools(Services,BroadcastReceivers) I can use and how can I achieve it, as I am not very experienced.
This is what I tried and failed:
loginChecker.class
public class loginChecker extends Service {
public loginChecker() {
}
public static String username;
public static String password;
private loginChecker mInstance = this;
public static boolean loginCheck= true;
public static String responseG = "failed";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle b=intent.getExtras();
username = b.getString("username");
password = b.getString("password");
final String URL = ".........";
final RequestQueue requestQueue = Volley.newRequestQueue(mInstance);
new Thread(new Runnable(){
public void run() {
do{
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
responseG = response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
responseG = "error";
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("username", username);
hashMap.put("password", password);
return hashMap;
}
};
requestQueue.add(request);
switch(responseG){
case "successful" :
loginCheck = true;
break;
case "failed" :
loginCheck= false;
break;
case "error" :
loginCheck = false;
break;
}
}
while(loginCheck == true || responseG == "successful");
}
}).start();
Toast.makeText(getApplicationContext(), "LOOP ENDED", Toast.LENGTH_SHORT).show();
return START_REDELIVER_INTENT;
}
#Override
public void onDestroy() {
final Intent mainActivity = new Intent(mInstance, MainActivity.class);
mainActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mainActivity);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity {
private RequestQueue requestQueue;
private static final String URL = "........";
private StringRequest request;
private TextView text;
private EditText userName, passWord;
private Button loginButton;
public MainActivity mInstance = this;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView);
userName = (EditText) findViewById(R.id.userName);
passWord = (EditText) findViewById(R.id.passWord);
loginButton = (Button) findViewById(R.id.loginButton);
requestQueue = Volley.newRequestQueue(this);
final Intent profilePage = new Intent(this, Profile.class);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick (View v){
loginButton.setEnabled(false);
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
text.setText(response);
switch(response){
case "successful" :
Intent loginCheckerService = new Intent(mInstance, com.erenyenigul.apps.starter.services.loginChecker.class);
Bundle b = new Bundle();
b.putString("username", String.valueOf(userName.getText()));
b.putString("password", String.valueOf(passWord.getText()));
loginCheckerService.putExtras(b);
startService(loginCheckerService);
startActivity(profilePage);
finish();
break;
case "failed" :
Toast.makeText(getApplicationContext(), "Username or Password you entered is wrong!", Toast.LENGTH_LONG).show();
loginButton.setEnabled(true);
break;
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "There is a problem with our servers or you don't have internet connection!", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("username", userName.getText().toString());
hashMap.put("password", passWord.getText().toString());
return hashMap;
}
};
requestQueue.add(request);
}
}
);
}
}
There is also a file called Profile.class but it is empty. I tried this but the loop lasted one tour. It stopped even though the connection was ok and the data wasn't changed.
Hey developers i am tried send the data through intent
i am sending data A activity to B activity data is send A Activity properly but B Activity is not receive but some data is receive but some data not receive
Code is A Activity
private void requestForSMS(final String mobile) {
StringRequest strReq = new StringRequest(Request.Method.POST,
config.Config.URL_REQUEST_SMS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject responseObj = new JSONObject(response);
final String user = responseObj.getString("uid");
String message = responseObj.getString("msg");
Intent intent1 = new Intent(getApplicationContext(),HttpService.class);
intent1.putExtra("uid", user); // <---Sending data here this data not recive B Activity ------>
Log.d("user id going","====>"+user);
if(!user.equalsIgnoreCase("")){
pref.setIsWaitingForSms(true);
viewPager.setCurrentItem(1);
txtEditMobile.setText(pref.getMobileNumber());
layoutEditMobile.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"ErrorToast: " + message,
Toast.LENGTH_LONG).show();
}
// hiding the progress bar
progressBar.setVisibility(View.GONE);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "ErrorResponce: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("key","xxxxxxxxxxxxx");
params.put("mobile", mobile);
Log.e(TAG, "Posting params: " + params.toString());
return params;
}
};
int socketTimeout = 60000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
strReq.setRetryPolicy(policy);
// Adding request to request queue
newapp.getInstance().addToRequestQueue(strReq);
}
private void verifyOtp() {
String otp = inputOtp.getText().toString().trim();
if (!otp.isEmpty()) {
Intent grapprIntent = new Intent(getApplicationContext(), HttpService.class);
// <---- sending data here also B Activity---->
grapprIntent.putExtra("key","xxxxxxxxxxxx");
grapprIntent.putExtra("mobileverify", otp);
startService(grapprIntent);
} else {
Toast.makeText(getApplicationContext(), "Please enter the OTP", Toast.LENGTH_SHORT).show();
}
}
private static boolean isValidPhoneNumber(String mobile) {
String regEx = "^[0-9]{10}$";
return mobile.matches(regEx);
}
B Activity
public class HttpService extends IntentService {
private static String TAG = HttpService.class.getSimpleName();
public HttpService() {
super(HttpService.class.getSimpleName());
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
String otp = intent.getStringExtra("mobileverify");
final String user1 = intent.getStringExtra("uid"); //<---- this is not recive value ---->
verifyOtp(otp,user1);
}
}
/**
* Posting the OTP to server and activating the user
*
* #param otp otp received in the SMS
*/
private void verifyOtp(final String otp, final String user1){
StringRequest strReq = new StringRequest(Request.Method.POST,
config.Config.URL_VERIFY_OTP, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject responseObj = new JSONObject(response);
// Parsing json object response
// response will be a json object
String message = responseObj.getString("msg");
if (message!="") {
// parsing the user profile information
JSONObject profileObj = responseObj.getJSONObject(response);
String mobile = profileObj.getString("mobile");
PrefManager pref = new PrefManager(getApplicationContext());
pref.createLogin(mobile);
Intent intent = new Intent(HttpService.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Toast.makeText(getApplicationContext(), "HTTPIF"+message, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "HTTPELSE"+message, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "HTTPError: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("key","xxxxxxxxxx");
params.put("mobileverify", otp);
params.put("uid",user1); // here its given error
Log.e(TAG, "Posting params: " + params.toString());
return params;
}
};
MyApplication.getInstance().addToRequestQueue(strReq);
}
Please Help me Thanks
Your grapprIntentdoesn't contain a value for "uid" key because you don't put it. You use some intent1 which is not used anywhere more. Instead you need to put "uid" into grapprIntent:
grapprIntent.putExtra("uid", user);
Maybe grapprIntent should be global variable for the class or find a way to pass it between methods.
Create A Global variable in your Application class and Use set and get Methods
like this
Application.class
private String user;
public String setuser(String usermy) {
this.user = usermy;
return null;
}
public String getuser()
{
return user;
}
where you want to send value set value like as your code
SMSActivity
MyApplication myUser = (MyApplication)getApplicationContext();
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject responseObj = new JSONObject(response);
String user = responseObj.getString("uid");
String user1 = myUser.setuser(user);
And Get Value in your HttpService.class
Like this
MyApplication uidinfo = (MyApplication)getApplicationContext();
final String user = uidinfo.getuser();
and mention manifest.xml inside Application tag
<application
android:name=".MyApplication"
/>
happy coding