Android Volley Crashing - java

I'm using Android Volley to login a user in but when addToRequestQueue is called the following crash report is shown.
The login request is carried out onclick in the Loginactivity as follows:
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String username = inputUserName.getText().toString();
String pin = inputPIN.getText().toString();
// Check for empty data in the form
if (username.trim().length() > 0 && pin.trim().length() > 0) {
// login user
SharedPreferences prefs = getGCMPreferences(context);
String storeRegId = prefs.getString(PROPERTY_REG_ID, "");
String devid = Secure.getString(getBaseContext().getContentResolver(),Secure.ANDROID_ID);
String vars = "/?tag=login&username=" + username + "&pin=" + pin + "&regid=" + storeRegId + "&devid=" + devid;
WebRequest wr = new WebRequest(context);
wr.Request(AppConfig.URL_LOGIN, vars, true, "Please Wait", "Logging in...", "req_login");
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(), "Please enter the credentials!", Toast.LENGTH_LONG).show();
}
}
});
WebRequest, which uses volley looks like this:
package app;
import helper.SQLiteHandler;
import helper.SessionManager;
import helper.dbTables;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import main.MainActivity;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.StringRequest;
import com.google.android.gms.gcm.GoogleCloudMessaging;
public class WebRequest extends Activity {
private static final String TAG = "LoginActivity";
AtomicInteger msgId = new AtomicInteger();
GoogleCloudMessaging gcm;
SharedPreferences prefs;
public SQLiteHandler db;
SessionManager session;
protected Context context;
public WebRequest(Context context){
this.context = context.getApplicationContext();
}
public void Request(final String url, final String vars, final Boolean show, final String title, final String msg, final String requestName){
final SessionManager session = new SessionManager(context);
final ProgressDialog theProgressDialog = new ProgressDialog(context);
db = new SQLiteHandler(context);
if(show == true){
theProgressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
theProgressDialog.setTitle(title);
theProgressDialog.setMessage(msg);
theProgressDialog.setIndeterminate(true);
theProgressDialog.setCancelable(false);
theProgressDialog.show();
}
StringRequest strreq = new StringRequest(Method.GET, url + vars,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "WEB Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
switch(requestName){
case "req_login":
//process user login
// Fetching user details from sqlite
HashMap<String, String> user = db.fetchResults(dbTables.TABLE_LOGIN, null);
String storedUid = user.get("uid");
JSONObject login = jObj.getJSONObject("login");
if(storedUid != login.getString("uid")){
//new user for device
String[] emptyTables = {dbTables.TABLE_LOGIN};
for(int i=0; i<emptyTables.length; i++){
db.emptyTable(emptyTables[i]);
Log.d(TAG, "empty table : " + emptyTables[i]);
}
}
//store user in database
db.addUser(login.getString("uid"),
login.getString("companyid"),
login.getString("resourceid"),
login.getString("groupid"),
login.getString("title"),
login.getString("firstname"),
login.getString("middleinitial"),
login.getString("lastname"),
login.getString("jobtitle"),
login.getString("managerid"),
login.getString("email"),
login.getString("photo_url"),
login.getString("signature_url"),
login.getString("language"),
login.getString("skin"),
login.getString("defaultprojectid"),
login.getString("cnNotifications"),
login.getString("crNotifications"),
login.getString("coNotifications"),
login.getString("addedby"),
login.getString("dateadded"),
login.getString("editedby"),
login.getString("dateedited"));
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
//finish();
break;
}
if(show == true){
theProgressDialog.dismiss();
}
}else{
String errorMsg = jObj.getString("error_msg");
Toast.makeText(context, errorMsg, Toast.LENGTH_LONG).show();
if(show == true){
theProgressDialog.dismiss();
}
}
}catch(JSONException e){
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Web Error: " + error.getMessage());
Toast.makeText(context, error.getMessage(), Toast.LENGTH_LONG).show();
if(show == true){
theProgressDialog.dismiss();
}
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strreq, requestName);
}
}
I've also included the AppController which I haven't personally changed
package app;
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}

This is no way to create a Activity object. A lot get go wrong
like this.
Activity is a context therefore he doesnt need to hold a context
as a member. That is a common memory leak.
The activity doesnt go trough the proper life cycle and that is why
everything blows up.
I would suggest to you to start from the basic because when you will do this everything will be clearer.

