How to save fragment onButtonClick and load on next program start - java

I have an app where I have a fragment.Let's call it mainScreen. In mainScreen there's a button and onClick() opens second fragment. Let's call it FragmentHomePage. In FragmentHomePage i have a retrofit. There's a button named logOut. My problem is, when user not clicked logOut, i want to save this fragment and load this fragment. In default when app starts, opens mainScreen, but if user not clicks logOut, i need open FragmentHomePage on app start. How can i do this?
public class FragmentHomePage extends BaseFragment {
View mainView;
TextView fullName, userName, email;
Button logOut;
ApiClient apiClient = ApiClient.getInstance();
SupportObjToken supportopToken = new SupportObjToken();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.home_page, container, false);
init(mainView);
newTokenCall();
return mainView;
}
private void init(View v) {
fullName = v.findViewById(R.id.fullName);
userName = v.findViewById(R.id.user);
email = v.findViewById(R.id.mail);
logOut = v.findViewById(R.id.logOut);
}
public void newTokenCall() {
String clientID = SharedPreferencesManager.getInstance().getClientID();
String clientSecret = SharedPreferencesManager.getInstance().getClientSecret();
String refreshToken = SharedPreferencesManager.getInstance().getRefreshToken();
String newRefreshToken = SharedPreferencesManager.getInstance().getNewRefreshToken();
final String firstName = SharedPreferencesManager.getInstance().getFirstName();
final String lastName = SharedPreferencesManager.getInstance().getLastName();
final String mail = SharedPreferencesManager.getInstance().getEmail();
final String user = SharedPreferencesManager.getInstance().getUsername();
supportopToken.setGrantType("refresh_token");
supportopToken.setClientId(clientID);
supportopToken.setClientSecret(clientSecret);
supportopToken.setRefreshToken(refreshToken);
Call<ResponseBody> newToken = apiClient.newToken(supportopToken);
newToken.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String newDataAccess = response.body().string();
JSONObject obj = new JSONObject(newDataAccess);
String newAccessToken = obj.getString("accessToken");
String newRefreshToken = obj.getString("refreshToken");
SharedPreferencesManager.getInstance().setNewAccessToken(newAccessToken);
SharedPreferencesManager.getInstance().setNewRefreshToken(newRefreshToken);
fullName.setText(firstName + " " + lastName);
userName.setText(user);
email.setText(mail);
} catch (IOException | JSONException e) {
e.printStackTrace();
}
} else if (response.code() == 401) {
supportopToken.setRefreshToken(SharedPreferencesManager.getInstance().getNewRefreshToken());
Call<ResponseBody> newToken1 = apiClient.newToken(supportopToken);
newToken1.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String newDataAccess = response.body().string();
JSONObject obj = new JSONObject(newDataAccess);
String newAccessToken = obj.getString("accessToken");
String newRefreshToken = obj.getString("refreshToken");
SharedPreferencesManager.getInstance().setNewAccessToken(newAccessToken);
SharedPreferencesManager.getInstance().setNewRefreshToken(newRefreshToken);
fullName.setText(firstName + " " + lastName);
userName.setText(user);
email.setText(mail);
} catch (JSONException | IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getActivity(), "You're on failure getting new Token", Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getActivity(), "You're on failure getting new Token", Toast.LENGTH_SHORT).show();
}
});
}}
How can i do this part? Thanks. Yeah and not give negative vote. I'm a beginner on this site)).
Here's the activity where i'm launching the fragments.
public class MainActivity extends AppCompatActivity implements FragmentChangeListener {
FragmentActivity fragmentActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ApiClient.initializeInstance("simple web page");
fragmentActivity = new FragmentActivity();
this.replaceFragment(fragmentActivity, true);
SharedPreferencesManager.init(this);
}
#Override
public void replaceFragment(BaseFragment fragment, Boolean isAddToBackStack) {
String backStateName = fragment.getClass().getName();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container, fragment, fragment.toString());
transaction.addToBackStack(backStateName);
transaction.commit();
}}

