Android NullPointerException when using Volley library - java

I have been following a tutorial (http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/) and when running the code for registration a encounter a nullpointerexception.
02-11 16:40:57.795: E/AndroidRuntime(1024): java.lang.NullPointerException
02-11 16:40:57.795: E/AndroidRuntime(1024): at activity.RegisterActivity.registerUser(RegisterActivity.java:209)
The following line of code is what causes the issue
ApplicationController.getInstance().addToRequestQueue(strReq, tag_string_req);
Because when I comment it out, everything runs find - well apart from the fact it stays stuck on the "registering spinner"
The code below is the RegisterUser method.
StringRequest strReq = new StringRequest(Method.POST,ApplicationServicesConfig.Register_URL, 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) {
JSONObject user = jObj.getJSONObject("user");
String id = user.getString("id");
String name = user.getString("name");
String email = user.getString("email");
String dob = user.getString("dob");
String gender = user.getString("gender");
String created_at = user.getString("created_at");
db.addUser(name, email, dob, gender, created_at);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).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("name", name);
params.put("email", email);
params.put("dob", dob);
params.put("gender", gender);
params.put("password", password);
Log.d(TAG, "params: " + params);
return params;
}
#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");
return params;
}
};
// Adding request to request queue
ApplicationController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
My initial thoughts was that within the application controller class I was never actually creating a request queue (hence the null pointer exception).
Although within the .addToRequestQueue, one is created.
Code supplied for reference:
public class ApplicationController extends Application {
public static final String TAG = ApplicationController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static ApplicationController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized ApplicationController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
Log.d(TAG, "request queue" + mRequestQueue);
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
Log.d(TAG ,"Within top request queue");
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
Log.d(TAG ,"Within bottom requeuest queue");
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
I have also (as you can see) placed some Logging within the Volley functionality, however that never gets called.
I'm hoping I'm just being ignorant,
Any ideas?

Thanks to #NguyenQuangAnh I realised that I didn't specify that ApplicationController is applications class.
I also looked on this page http://rominirani.com/android-application-class/ where I learn't more.
Basically: Updated android manifest
<application
android:allowBackup="true"
android:label="#string/app_name"
android:icon="#drawable/icon"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:name="app.ApplicationController" >
(Before you specify activities etc)

Related

Accessing method from activity that will start another activity from a class

Hi i'm developing an app that will use a fingerprint authentication to login, I create a class named FingerprintHandler and from that class i'm calling a method that will start another activity if fingerprint auth succeed, i also tried passing the context to the method but i still get an null object reference
FingerprintHanlder Class
#TargetApi(Build.VERSION_CODES.M)
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
private Context context;
public FingerprintHandler(Context context){
this.context = context;
}
public void startAuth(FingerprintManager fingerprintManager, FingerprintManager.CryptoObject cryptoObject){
CancellationSignal cancellationSignal = new CancellationSignal();
fingerprintManager.authenticate(cryptoObject, cancellationSignal,0, this,null);
}
private void update(String s, boolean b){
MainActivity m = new MainActivity();
EditText etEmail,etPassword;
TextView tvFeedback = (TextView) ((Activity)context).findViewById(R.id.tvFeedback);
tvFeedback.setText(s);
if(b == false) {
tvFeedback.setTextColor(ContextCompat.getColor(context,R.color.colorAccent));
} else {
tvFeedback.setTextColor(ContextCompat.getColor(context,R.color.colorPrimary));
m.login(context.getApplicationContext(),context,"user","password");
}
}
}
MainActivity Class Method
public void login(final Context c1,final Context c, final String user, final String password) {
dialog = new ProgressDialog(c);
dialog.setMessage("Authenticating ...");
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, dBhelper.URL + "app-ess-login", new Response.Listener<String>() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onResponse(String response) {
Log.d("test: ", response);
try {
JSONObject collections = new JSONObject(response);
is_auth = collections.getInt("auth");
JSONArray jsonArrayUsers = collections.getJSONArray("user");
if(is_auth > 0) {
dBhelper.truncate();
for(int x = 0; x < jsonArrayUsers.length(); x++) {
JSONObject user = jsonArrayUsers.getJSONObject(x);
dBhelper.insertData(user.getInt("id"), user.getString("formal_name"), user.getString("email"), user.getString("job_title_name"), user.getString("schedule"));
}
dBhelper.username = user;
dBhelper.password = password;
dialog.dismiss();
Intent intent = new Intent(c, BundyClock.class);
startActivity(intent);
finish();
} else {
Toast.makeText(c, "Incorrect Email or Password", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(c, "Error: " + error, Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("email", user);
params.put("password", password);
return params;
}
};
com.example.ess.AppController.getInstance().addToRequestQueue(stringRequest);
}
Thank you so much
You are calling startActivity(intent) And this is where you see the error. Why are you seeing this error?
You are calling MainActivity m = new MainActivity(); and m.login(). Activities are not a regular Java class and you need a lot of inheritance (BaseContext, etc) to make it work correctly. If you want to use the activity, you need to call startActivity(Intent) so it has all the necessary inheritance.
Since you are not starting MainActivity, it does not have proper context. When you call startActivity(intent) in your onResponse callback, it throws Null Pointer Exception as it does not have proper context.
How to fix this?
Do not use m.login(). You should move this method to some other class (not an activity). or make login a static method so that it is no tied to the MainActivity.
Use context.startActivity(intent) since you are passing context in login method.

How to create a single volley webservice class to use across the android app?

My android application uses multiple network calls in a single activity and i have several of these activities where i have to use both post and get requests. I want to create a single "VolleyWebservice" class and call the same in multiple activities instead of writing the complete volley code. I am relatively new to android development and i don't understand where i am going wrong.
public class VolleyWebService {
public JSONObject result;
public JSONObject getResponse(String url, Context mContext) {
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
result = response;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
mQueue.add(request);
return result;
}
}
The method in My activity where i am calling this class
private void callFunctionGetDist() {
ProgressDialog progressDialog;
progressDialog = ProgressDialog.show(recorddata.this, "", "Please Wait...", true);
JSONObject response = new VolleyWebService().getResponse(urlConfigClass.GET_DISTRICT, this);
try {
if(response.toString().contains("Status:Success,Details")){
arrDistName.clear();
arrDistCode.clear();
arrDistName.add("Select District Name");
arrDistCode.add("Select District Code");
JSONArray jsonArray = response.getJSONArray("Status:Success,Details");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jobJ = jsonArray.getJSONObject(i);
String scheName = jobJ.getString("post");
JSONObject jobJDist = new JSONObject(scheName);
String distname = jobJDist.getString("District");
String distcode = jobJDist.getString("DistrictCode");
arrDistName.add(distname);
arrDistCode.add(distcode);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(recorddata.this,
R.layout.custom_textview_to_spinner, arrDistName);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
district.setAdapter(dataAdapter);
progressDialog.dismiss();
}else{
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Response is null or empty", Toast.LENGTH_LONG).show();
}
} catch (Exception volleyError) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
}
I tried creating the same class but i am not able to get the response to other activities. Although i am getting the correct response in the Volley jsonbject response, the response return null in other activities.
I want to have the result object return the response in my recorddata activity
This is what i have tried so far, no luck though!
public void postResponse (String url, Context mContext, final VolleyResponseListener listener) {
try {
String encodedUrl = url.replace(" ", "%20") + "";
if (encodedUrl.contains("("))
encodedUrl = encodedUrl.replace("(", "%28");
if (encodedUrl.contains(")"))
encodedUrl = encodedUrl.replace(")", "%29");
encodedUrl = encodedUrl.replace(" ", "%20");
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POst, encodedUrl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
listener.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error);
}
}) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
};
mQueue.add(request);
} catch (Exception e) {
e.printStackTrace();
}
}
For the sake of achieving your goal, (without taking in to consideration architecture and coding principles), you can pass a callback:
public class VolleyWebService {
public interface VolleyResponseListener {
void onSuccess(JSONObject response);
void onError(VolleyError error);
}
public JSONObject result;
public JSONObject getResponse(String url, Context mContext, VolleyResponseListener listener) {
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
listener.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error);
}
});
mQueue.add(request);
return result;
}
}
To use it:
volleyWebService.getResponse("your url", context, new VolleyResponseListener() {
#Override
void onSuccess(JSONObject response) {
//do what you want on success
}
#Override
void onError(VolleyError error) {
//do what you want on error
}
});