The AppController isn't neccessary in creating a request using volley......Just add the request in volley android volley request.....https://www.simplifiedcoding.net/android-volley-post-request-tutorial/.......

The way you sends the request will determine if the app crashes.....one, the Sqlite will make the application crashes if the request is sent properly...

Related

Login button need to be clicked twice in order to login

I am making an attendance app on android studio, but whenever I try to log in using correct credentials I need to click twice on the login button to move forward to the next activity. I tried Asynctasks because of its background thread, after the same result I just reverted back
So, at first click nothing happens but as soon as please wait dialog box disappears and if I click like in under a second or two then it moves to the next activity.
clicking on login fetches some data from the server after the server has validated that the login exists and is correct. when data is received then the new activity is supposed to start since that received data will be shown in the next activity. (i have a list that is checked if it has data then it moves forward)
Login Activity code:
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
//sign up and login button
private Button btnSignUp;
private Button btnLogin;
private ProgressDialog progressDialog;
private RequestQueue Queue;
//data URL
private String extractStudentDataURL = "https://asuiot12.000webhostapp.com/checkLoginCredentials.php";
private String extractEnrolmentsDataURL = "https://asuiot12.000webhostapp.com/retrieveEnrolledCoursesData.php";
//editText
private EditText editTextEmail, editTextPassword;
private ConstraintLayout login;
//string variables
public static String inputEmail;
private String inputPassword;
//array list to store enrolled courses data
public static LinkedList<Courses> enrolledCoursesData = new LinkedList();
//static variable
public static StudentData studentData;
//shared preferences to maintain the login status of the user...
public static SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = findViewById(R.id.login_activity);
login.setBackgroundColor(Color.WHITE);
btnSignUp = findViewById(R.id.button_sign_up);
btnLogin = findViewById(R.id.button_login);
// sp = getSharedPreferences("login", MODE_PRIVATE);
editTextEmail = findViewById(R.id.editText_RA_emailAddress);
editTextPassword = findViewById(R.id.editText_RA_password);
//login button listener
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputEmail = editTextEmail.getText().toString();
inputPassword = editTextPassword.getText().toString();
if (inputEmail.isEmpty()) {
editTextEmail.setError("Email Required");
editTextEmail.requestFocus();
} else if (inputPassword.isEmpty()) {
editTextPassword.setError("Password Required");
editTextPassword.requestFocus();
} else {
enrolledCoursesData.clear();
ExtractData();
}
}
});
//signUp button listener
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
startActivityForResult(intent, 1);
}
});
}
//retrieving data from the server and checking the login credentials
private void ExtractData() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, extractStudentDataURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject data = array.getJSONObject(i);
int success = data.getInt("success");
if (success == 1) {
Long CNIC = data.getLong("CNIC");
String name = data.getString("Full_Name");
String fss = data.getString("FSS");
String regNo = data.getString("Reg_No");
String batch = data.getString("Batch");
String department = data.getString("Department");
int semester = data.getInt("Semester");
Long mobileNo = data.getLong("Mobile_No");
String nationality = data.getString("Nationality");
String MACAddress = data.getString("MAC_Address");
String homeAddress = data.getString("Home_Address");
String email = data.getString("Email");
String loginPassword = data.getString("Login_Password");
String photo = data.getString("Photo");
studentData = new StudentData(new BigInteger(String.valueOf(CNIC)), new BigInteger(String.valueOf(mobileNo))
, semester, name, fss, regNo, batch, department, nationality,
MACAddress, homeAddress, email, loginPassword, photo);
Toast.makeText(MainActivity.this, "Plz wait....", Toast.LENGTH_LONG).show();
// to get data of courses in which student is enrolled
extractDataOfEnrolments(email);
if (!enrolledCoursesData.isEmpty()) {
Intent intent = new Intent(MainActivity.this, CoursesActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("list", enrolledCoursesData);
intent.putExtras(bundle);
startActivity(intent);
}
} else if (success == 0) {
Toast.makeText(MainActivity.this, "Incorrect username or password",
Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error " + error, Toast.LENGTH_SHORT).show();
}
}) {
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", editTextEmail.getText().toString().trim());
params.put("password", editTextPassword.getText().toString().trim());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
//retrieving data of enrolments from server
private void extractDataOfEnrolments(final String email) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, extractEnrolmentsDataURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject data = array.getJSONObject(i);
String courseCode = data.getString("Course_Code");
String courseName = data.getString("Course_Name");
Courses courses = new Courses(courseCode, courseName);
enrolledCoursesData.add(courses);
}
} catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error " + error, Toast.LENGTH_SHORT).show();
}
}) {
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
If layout code or server-side PHP code is required to better understand the question, then please do ask.
You have a misunderstanding as to how threading works.
In your ExtractData method and its onResponse handler, you call extractDataOfEnrolments(), which is itself asynchronous:
// to get data of courses in which student is enrolled
extractDataOfEnrolments(email);
// the list hasn't been filled yet, will be empty!!!
if (!enrolledCoursesData.isEmpty()) {
}
You then immediately inspect the enrolledCoursesData list and start the CoursesActivity if not empty. The extractDataOfEnrolments() has an asynchronous callback (onResponse()) that hasn't completed yet, so the list would be empty.
You might consider moving the startActivity code into extractDataOfEnrolments(), e.g.:
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject data = array.getJSONObject(i);
String courseCode = data.getString("Course_Code");
String courseName = data.getString("Course_Name");
Courses courses = new Courses(courseCode, courseName);
enrolledCoursesData.add(courses);
}
// now your list is populated, so now Ok to startActivity
if (!enrolledCoursesData.isEmpty()) {
Intent intent = new Intent(MainActivity.this, CoursesActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("list", enrolledCoursesData);
intent.putExtras(bundle);
startActivity(intent);
}
} catch (Exception e) {
}