In your mainScreen button onclick, add a key to shared preferences like this
SharedPreferences.Editor editor = getSharedPreferences("APP_PREF", MODE_PRIVATE).edit();
editor.putString("state", "logged_in");
editor.apply();
inside your logOut button onclick in FragmentHomePage add the following code
SharedPreferences.Editor editor = getSharedPreferences("APP_PREF", MODE_PRIVATE).edit();
editor.putString("state", "logged_out");
editor.apply();
Now inside your first fragment's oncreate add this
SharedPreferences prefs = getSharedPreferences("APP_PREF", MODE_PRIVATE);
String state = prefs.getString("state", "state");
if(state.equals("logged_in"){
//load second fragment here
}

save a boolean value in SharedPreferences with default value false.
PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).edit().putBoolean("ISUSERALREADYLOGGEDIN", false).apply();
when ever you come to the FragmentHomePage , set this value to true.
PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).edit().putBoolean("ISUSERALREADYLOGGEDIN", true).apply();
When user clicks logout button , set this value to false again.
PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).edit().putBoolean("ISUSERALREADYLOGGEDIN", false).apply();
From the Base Activity which is keeping these fragments,
When you launch the mainScreen fragment, check this value, with this code :
PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).getBoolean("ISUSERALREADYLOGGEDIN", false);
If the value is true, launch the HomeFragment, else launch the mainScreen fragment.
Use this function to launch the fragment:
public void launchFragmentByReplacing(Fragment fragment, String incomingFragmentTag) {
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(frameLayout.getId(), fragment, incomingFragmentTag);
transaction.commit();
manager.executePendingTransactions();
}
In your case, right before :
this.replaceFragment(fragmentActivity, true);
check for the SharedPref value.
Boolean isloggedIn = PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).getBoolean("ISUSERALREADYLOGGEDIN", false);
if(isloggedIn) //is true
this.replaceFragment(new FragmentActivity(), true);
else
this.replaceFragment(new FragmentHomePage(), true);

Related

URL is not redirecting to home page after sending token android?

