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.
Related
I'm new in android programming. Currently, I develop apps that require login. For now, the login is successful. Below is the code:
MainActivity.JAVA
private void userLogin() {
//first getting the values
final String badgeid = etBadgeid.getText().toString();
final String pwd = etPassword.getText().toString();
//validating inputs
if (TextUtils.isEmpty(badgeid)) {
etBadgeid.setError("Please enter your badgeid");
etBadgeid.requestFocus();
return;
}
if (TextUtils.isEmpty(pwd)) {
etPassword.setError("Please enter your password");
etPassword.requestFocus();
return;
}
//if everything is fine
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("onPostExecute","response is: "+response);
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getString("badgeid"),
userJson.getString("email"),
userJson.getString("fullname"),
userJson.getInt("roles_id"),
userJson.getInt("team_id")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), Home.class));
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("badgeid", badgeid);
params.put("pwd", pwd);
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
URL_LOGIN (PHP)
<?php
require_once '../config/configPDO.php';
$response = array();
if(isTheseParametersAvailable(array('badgeid', 'pwd'))){
$badgeid = $_POST['badgeid'];
$pwd = $_POST['pwd'];
$stmt = $conn->prepare("SELECT badgeid, email, fullname, roles_id, team_id FROM ot_users WHERE badgeid = :badgeid AND pwd = :pwd AND roles_id = 7 AND team_id <> 1");
$stmt->bindParam(':badgeid',$badgeid,PDO::PARAM_STR);
$stmt->bindParam(':pwd',$pwd,PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result) {
$response['error'] = false;
$response['message'] = 'Login successfull';
$response['user'] = $result;
}else{
$response['error'] = false;
$response['message'] = 'Invalid username or password';
}
}
echo json_encode($response);
function isTheseParametersAvailable($params){
foreach($params as $param){
if(!isset($_POST[$param])){
return false;
}
}
return true;
}
?>
Then, I want to use web services (url) when retrieving the data from the database. Below is the php code
URL_LOGIN (PHP)
<?php
require_once '../config/configPDO.php';
$response = array();
if(isTheseParametersAvailable(array('badgeid', 'pwd'))){
$badgeid = $_POST['badgeid'];
$pwd = $_POST['pwd'];
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/ot_displayUser?badgeid=$badgeid&pwd=$pwd";
$data = file_get_contents($url);
$json = json_decode($data);
$result = $json->otUserList;
if ($result) {
$response['error'] = false;
$response['message'] = 'Login successfull';
$response['user'] = $result;
}else{
$response['error'] = false;
$response['message'] = 'Invalid username or password';
}
}
echo json_encode($response);
function isTheseParametersAvailable($params){
foreach($params as $param){
if(!isset($_POST[$param])){
return false;
}
}
return true;
}
?>
When I use this code, It will POPUP "Login successful" but it failed to redirect to the next page (Home.JAVA). Can anyone know what is the problem?
You are calling finish() method before startActivity(new Intent(MainActivity.this, Home.class));. finish() is used to remove current activity from stack. You alway s have to call after navigating to another activty.
If you find this as a correct answer then correct it.
UPDATED your code so copy the following code:
MainActivity.java
private void userLogin() {
//first getting the values
final String badgeid = etBadgeid.getText().toString();
final String pwd = etPassword.getText().toString();
//validating inputs
if (TextUtils.isEmpty(badgeid)) {
etBadgeid.setError("Please enter your badgeid");
etBadgeid.requestFocus();
return;
}
if (TextUtils.isEmpty(pwd)) {
etPassword.setError("Please enter your password");
etPassword.requestFocus();
return;
}
//if everything is fine
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("onPostExecute","response is: "+response);
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(MainActivity.this, obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getString("badgeid"),
userJson.getString("email"),
userJson.getString("fullname"),
userJson.getInt("roles_id"),
userJson.getInt("team_id")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
startActivity(new Intent(MainActivity.this, Home.class));
finish(); //it will remove current activity from activity stack
} else {
Toast.makeText(MainActivity.this, obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("badgeid", badgeid);
params.put("pwd", pwd);
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(MainActivity.this);
requestQueue.add(stringRequest);
}
How do I return serverAnswer behind onResponse?
Because in onResponse, serverAnswer gets data, but behind onResponse it's an empty variable...
For example, if I try to show a Toast with serverAnswer in onResponse, it's alright, serverAnswer has data from JSON string. But if try to show a Toast with serverAnswer behind onResponse - I get an empty Toast.
And addUser returns an empty String too.
public String addUser(final String username, final String email, final String password, final Context context) {
StringRequest request = new StringRequest(
Request.Method.POST,
REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
try {
JSONObject jsonObject = new JSONObject(response);
final JSONObject status = jsonObject.getJSONObject("Result");
serverAnswer = status.getString("Server answer");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
serverAnswer = error.getMessage();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put(KEY_USERNAME, username);
params.put(KEY_EMAIL, email);
params.put(KEY_PASSWORD, password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(request);
return serverAnswer;
}
Fed up with this problem.. How to solve it.. please Help.. Everytime I run my application I get this same error again and again.. Wasted 2 days already.. please someone help to get rid of it.
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response);
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
Boolean error= jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("username");
String name = user.getString("username");
String email = user.getString("password");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("username", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
Above is the Login Activity code..
I am trying to make a volley PUT request to upload an image, Since httpEntity is deprecated now, I had to do some other research, I came across these solutions and tried to implement them into my code :
1. https://gist.github.com/anggadarkprince/a7c536da091f4b26bb4abf2f92926594
2. How to send multipart request using Volley without HttpEntity?
3. Working POST Multipart Request with Volley and without HttpEntity
but still I cannot upload my image. The image I want to upload is either captured from the camera or selected in the gallery, and it is executed onClick.
ProfileSetting.java
public class ProfileSetting extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private ImageView CustomerIcon;
private Button confirm_button;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_setting);
CustomerIcon = (ImageView) findViewById(R.id.CustomerIcon);
confirm_button = (Button) findViewById(R.id.confirm_button);
CustomerIcon.setOnClickListener(new ImageView.OnClickListener(){
public void onClick(View v){
showPickImageDialog();
}
});
confirm_button.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View view) {
//PUT VOLLEY
saveProfileAccount();
}
});
}
private void showPickImageDialog() {
AlertDialog.Builder builderSingle = new AlertDialog.Builder(ProfileSetting.this);
builderSingle.setTitle("Choose Profile Icon");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
ProfileSetting.this,
android.R.layout.select_dialog_singlechoice);
arrayAdapter.add("Gallery");
arrayAdapter.add("Camera");
builderSingle.setNegativeButton(
"cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builderSingle.setAdapter(
arrayAdapter,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
break;
case 1:
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
break;
}
}
});
builderSingle.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
CustomerIcon.setImageURI(selectedImage);
}
break;
case 1:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
CustomerIcon.setImageURI(selectedImage);
}
break;
}
}
private void saveProfileAccount() {
// loading or check internet connection or something...
// ... then
String url = "https://url to put image to";
SharedPreferences sp1=this.getSharedPreferences("FINALTOKEN", Context.MODE_PRIVATE);
final String finalToken = sp1.getString("FINALTOKEN","");
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.PUT, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
String resultResponse = new String(response.data);
try {
JSONObject result = new JSONObject(resultResponse);
String status = result.getString("status");
String message = result.getString("message");
if (status.equals(Constant.REQUEST_SUCCESS)) {
// tell everybody you have succeed upload image and post strings
Log.i("Messsage", message);
} else {
Log.i("Unexpected", message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String errorMessage = "Unknown error";
if (networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
errorMessage = "Request timeout";
} else if (error.getClass().equals(NoConnectionError.class)) {
errorMessage = "Failed to connect server";
}
} else {
String result = new String(networkResponse.data);
try {
JSONObject response = new JSONObject(result);
String status = response.getString("status");
String message = response.getString("message");
Log.e("Error Status", status);
Log.e("Error Message", message);
if (networkResponse.statusCode == 404) {
errorMessage = "Resource not found";
} else if (networkResponse.statusCode == 401) {
errorMessage = message+" Please login again";
} else if (networkResponse.statusCode == 400) {
errorMessage = message+ " Check your inputs";
} else if (networkResponse.statusCode == 500) {
errorMessage = message+" Something is getting wrong";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("Error", errorMessage);
error.printStackTrace();
}
}) {
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers= new HashMap<>();
headers.put("Authorization",finalToken);
return headers;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// file name could found file base or direct access from real path
// for now just get bitmap data from ImageView
params.put("avatar", new DataPart("file_avatar.jpg", ImageConverter.getFileDataFromDrawable(getBaseContext(), CustomerIcon.getDrawable()), "image/jpeg"));
return params;
}
};
VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
}
}
VolleyMultipartRequest.java and VolleySingleton.java I am using the same class as what my first link has.
My errors are first of all I cannot resolve symbol 'Constant' in the if statement:
if (status.equals(Constant.REQUEST_SUCCESS))
so I tried commenting the statement, after running the code I got the following error:
BasicNetwork.performRequest: Unexpected response code 500 for https://my url
W/System.err: org.json.JSONException: No value for status
I am not sure what is causing my problem,please help, thank you!
Here is Simple Solution And Complete Example for Uploading File Using Volley Android
1) Gradle Import
compile 'dev.dworks.libs:volleyplus:+'
2)Now Create a Class RequestManager
public class RequestManager {
private static RequestManager mRequestManager;
/**
* Queue which Manages the Network Requests :-)
*/
private static RequestQueue mRequestQueue;
// ImageLoader Instance
private RequestManager() {
}
public static RequestManager get(Context context) {
if (mRequestManager == null)
mRequestManager = new RequestManager();
return mRequestManager;
}
/**
* #param context application context
*/
public static RequestQueue getnstance(Context context) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(context);
}
return mRequestQueue;
}
}
3)Now Create a Class to handle Request for uploading File WebService
public class WebService {
private RequestQueue mRequestQueue;
private static WebService apiRequests = null;
public static WebService getInstance() {
if (apiRequests == null) {
apiRequests = new WebService();
return apiRequests;
}
return apiRequests;
}
public void updateProfile(Context context, String doc_name, String doc_type, String appliance_id, File file, Response.Listener<String> listener, Response.ErrorListener errorListener) {
SimpleMultiPartRequest request = new SimpleMultiPartRequest(Request.Method.POST, "YOUR URL HERE", listener, errorListener);
// request.setParams(data);
mRequestQueue = RequestManager.getnstance(context);
request.addMultipartParam("token", "text", "tdfysghfhsdfh");
request.addMultipartParam("parameter_1", "text", doc_name);
request.addMultipartParam("dparameter_2", "text", doc_type);
request.addMultipartParam("parameter_3", "text", appliance_id);
request.addFile("document_file", file.getPath());
request.setFixedStreamingMode(true);
mRequestQueue.add(request);
}
}
4) And Now Call The method Like This to Hit the service
public class Main2Activity extends AppCompatActivity implements Response.ErrorListener, Response.Listener<String>{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadData();
}
});
}
private void uploadData() {
WebService.getInstance().updateProfile(getActivity(), "appl_doc", "appliance", "1", mChoosenFile, this, this);
}
#Override
public void onErrorResponse(VolleyError error) {
}
#Override
public void onResponse(String response) {
//Your response here
}
}
mChoosenFile is your image file
First of all convert your image bitmap to base64 string using the following code:
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
Then make a PUT Request like the following one and pass the base64 string as a parameter of the request
url = "http://example.com";
StringRequest putRequest = new StringRequest(Request.Method.PUT, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("imageString", base64String);
return params;
}
};
queue.add(putRequest);
Refer Android Volley Tutorial if you face any difficulty in implementing volley request.
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)