Change screen after successful login? (Android studio)

I've been tasked during my internship to take over someone else's code and work on a project.I am having difficulties trying to navigate to another screen after a successful login.Currently, the code below redirects me back to the original main menu page after a successful login (While a failed login does nothing).
My question is how do I display a toast message saying wrong username/password?
Currently it displays nothing during a failed login.Also, how do I change screens from activity_login.xml to landing_page.xml after a SUCCESSFUL login? What code should I add?
LoginActivity.java :
package com.finchvpn.androidcloudpark;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Objects;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class LoginActivity extends AppCompatActivity {
private EditText textUsername;
private EditText txtPassword;
private static RestClient restClient = new RestClient();
private SharedPreferences.Editor sharedPreferencesEditor;
#SuppressLint("CommitPrefEdits")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
try {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
} catch (Exception e) {
}
textUsername = findViewById(R.id.textUsername);
txtPassword = findViewById(R.id.textPassword);
SharedPreferences sharedPreferences = getSharedPreferences("UserInfo", 0);
sharedPreferencesEditor = sharedPreferences.edit();
textUsername.setText(sharedPreferences.getString("textUsername", ""));
txtPassword.setText(sharedPreferences.getString("txtPassword", ""));
}
public static RestClient getRestClient() {
return restClient;
}
public void loginButtonClick(View v) {
if (!textUsername.getText().toString().equals("") && !txtPassword.getText().toString().equals("")) {
apiPostLogin(Constants.ANDROID_KEY + ":" + textUsername.getText().toString() + ":" + txtPassword.getText().toString());
sharedPreferencesEditor.putString("textUsername", textUsername.getText().toString());
sharedPreferencesEditor.putString("txtPassword", txtPassword.getText().toString());
sharedPreferencesEditor.commit();
} else {
Toast.makeText(LoginActivity.this, "NULL", Toast.LENGTH_LONG).show();
}
}
private void apiPostLogin(String data) {
final ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Logging in");
progress.setMessage("Please wait ...");
progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
progress.show();
Call<ResponseBody> call = getRestClient().getLoginService().postLogin(data);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful() && response.body() != null) {
try {
String data = response.body().string();
JSONObject jsonObject = new JSONObject(data);
Constants.uid = Integer.parseInt(jsonObject.getString("id"));
Constants.username = jsonObject.getString("username");
Constants.email = jsonObject.getString("email");
Constants.credit = jsonObject.getString("credit");
Constants.qr_code = jsonObject.getString("qr_code");
Constants.created_at = jsonObject.getString("created_at");
Constants.updated_at = jsonObject.getString("updated_at");
Toast.makeText(LoginActivity.this, "apiPostLogin onResponse <<<< \r\n\r\n" + jsonObject.toString(), Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
progress.dismiss();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(LoginActivity.this, "Incorrect username/password, please try again." + t.getMessage(), Toast.LENGTH_LONG).show();
progress.dismiss();
}
});
}
}
First of all, for changing your activity layout you have to change this line of code in the onCreate method:
setContentView(R.layout.activity_login);
Second, to display toast if the login fails, change your apiPostLogin method to:
private void apiPostLogin(String data) {
final ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Logging in");
progress.setMessage("Please wait ...");
progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
progress.show();
Call<ResponseBody> call = getRestClient().getLoginService().postLogin(data);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful() && response.body() != null) {
try {
String data = response.body().string();
JSONObject jsonObject = new JSONObject(data);
Constants.uid = Integer.parseInt(jsonObject.getString("id"));
Constants.username = jsonObject.getString("username");
Constants.email = jsonObject.getString("email");
Constants.credit = jsonObject.getString("credit");
Constants.qr_code = jsonObject.getString("qr_code");
Constants.created_at = jsonObject.getString("created_at");
Constants.updated_at = jsonObject.getString("updated_at");
Toast.makeText(LoginActivity.this, "apiPostLogin onResponse <<<< \r\n\r\n" + jsonObject.toString(), Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
} else {
//
//
//This scope runs where the login fails
}
progress.dismiss();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(LoginActivity.this, "Incorrect username/password, please try again." + t.getMessage(), Toast.LENGTH_LONG).show();
progress.dismiss();
}
});
}
If you are starting this loginactivity using startActivityForResult then handle the response from onActivityResult method in your calling activity.
And
setResult(Activity.RESULT_CANCELED, returnIntent);
this should be
setResult(Activity.RESULT_OK, returnIntent);