I have a login activity that works fine,after successfully login i get token which i send it to the webview fragment by SharedPreferences and pass it to WebviewClient but it doesn't redirect to the homepage URL of the site which is inside webview,it's redirect to login page URL of the site inside Webview.I didn't find helpful solution.
Thanks in advance
My code:
Login Activity
btnSignin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fetchToken();
}
});
}
private void fetchToken() {
String email = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
UserRequest userRequest = new UserRequest(email, password);
RxUtil.asyncConsumer(service.getToken(userRequest), new Consumer<TokenResponse>() {
#Override
public void accept(TokenResponse response) throws Exception {
Log.d("ResponseToken", "" + response.getSuccess().getToken());
if (response.getSuccess() != null) {
String token = response.getSuccess().getToken();
setKeyToken(token);
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
}else {
Toast.makeText(LoginActivity.this, "Something went wrong please try again", Toast.LENGTH_LONG).show();
}
}
});
}
private void setKeyToken(String token) {
preferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(KEY_TOKEN, token);
editor.apply();
}
public String getKeyToken() {
preferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
return preferences.getString(KEY_TOKEN, "");
}
Web Fragment inside Main Activity
public class WebFragment extends Fragment {
private WebView webView;
private ProgressBar progressBar;
private String url = "some_url";
private String token;
private SharedPreferences preferences;
public WebFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_web, container, false);
webView = view.findViewById(R.id.web_view);
progressBar = view.findViewById(R.id.progress_bar);
preferences = getActivity().getSharedPreferences(LoginActivity.SHARED_PREFS, Context.MODE_PRIVATE);
initWebView(url);
return view;
}
private void initWebView(String url) {
webView.loadUrl(url);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebClient());
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setSupportMultipleWindows(true);
webView.getSettings().setUseWideViewPort(true);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
}
public class WebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressBar.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Nullable
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
String token = preferences.getString(LoginActivity.KEY_TOKEN, "DEFAULT");
Log.d("Arg", "" + token);
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).addHeader("Authorization", "Bearer " + token).build();
Response response = okHttpClient.newCall(request).execute();
return new WebResourceResponse(response.header("text/html", response.body().contentType().type()),
response.header("content-encoding", "utf-8"),response.body().byteStream());
} catch (ProtocolException e) {
//return null to tell WebView we failed to fetch it WebView should try again.
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
#Override
public void onPageFinished(WebView view, String url) {
progressBar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
}

Unable to get Saved shared preferences in the fragment

I am working on a app and while getting my shared preferences(which are saved in login activity), i am trying to get it in dashboard fragment but i am not be able to get it. After this i checked whether the is saved or not so then i used
boolean ok= editor.commit();
Toast.makeText(Login.this, "Saved: "+ok, Toast.LENGTH_LONG).show();
My toast shows message as Saved:true
After this try i am assuming that my data is saved to preferecnces but i am unable to fetch it. Below is my dashboard fragmenr code.
public class dashboard extends Fragment {
private TextView comp_text,mail_text,gst_text;
private String mUsername;
private SharedPreferences mSharedPreferences;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//this inflates out tab layout file.
View x = inflater.inflate(R.layout.dashboard_frag, null);
comp_text=(TextView)x.findViewById(R.id.company_id);
mail_text=(TextView)x.findViewById(R.id.email_id);
gst_text= (TextView)x.findViewById(R.id.gst_id);
initSharedPreferences();
Toast.makeText(getActivity(), "Logged member-> "+mUsername, Toast.LENGTH_LONG).show();
return x;
}
private void initSharedPreferences() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUsername = mSharedPreferences.getString(Constants.USERNAME, "");
}
}
Here my Toast show **logged member-> **, that means musername have nothing to print and preferences are unable get.
I'm still confused this is my point of view if you want i can show where i saved preferences.
Help will be appreciated !
THANKS !
EDIT 1 ----
Here is my onResponse function where i saved preferences.
public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
if(response.isSuccessful()) {
ServerResponse serverResponse = response.body();
if(serverResponse.getMessage().equals(username)) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putBoolean("LoggedIn",true);
editor.putString(Constants.USERNAME,serverResponse.getMessage());
boolean ok= editor.commit();
Toast.makeText(Login.this, "Saved: "+ok, Toast.LENGTH_LONG).show();
goToProfile();
}
} else {
Gson gson = new Gson();
ServerResponse errorResponse = null;
try {
errorResponse = gson.fromJson(response.errorBody().string(), ServerResponse.class);
} catch (IOException e) {
e.printStackTrace();
}
Snackbar.make(loginButton,errorResponse.getMessage(),Snackbar.LENGTH_SHORT).show();
}
}
Try this
SharedPreferences.Editor editor = getSharedPreferences("my_prefs", MODE_PRIVATE).edit();;
editor.putBoolean("LoggedIn",true);
editor.putString(Constants.USERNAME,serverResponse.getMessage());
boolean ok= editor.commit();
And then in Fragment
mSharedPreferences = getActivity().getSharedPreferences("my_prefs", MODE_PRIVATE); ;
mUsername = mSharedPreferences.getString(Constants.USERNAME, "");

How to auto login with Firebase in Android Studio?