What would be the simplest way of posting data using Volley?

I am trying to use Volley to send 3 strings to a php script that sends it to a localhost server. I have this so far;
RegisterRequest;
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://192.168.*.*:80/phptesting/Register.php";
private Map<String, String> params;
public RegisterRequest(String username, String password,String isAdmin,
Response.Listener<String> listener,
Response.ErrorListener errListener){
super(Method.POST, REGISTER_REQUEST_URL,listener,errListener);
params = new HashMap<>();
params.put("username",username);
params.put("password",password);
params.put("isAdmin",isAdmin+"");
}
public Map<String, String> getparams() {
return params;
}
}
This is CreateUser;
public class CreateUser extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_user);
this.setTitle("Create User");
final EditText username1 = findViewById(R.id.Createusername);
final EditText password1 = findViewById(R.id.CreatePassword);
final Switch isAdmin = findViewById(R.id.isadmin);
final Button createuser = findViewById(R.id.createuserbtn);
if (getIntent().hasExtra("com.example.northlandcaps.crisis_response")){
isAdmin.setVisibility(View.GONE);
}
createuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = username1.getText().toString();
final String password = password1.getText().toString();
final String isadmin = isAdmin.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response Value: ", response);
if (response.equals("success")){
Intent intent = new Intent(CreateUser.this, MainActivity.class);
CreateUser.this.startActivity(intent);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(CreateUser.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry",null)
.create()
.show();
}
}
};Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), String.valueOf(error), Toast.LENGTH_SHORT).show();
}
};
RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,responseListener,errorListener);
RequestQueue queue = Volley.newRequestQueue(CreateUser.this);
queue.add(registerRequest);
}
});
}
Now, the only error im getting is an Undefined index. And thats because Volley isnt sending data to the php script. The php script does work properly when data is sent to it, so my question is this; what changes do i have to make to my script for it to send the 3 strings over?
Never mess with code or else it will be confusing for you to handle things properly.
So just make another class and use it in your activity.
Have a look at this class I have written, you can use it anywhere and for any type of data request.
public class SendData {
private Context context;
private String url;
private HashMap<String, String> data;
private OnDataSent onDataSent;
public void setOnDataSent(OnDataSent onDataSent) {
this.onDataSent = onDataSent;
}
public SendData(Context context, String url, HashMap<String, String> data) {
this.context = context;
this.url = url;
this.data = data;
}
public void send(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(onDataSent != null){
onDataSent.onSuccess(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(onDataSent != null){
onDataSent.onFailed(error.toString());
}
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.putAll(data);
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, 0, 0));
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
public interface OnDataSent{
void onSuccess(String response);
void onFailed(String error);
}
}
And now you can easily use it from any activity. Just give data in the constructor and use the interface to track the events this way
HashMap<String, String> data = new HashMap<>();
data.put("username", "");//define the value
data.put("password", "");//define the value
data.put("is_admin", "");//define the value
SendData sendData = new SendData(this, "", data); //defie the context and url properly
sendData.setOnDataSent(new SendData.OnDataSent() {
#Override
public void onSuccess(String response) {
//parse the response
}
#Override
public void onFailed(String error) {
//something went wrong check the error
}
});
sendData.send();

String Request To Post not showing any error

I am making a post request in Android studio using string request, when I debug,i get no error. I don't get the JSON object in the code when i debug. It skips the login request and debug is ended.if I'm not doing something correct.please try and correct it
This is the JSON object
{"RESPONSECODE":200,
"RESPONSEDATA:[{"id_User":"120","FirstName":"King",
"LastName":"Dosty","Role_Id":"2","Email":"donmister5000#gmail.com","location":null,"Password":"$2y$10$fJJH6qOuhhXaDadHQhZefemBwHPZ3aHid\/WF579DwVJo8XyVGaEN6",
}],"Success":true}
This is the loginRequest java class
public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL = "http://localhost/project/index.php/clientapinew/post_login2";
private Map<String, String> params;
public LoginRequest(String Email,String Password, Response.Listener<String> listener){
super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("Email", Email);
params.put("Password", Password);
}
#Override
public Map<String, String> getParams(){
return params;
}
}
This is the login button to sent the request on click in the activity
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Email = emailEdt.getText().toString();
String Password = passwordEdt.getText().toString();
LoginRequest loginRequest = new LoginRequest(Email, Password,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
Log.d(TAG, jsonResponse.getString("SUCCESS"));
boolean success = jsonResponse.getBoolean("SUCCESS");
if (success)
{
Intent intent = new Intent (LoginActivity.this,MainActivity.class);
startActivity(intent);
Toast.makeText(LoginActivity.this, "Login Successful",
Toast.LENGTH_SHORT).show();}
else {
AlertDialog.Builder builder = new
AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed").setNegativeButton("Retry", null)
.create().show();
}
}
catch (JSONException e)
{ e.printStackTrace();}}
});
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
This is the url get and the params when i debug
[ ] localhost/project/index.php/clientapinew/post_login2
0x59c3b57d NORMAL null
Email : john#gmail.com
Password: azerty
I'd suggest you ditch the LoginRequest Class, and add this method in your LoginActivity:
private void login(final String email, final String password){
String LOGIN_REQUEST_URL = "http://localhost/project/index.php/clientapinew/post_login2";
// JSON data
JSONObject jsonObject = new JSONObject();
try{
jsonObject.put("Email", email);
jsonObject.put("Password", password);
} catch (JSONException e){
e.printStackTrace();
}
// Json request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
LOGIN_REQUEST_URL,
jsonObject,
new Response.Listener<JSONObject>(){
#Override
public void onResponse(JSONObject response){
//Toast.makeText(context, "Product successfully added", Toast.LENGTH_SHORT).show();
try{
//use the response JSONObject now like this log
Log.d(TAG, response.getString("Success"));
boolean success = response.getBoolean("Success");
if (success) {
//...
}
} catch (JSONException e) {
System.out.println("Error logging in");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
Toast.makeText(LoginActivity.this, "Can't connect to Internet. Please check your connection.", Toast.LENGTH_LONG).show();
}
else if (error instanceof ServerError) {
Toast.makeText(LoginActivity.this, "Unable to login. Either the username or password is incorrect.", Toast.LENGTH_LONG).show();
}
else if (error instanceof ParseError) {
Toast.makeText(LoginActivity.this, "Parsing error. Please try again.", Toast.LENGTH_LONG).show();
}
else if (error instanceof NoConnectionError) {
Toast.makeText(LoginActivity.this, "Can't connect to internet. Please check your connection.", Toast.LENGTH_LONG).show();
}
else if (error instanceof TimeoutError) {
Toast.makeText(LoginActivity.this, "Connection timed out. Please check your internet connection.", Toast.LENGTH_LONG).show();
}
//Do other stuff if you want
error.printStackTrace();
}
}){
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String,String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
3600,
0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueueSingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
}
And then your onClick should look something like
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Email = emailEdt.getText().toString();
String Password = passwordEdt.getText().toString();
login(Email, Password);
}
}
Create RequestQueueSingleton.java class and use something like this:
public class RequestQueueSingleton {
private static RequestQueueSingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mCtx;
private RequestQueueSingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
}
public static synchronized RequestQueueSingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new RequestQueueSingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
}
The first character in the response is ">". When it tries to run this line:
JSONObject jsonResponse = new JSONObject(response);
It can't find a JsonObject in the response and your code won't work.
My suggestion is to remove ">" from your response and try again.