cannot resolve method 'addToRequestQueque(com.android.volley.toolbox.StringRequest,java.lang.String)'

Im going to make a database in php my sql using android studio
but this error is in the way
//Adding request to request queue
AndroidLoginController.getInstance();
addToRequestQueue(strReq, tag_string_req);
}
I receive the error cannot resolve method 'addToRequestQueque(com.android.volley.toolbox.StringRequest,java.lang.String)'
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.pjsr.brnp.MainActivity;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import prefs.UserInfo;
import prefs.UserSession;
public class Login extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = Login.class.getSimpleName();
private EditText email, password;
private Button login;
private TextView signup;
private ProgressDialog progressDialog;
private UserSession session;
private UserInfo userInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
signup = (TextView) findViewById(R.id.open_signup);
progressDialog = new ProgressDialog(this);
session = new UserSession(this);
userInfo = new UserInfo(this);
if (session.isUserLoggedin()) {
startActivity(new Intent(this, MainActivity.class));
finish();
}
login.setOnClickListener(this);
signup.setOnClickListener(this);
}
private void login(final String email, final String password) {
//Tag used to cancel the request
String tag_string_req = "req_login";
progressDialog.setMessage("Logging in....");
progressDialog.show();
StringRequest strReq = new StringRequest(Request.Method.POST,
Utils.LOGIN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
//check for error node in json
if (!error) {
//now store the user in SQLite
JSONObject user = jObj.getJSONObject("user");
String uName = user.getString("username");
String email = user.getString("email");
//Inserting row in users table
userInfo.setEmail(email);
userInfo.setUsername(uName);
session.setLoggedin(true);
startActivity(new Intent(Login.this, MainActivity.class));
finish();
} else {
//error in login, get the error message
String errorMsg = jObj.getString("error_msg");
toast(errorMsg);
}
} catch (JSONException e) {
//json error
e.printStackTrace();
toast("Json error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
toast("Unknown Error occured");
progressDialog.hide();
}
}) {
#Override
protected Map<String, String> getParams() {
//Posting parameters to login url
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
//Adding request to request queue
AndroidLoginController.getInstance();
addToRequestQueue(strReq, tag_string_req);
}
private void toast(String x) {
Toast.makeText(this, x, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login:
String uName = email.getText().toString().trim();
String pass = password.getText().toString().trim();
login(uName, pass);
break;
case R.id.open_signup:
startActivity(new Intent(this, SignUp.class));
break;
}
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Login Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
}
addToRequestQueue is a method defined for the volley application controller which seems to be AndroidLoginController in your case. Change the line to
AndroidLoginController.getInstance().addToRequestQueue(strRe‌​q,tag_string_req)
This is assuming you have created the singleton using standard volley tutorials or android developer documentation

how to get meetup access token on android, via oauth 2

my app needs to get user's meetup id. meetup uses oauth 2.0. found different pieces of code across the web, will paste in stackoverflow as answer to this question, for the next person.
import a library via graddle build file:
dependencies {
compile 'net.smartam.leeloo:oauth2-common:0.1'
compile 'net.smartam.leeloo:oauth2-client:0.1'
}
create a class for meetup authenticating. this class written by adrianmaurer (https://gist.github.com/adrianmaurer/4673944), thank you adrianmaurer!
MeetupAuthActivity:
package pixtas.com.nightout;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
// leeloo oAuth lib https://bitbucket.org/smartproject/oauth-2.0/wiki/Home
import net.smartam.leeloo.client.OAuthClient;
import net.smartam.leeloo.client.URLConnectionClient;
import net.smartam.leeloo.client.request.OAuthClientRequest;
import net.smartam.leeloo.client.response.OAuthAccessTokenResponse;
import net.smartam.leeloo.client.response.OAuthAuthzResponse;
import net.smartam.leeloo.common.exception.OAuthProblemException;
import net.smartam.leeloo.common.exception.OAuthSystemException;
import net.smartam.leeloo.common.message.types.GrantType;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
/**
* Created by tmr_byronMac on 4/24/15.
*/
public class MeetupAuthActivity extends Activity {
private final String TAG = getClass().getName();
// Meetup OAuth Endpoints
public static final String AUTH_URL = "https://secure.meetup.com/oauth2/authorize";
public static final String TOKEN_URL = "https://secure.meetup.com/oauth2/access";
// Consumer
//public static final String REDIRECT_URI_SCHEME = "oauthresponse";
//public static final String REDIRECT_URI_HOST = "com.yourpackage.app";
//public static final String REDIRECT_URI_HOST_APP = "yourapp";
//public static final String REDIRECT_URI = REDIRECT_URI_SCHEME + "://" + REDIRECT_URI_HOST + "/";
public static final String REDIRECT_URI = "NightOut://meetup.com";
public static final String CONSUMER_KEY = "YOUR_KEY";
public static final String CONSUMER_SECRET = "YOUR_SECRET";
private WebView _webview;
private Intent _intent;
private Context _context;
public void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
_intent = getIntent();
_context = getApplicationContext();
_webview = new WebView(this);
_webview.setWebViewClient(new MyWebViewClient());
setContentView(_webview);
_webview.getSettings().setJavaScriptEnabled(true);
OAuthClientRequest request = null;
try {
request = OAuthClientRequest.authorizationLocation(
AUTH_URL).setClientId(
CONSUMER_KEY).setRedirectURI(
REDIRECT_URI).buildQueryMessage();
} catch (OAuthSystemException e) {
Log.d(TAG, "OAuth request failed", e);
}
_webview.loadUrl(request.getLocationUri() + "&response_type=code&set_mobile=on");
}
public void finishActivity() {
//do something here before finishing if needed
finish();
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
String code = uri.getQueryParameter("code");
String error = uri.getQueryParameter("error");
if (code != null) {
new MeetupRetrieveAccessTokenTask().execute(uri);
// setResult(RESULT_OK, _intent);
// finishActivity();
} else if (error != null) {
setResult(RESULT_CANCELED, _intent);
finishActivity();
}
return false;
}
}
private class MeetupRetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {
#Override
protected Void doInBackground(Uri... params) {
Uri uri = params[0];
String code = uri.getQueryParameter("code");
OAuthClientRequest request = null;
try {
request = OAuthClientRequest.tokenLocation(TOKEN_URL)
.setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(
CONSUMER_KEY).setClientSecret(
CONSUMER_SECRET).setRedirectURI(
REDIRECT_URI).setCode(code)
.buildBodyMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthAccessTokenResponse response = oAuthClient.accessToken(request);
// do something with these like add them to _intent
// Intent returnIntent = new Intent();
// returnIntent.putExtra("access_token", response.getAccessToken());
// setResult(RESULT_OK,returnIntent);
Log.d(TAG, "access token: " + response.getAccessToken());
Log.d(TAG, response.getExpiresIn());
Log.d(TAG, response.getRefreshToken());
_intent.putExtra("access_token", response.getAccessToken());
setResult(RESULT_OK, _intent);
finish();
} catch (OAuthSystemException e) {
Log.e(TAG, "OAuth System Exception - Couldn't get access token: " + e.toString());
Toast.makeText(_context, "OAuth System Exception - Couldn't get access token: " + e.toString(), Toast.LENGTH_LONG).show();
} catch (OAuthProblemException e) {
Log.e(TAG, "OAuth Problem Exception - Couldn't get access token");
Toast.makeText(_context, "OAuth Problem Exception - Couldn't get access token", Toast.LENGTH_LONG).show();
}
return null;
}
}
#Override
public void onBackPressed()
{
setResult(RESULT_CANCELED, _intent);
finishActivity();
}
}
call MeetupAuthActivity from your main activity.
MainActivity:
public void getMeetupAccessToken(){
Intent intent;
intent = new Intent(this, MeetupAuthActivity.class);
// startActivity(intent);
startActivityForResult(intent,GET_MEETUP_ACCESS_TOKEN_ACTIVITY);
}
in MainActivity, capture the results form auth activity.
MainActivity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// if(requestCode == 1 && resultCode == RESULT_OK)
if(requestCode == GET_MEETUP_ACCESS_TOKEN_ACTIVITY)
{
accessToken = data.getExtras().getString("access_token");
saveMeetupAccessTokenToSharedPreferences();
//save meetupid plus device id to parse
getMyMeetupIdFromMeetupServer();
// Log.i(DEBUG_TAG,"MainActivity, accessToken" + accessToken);
}
}