I am creating a restaurant app for members & non-members. The home page consist of 3 buttons- menu, sign-in and sign-up. I want to let non-members auto login (default phoneId)into the system when they tap on the menu button and members will just sign-in or sign-up each time.
I tried to use sharedPreferences (default phoneId) for the non-member auto login but I don't know whether the default phoneId can be sync with firebase. I want to track the transaction orders for the non-members. Is there any way to only let the default phoneId to have auto login function?
p/s I am just a beginner and doing this app for my project. pls help thanks.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button btnSignIn, btnSignUp, btnMenu;
public AppPreferences appPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appPreference = new AppPreferences(this);
btnMenu = (Button)findViewById(R.id.btnMenu);
btnSignUp = (Button)findViewById(R.id.btnSignUp);
btnSignIn = (Button)findViewById(R.id.btnSignIn);
btnMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent home = new Intent(MainActivity.this, Home.class);
//Here save user info to preferences
appPreference.setUserPhoneId(Constant.DEFAULT_PHONE_ID);
appPreference.setUserPassword(Constant.DEFAULT_PASSWORD);
startActivity(home);
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signUp = new Intent(MainActivity.this, SignUp.class);
startActivity(signUp);
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signIn = new Intent(MainActivity.this, SignIn.class);
startActivity(signIn);
}
});
}
}
AppPreferences.java
public class AppPreferences {
// Class variables
private Context context;
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor editor;
public static final String PREF_NAME = "iMenuApp";
private int PRIVATE_MODE = 0;
// Define your preferences key
private static final String USER_PHONE = "9876543210";
private static final String USER_PASSWORD = "12345";
public AppPreferences(Context context)
{
this.context = context;
sharedPreferences = this.context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
if (sharedPreferences != null)
{
editor = sharedPreferences.edit();
}
}
//Store user PhoneId
public void setUserPhoneId(String userId){
String TAG = "AppPref:setUserId";
try
{
editor.putString(USER_PHONE, userId);
editor.commit();
} catch (Exception e) {
Log.e(TAG, String.valueOf(e));
}
}
// Get userPhoneId
public String getUserPhoneId(){
return sharedPreferences.getString(USER_PHONE,"default_phone");
}
//Store userPassword
public void setUserPassword(String userPassword){
String TAG = "AppPref:setUserPassword";
try
{
editor.putString(USER_PASSWORD, userPassword);
editor.commit();
} catch (Exception e) {
Log.e(TAG, String.valueOf(e));
}
}
// Get userPassword
public String getUserPassword(){
return sharedPreferences.getString(USER_PASSWORD,"default_password");
}
}
the whole approach is rather questionable, because there is an anonymous authentication provider, which should be used for those "non-members" (and it can also be used together with security rules). storing the state of the authentication to Preferences is prone to errors, because it does not consider the actual state of the authentication - which will result in access denied, once the token expired.
I've also seen your previous question, while nevertheless the whole business logic is flawed.
... better see AccountManager, for how to properly store accounts on Android.
You need to do something like this,
MainActivity -> SignIn -> if SignIn success -> Next time you launch the app land to Home Activity
Try this,
1.) First, you define a new boolean preferences key, USER_LOGGED_IN and create setUserLoggedIn() and getUserLoggedIn() methods in your AppPreferences class as below.
private static final boolean USER_LOGGED_IN = false;
public static void setUserLoggedIn(boolean value) {
String TAG = "AppPref:setUserLoggedIn";
try{
editor.putBoolean(USER_LOGGED_IN, value);
editor.commit();
} catch (Exception e) {
Log.e(TAG, String.valueOf(e));
}
}
public static boolean getUserLoggedIn() {
return sharedPreferences.getBoolean(USER_LOGGED_IN, false);
}
2.) Then, in your SignIn Activity, If login success, set UserLoggedIn as true in your sharedPreferences.
3.) Finally, In your MainActivity, override onResume() method as follows,
#Override
protected void onResume() {
super.onResume();
boolean userLoggedIn = AppPreferences.getUserLoggedIn();
if(userLoggedIn){
MainActivity.this.startActivity(new Intent(getApplicationContext(), Home.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
}
}
Try this and let me know your feedback.
Thanks!

Android Studio - Using Volley to get JSON data from the server

This is my first attempt to create a login system in Android Studio and already got myself into trouble with my code.
My PHP script always returns something as JSON and I'm trying to parse that JSON in my LoginActivity, inside the login -method, but I'm getting
the following error after creditentials were forwarded to the server and the login button was clicked:
I/qtaguid﹕ Failed write_ctrl(u 43) res=-1 errno=22
I/qtaguid﹕ Untagging socket 43 failed errno=-22
W/NetworkManagementSocketTagger﹕ untagSocket(43) failed with errno -22
It did work earlier, when I was doing a stringRequest instead of jsonRequest, so everything should be fine on the server side. Since I'm very new to Android development, I'm unable to figure this one out by myself and need desperately your help.
Here's my LoginActivity without the imports:
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
// Define Views
private EditText editTextEmail, editTextPassword;
private Button buttonLogin;
private ProgressBar progress;
private UserLocalStore userLocalStore;
private boolean loggedIn = false;
private final String TAG = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide(); // Hides the Action Bar for Login Activity
setContentView(R.layout.activity_login); // Sets the Content View
// Initializing Views
// EditText fields
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
// Buttons
buttonLogin = (Button) findViewById(R.id.buttonLogin);
// Other
progress = (ProgressBar) findViewById(R.id.progressBar);
// This method will set watcher for the EditTextFields
// The method will watch the value set to the EditTextFields.
// If there is nothing inputted in the EditTextField, "Login" button is disabled.
// Correspondingly, if there are text in the field, "Login" button is enabled.
watcher(editTextEmail, editTextPassword, buttonLogin);
// On-Click listeners
buttonLogin.setOnClickListener(this);
}
// Watcher method to check the value of EditText field
public void watcher(final EditText editText, final EditText editPassword, final Button button)
{
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (editText.length() == 0 && editPassword.length() == 0) // If length of the text field is equal to 0
button.setEnabled(false); // Disable the "Send" button
else
button.setEnabled(true); // Otherwise enable
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
if(editText.length() == 0 && editPassword.length() == 0)
button.setEnabled(false); //disable at app start
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
// If the value of loggedIn variable is true
if(!loggedIn) {
// We will start the Courses activity
Intent intent = new Intent(LoginActivity.this, CourseActivity.class);
startActivity(intent);
}
}
private void login() {
// Get the values from the edit texts
final String email = editTextEmail.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
// Creating a JSON Object request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Config.LOGIN_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
// This line will not print out
System.out.println(response);
try {
String json_status = response.getString("status");
String message = response.getString("message");
if(json_status.equalsIgnoreCase(Config.LOGIN_SUCCESS)) {
System.out.println(message);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// You can handle the 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(Config.KEY_EMAIL, email);
params.put(Config.KEY_PASSWORD, password);
// Return parameters
return params;
}
};
// Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
// If button Login was clicked
case R.id.buttonLogin:
login(); // Start login method after "Login" button is clicked
// startActivity(new Intent(this, MainActivity.class));
break;
}
}
}
And here's my PHP:
<?php
require_once("dbconnect.php");
// POST Variables
$post_email = $_POST['email'];
$post_password = $_POST['password'];
// Prepare the SQL query
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(array(
':email' => $post_email,
));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0 && password_verify($post_password, $row['password']) && $row['role'] != 'staff') {
$user = array(); // Create an array for the user information
$user['id'] = $row['id'];
$user['name'] = $row['name'];
$user['email'] = $row['email'];
$user['password'] = $row['password'];
$user['role'] = $row['role'];
// echo json_encode(["message" => "success"]);
echo json_encode(["status" => "success", "message" => "Successfully logged in"]); // Format the array to JSON
} else {
echo json_encode(["status" => "error", "message" => "Incorrect creditentials"]);
}
You might not be passing the params, I usually use this syntax:
// Get the values from the edit texts
final String email = editTextEmail.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
Map<String, Object> params = new ArrayMap<>(2);
// Adding parameters to request
params.put(Config.KEY_EMAIL, email);
params.put(Config.KEY_PASSWORD, password);
// Creating a JSON Object request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params),
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
Log.d(TAG, response.toString());
// other stuff ...
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
// You can handle the error here if you want
}
});
// Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
Also, you might want to handle all the volley requests in a Singleton class, have a look at this SO question.
Hope this helps in any way :)