How to send POST request in JSON using StringRequest

I am trying send post request in Json using StringRequest.I desing Jersey Servlet in java and I created android project in android studio.
I can send json object with Poster Plugin in Chrome but I cant android client.
Please help me.
Jersey Servlet:
#Path("/register")
public class RegisterServlet {
#POST
#Path("/add")
#Consumes(MediaType.APPLICATION_JSON)
public Response addUser(UserDTO user){
if((user.getUsername()=="") || (user.getEmail()=="") || (user.getPassword()=="")){
Logger.getLogger(RegisterServlet.class).info("Name or Email or Password is empty");
return Response.status(200).entity("empty").build();
}
if(Service.getInstance().addUser(user)){
Logger.getLogger(RegisterServlet.class).info("Added User --> username: "+user.getUsername()+"email: "+user.getEmail());
return Response.status(200).entity("add").build();
}else{
Logger.getLogger(RegisterServlet.class).info("Error Add User");
return Response.status(200).entity("error").build();
}
}
}
Android Code ;
private void postUser(final String username,final String email,
final String password,final String dep_name){
String tag_string_req = "req_register";
StringRequest strReq = new StringRequest(Method.POST,
"http://192.168.56.1:8080/ServerApp/register/add", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
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("name", username);
params.put("email", email);
params.put("password", password);
params.put("dep_name", dep_name);
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
AppController in Android;
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);
}
}
}

Categories

Resources