Google Cloud messaging service returning empty registration id

I'm running into an issue implementing Google Cloud Messaging. When i try to register my emulator i'm suppost to get the Registration ID of the device, which in this case is my emulator. So when i looked around i saw i needed to link a google account so i did that but i still have the same issue. it returns that it is a new registration but the registration id is empty. could someone help me in the right direction? If you need to know anything else let me know. Thanks in advance
Code:
LoginActivity.java
package com.vict.voffice;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.vict.voffice.utilities.Dialogs;
import com.vict.voffice.utilities.GCMClientManager;
import com.vict.voffice.utilities.UserDetailCache;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class LoginActivity extends Activity {
EditText mNaam;
EditText mVersie;
EditText mWachtwoord;
String PROJECT_NUMBER = "##########";
private GCMClientManager pushClientManager;
private Context cont = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
cont = this;
pushClientManager = new GCMClientManager(this, PROJECT_NUMBER);
mNaam = (EditText)findViewById(R.id.editText_login);
mVersie = (EditText)findViewById(R.id.editText_bedrijf);
mWachtwoord = (EditText)findViewById(R.id.editText_wachtwoord);
final Button button = (Button) findViewById(R.id.btnLogin);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
#Override
public void onSuccess(String registrationId, boolean isNewRegistration) {
//Dialogs.LoginDialog(cont).show();
Toast.makeText(getApplicationContext(), "Regid: "+registrationId+" "+isNewRegistration, Toast.LENGTH_SHORT).show();
//Login(mNaam.getText().toString(), mWachtwoord.getText().toString(), mVersie.getText().toString(), pushClientManager.getRegistrationId(cont));
}
#Override
public void onFailure(String ex) {}});
Log.d("DBG", "Login Pressed");
}
});
Log.d("DBG", ""+UserDetailCache.GetNodeFromFile(cont));
if(UserDetailCache.GetNodeFromFile(cont) != null || UserDetailCache.GetNodeFromFile(cont) != "" || UserDetailCache.GetNodeFromFile(cont) != "null" || UserDetailCache.GetNodeFromFile(cont).isEmpty()){
if(UserDetailCache.GetUserNameFromFile(cont) != null || UserDetailCache.GetUserNameFromFile(cont) != "" || UserDetailCache.GetUserNameFromFile(cont) != "null"){
if(UserDetailCache.GetPasswordFromFile(cont) != null || UserDetailCache.GetPasswordFromFile(cont) != "" || UserDetailCache.GetPasswordFromFile(cont) != "null"){
Log.d("DBG", "Filling Fields from DB");
mNaam.setText(UserDetailCache.GetUserNameFromFile(getApplicationContext()));
mWachtwoord.setText(UserDetailCache.GetPasswordFromFile(getApplicationContext()));
mVersie.setText(UserDetailCache.GetNodeFromFile(getApplicationContext()));
button.performClick();
}else{
Log.d("DBG", "No Password");
}
}else{
Log.d("DBG", "No Username");
}
}else{
Log.d("DBG", "No Node");
}
}
#Override
public void onBackPressed(){
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
super.onBackPressed();
System.exit(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void Login(String Username, String Password, String Node, String Token){
class LoginAsyncTask extends AsyncTask<String, Void, String>{
UserDetailCache Dtc = new UserDetailCache();
String uniqueKey = "";
#Override
protected void onPreExecute(){
super.onPreExecute();
//Dialogs.LoginDialog(getApplicationContext()).show();
}
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramPassword = params[1];
String paramVersion = params[2];
uniqueKey = params[3];
Log.d("LoginActivity", "Token: " + uniqueKey);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://node11.voffice.nl/login/appcheck.asp?login=" + paramUsername + "&wachtw=" + paramPassword + "&versie=" + paramVersion + "&token=" + uniqueKey);
//Log.e("HTTP", "send link: " + httpPost.getURI());
try{
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
}catch (ClientProtocolException cpe){
// Log.e("HTTP", "First Exception, httpResponse : " + cpe);
cpe.printStackTrace();
}catch (IOException ioe){
// Log.e("HTTP", "Second Exception, httpResonse : " + ioe);
ioe.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Log.e("HTTP", "Server Responded with : " + result);
String splitResult[] = result.split("\\|");
if(splitResult[0].equals("OK") && splitResult != null){
String tempCompany = splitResult[1].substring(8);
User usr = new User(splitResult[1], tempCompany, splitResult[2], uniqueKey, splitResult[4], splitResult[3]);
Dialogs.LoginDialog(getApplicationContext()).hide();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(intent, 0);
}else{
Dialogs.TextDialog(getApplicationContext(), "Verkeerde Logingegeven", Toast.LENGTH_LONG);
Dialogs.LoginDialog(getApplicationContext()).hide();
}
Dialogs.TextDialog(getApplicationContext(), "", Toast.LENGTH_LONG);
Dialogs.LoginDialog(getApplicationContext()).hide();
}
}
LoginAsyncTask Logintask = new LoginAsyncTask();
Logintask.execute(Username, Password, Node, Token);
}
}
GCMClientManager.java
package com.vict.voffice.utilities;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.io.IOException;
/**
* Created by Kevin on 3/3/2015.
*/
public class GCMClientManager {
// Constants
public static final String TAG = "GCMClientManager";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "6";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
// Member variables
private GoogleCloudMessaging gcm;
private String regid;
private String projectNumber;
private Activity activity;
public static abstract class RegistrationCompletedHandler {
public abstract void onSuccess(String registrationId, boolean isNewRegistration);
public void onFailure(String ex) {
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
Log.e(TAG, ex);
}
}
public GCMClientManager(Activity activity, String projectNumber) {
this.activity = activity;
this.projectNumber = projectNumber;
this.gcm = GoogleCloudMessaging.getInstance(activity);
}
// Register if needed or fetch from local store
public void registerIfNeeded(final RegistrationCompletedHandler handler) {
if (checkPlayServices()) {
regid = getRegistrationId(getContext());
if (regid.isEmpty()) {
registerInBackground(handler);
} else { // got id from cache
Log.i(TAG, regid);
handler.onSuccess(regid, false);
}
} else { // no play services
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and app versionCode in the application's
* shared preferences.
*/
private void registerInBackground(final RegistrationCompletedHandler handler) {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getContext());
}
regid = gcm.register(projectNumber);
Log.i(TAG, regid);
// Persist the regID - no need to register again.
storeRegistrationId(getContext(), regid);
} catch (IOException ex) {
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
handler.onFailure("Error :" + ex.getMessage());
}
return regid;
}
#Override
protected void onPostExecute(String regId) {
if (regId != null) {
handler.onSuccess(regId, true);
}
}
}.execute(null, null, null);
}
/**
* Gets the current registration ID for application on GCM service.
* <p>
* If result is empty, the app needs to register.
*
* #return registration ID, or empty string if there is no existing
* registration ID.
*/
public String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* Stores the registration ID and app versionCode in the application's
* {#code SharedPreferences}.
*
* #param context application's context.
* #param regId registration ID
*/
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
/**
* #return Application's version code from the {#code PackageManager}.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
private SharedPreferences getGCMPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the regID in your app is up to you.
return getContext().getSharedPreferences(context.getPackageName(),
Context.MODE_PRIVATE);
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
}
return false;
}
return true;
}
private Context getContext() {
return activity;
}
private Activity getActivity() {
return activity;
}
}
Try to set your emulator target to Google API and add a google
account.(add account on emulator: setting->account&sync)

Categories