After "cancel" click on Twitter, request token for the page is invalid (Twitter4j)

I am using Twitter4j to let my user's sign in to their Twitter account. They are able to successfully log in and out, but a problem occurs if they hit "cancel" on the Twitter popup dialog and go back to the app and then reopen the login, the login gives an error saying the request token for the page is invalid. I know I have the right consumer/secret keys because the login works if I don't click cancel and log in normally. Any ideas?
MainActivity
public class MainActivity extends Activity {
SharedPreferences pref;
private static String CONSUMER_KEY = "mykey";
private static String CONSUMER_SECRET = "mykey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getPreferences(0);
SharedPreferences.Editor edit = pref.edit();
edit.putString("CONSUMER_KEY", CONSUMER_KEY);
edit.putString("CONSUMER_SECRET", CONSUMER_SECRET);
edit.commit();
Fragment login = new LoginFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, login);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
}
LoginFragment
public class LoginFragment extends Fragment {
ImageView login;
Twitter twitter;
RequestToken requestToken = null;
AccessToken accessToken;
String oauth_url, oauth_verifier, profile_url;
Dialog auth_dialog;
WebView web;
SharedPreferences pref;
ProgressDialog progress;
Bitmap bitmap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login_fragment, container, false);
login = (ImageView) view.findViewById(R.id.login);
pref = getActivity().getPreferences(0);
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(pref.getString("CONSUMER_KEY", ""),
pref.getString("CONSUMER_SECRET", ""));
login.setOnClickListener(new LoginProcess());
return view;
}
private class LoginProcess implements OnClickListener {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new TokenGet().execute();
}
}
private class TokenGet extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
try {
requestToken = twitter.getOAuthRequestToken();
oauth_url = requestToken.getAuthorizationURL()
+ "&force_login=true";
Log.d("URL", oauth_url);
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return oauth_url;
}
#Override
protected void onPostExecute(String oauth_url) {
if (oauth_url != null) {
Log.e("URL", oauth_url);
auth_dialog = new Dialog(getActivity());
auth_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
auth_dialog.setContentView(R.layout.auth_dialog);
web = (WebView) auth_dialog.findViewById(R.id.webv);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl(oauth_url);
web.setWebViewClient(new WebViewClient() {
boolean authComplete = false;
#Override
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (url.contains("oauth_verifier")
&& authComplete == false) {
authComplete = true;
Log.e("Url", url);
Uri uri = Uri.parse(url);
oauth_verifier = uri
.getQueryParameter("oauth_verifier");
auth_dialog.dismiss();
new AccessTokenGet().execute();
} else if (url.contains("denied")) {
auth_dialog.dismiss();
Toast.makeText(getActivity(),
"Sorry !, Permission Denied",
Toast.LENGTH_SHORT).show();
}
}
});
auth_dialog.show();
auth_dialog.setCancelable(true);
} else {
Toast.makeText(getActivity(),
"Sorry !, Network Error or Invalid Credentials",
Toast.LENGTH_SHORT).show();
}
}
}
private class AccessTokenGet extends AsyncTask<String, String, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(getActivity());
progress.setMessage("Fetching Data ...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.show();
}
#Override
protected Boolean doInBackground(String... args) {
try {
accessToken = twitter.getOAuthAccessToken(requestToken,
oauth_verifier);
SharedPreferences.Editor edit = pref.edit();
edit.putString("ACCESS_TOKEN", accessToken.getToken());
edit.putString("ACCESS_TOKEN_SECRET",
accessToken.getTokenSecret());
User user = twitter.showUser(accessToken.getUserId());
profile_url = user.getOriginalProfileImageURL();
edit.putString("NAME", user.getName());
edit.putString("IMAGE_URL", user.getOriginalProfileImageURL());
edit.commit();
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean response) {
if (response) {
progress.hide();
Fragment profile = new ProfileFragment();
FragmentTransaction ft = getActivity().getFragmentManager()
.beginTransaction();
ft.replace(R.id.content_frame, profile);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
}
}
}
Try adding an onCancelListener for the dialog and within that set the OAuthAccessToken to null.
mAuth_dialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
sTwitter.setOAuthAccessToken(null);
}
});

Categories

Resources