I am trying to send images taken from my phone to a server, with the code below the app crashes when I try to upload a picture taken from my phone, I know the code works because I am able to upload images I have downloaded onto my phone.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
String fileNameSegments[] = picturePath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
Bitmap myImg = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
myImg.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedString = Base64.encodeToString(byte_arr, 0);
}
}
the code that uploads
public void uploadImage() {
RequestQueue rq = Volley.newRequestQueue(this);
String url = "http://serverwebsite.com/image.php";
Log.d("URL", url);
StringRequest stringRequest = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.e("RESPONSE", response);
JSONObject json = new JSONObject(response);
Toast.makeText(getBaseContext(),
"The image is upload", Toast.LENGTH_SHORT)
.show();
} catch (JSONException e) {
Log.d("JSON Exception", e.toString());
Toast.makeText(getBaseContext(),
"Error while loadin data!",
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error [" + error + "]");
Toast.makeText(getBaseContext(),
"Cannot connect to server", Toast.LENGTH_LONG)
.show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("image", encodedString);
params.put("filename", fileName);
return params;
}
};
rq.add(stringRequest);
}
i hope this code help you
public void sendImage(MediaType mediaType)
{
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition",
"form-data; name=\"file\"; filename=" + '"'
+ name + '"'),
RequestBody.create(mediaType, new File(getFileAdress()
))).build();
final String credential = Credentials.basic(userName, pass);
Request request = new Request.Builder()
.header("Authorization", credential)
.url(WebServiceAddress())
.post(requestBody).build();
try {
Response response = client.newCall(request).execute();
int code=response.code();
String out = response.body().string();
if (response.isSuccessful()) {
} else {
} catch (Exception ex) {
}
}
This is my library addresses that I use for resizing photos :
https://github.com/alireza-87/ImageHelper
Related
I stored some lattitude and longitude on google map now i want add on google
I tried to read lattitude and longitude into array than i tried to read the array into google map but throw that the array is unitialized
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
phone = new String[response.length()];
liti = new double[response.length()];
longt = new double[response.length()];
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
phone[i] = jsonObject.getString("phone").toString();
liti[i] = ((double) jsonObject.getDouble("latitude"));
longt[i] = ((double) jsonObject.getDouble("longitude"));
Toast.makeText(context, longt[i]+"", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Toast.makeText(context, e.getMessage() + "", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(arrayRequest);
i want to add these lititude and longitude onto google map
It always show the else statement
StringRequest stringRequest=new StringRequest(Request.Method.GET, HI, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
String f="fasil";
TextView txt=(TextView)findViewById(R.id.nam);
JSONObject jsonObject=new JSONObject(response);
JSONArray array=jsonObject.getJSONArray("data");
for (int i=0;i<array.length();i++) {
JSONObject ob = array.getJSONObject(i);
String s = ob.getString("username").trim();
if(s==f) {
String text = "" + s;
txt.setText(text);
}
else
Toast.makeText(profile.this,"not available",Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(profile.this,"error",Toast.LENGTH_LONG).show();
}
});
php result
{"data":[{"username":"fasil","password":"fasilt"},{"username":"ubhh","password":"g g gvhv"},{"username":"ashique","password":"ashiqueash"},{"username":"zabir","password":"zabir1999"}]}
String s = ob.getString("username").trim();
if(s.equals("fasil")) {
txt.setText(s);
} else {
Toast.makeText(profile.this, "not available", Toast.LENGTH_LONG).show();
}
I'm trying to retrieve the total number of correct answers answered by the students from different countries.
I'm using JSON to link to my php then to my database. But i seems to can't read the spaces in between words. For example, the country name is "Czech Republic" in the database. However when i echo, it shows me "Czech".
The $country in the php code is from the android studio, where i sent a url link Config.LEADERSHIPBOARD_URL_ME + country; to get connected to the database.
This is my php code:
<?php
$country = $_GET['country'];
require "conn.php";
$sql_mcq = "SELECT * FROM mcqparticipator WHERE country = '".$country."'";
$r_mcq = mysqli_query($conn,$sql_mcq);
$result = array();
$mcqCount = 0;
if($r_mcq)
{
while($row = mysqli_fetch_array($r_mcq))
{
if(($row['correctAns'] == "1"))
{
$mcqCount++;
}
}
array_push($result,array(
"McqCount"=>$mcqCount,
"Country"=>$country));
echo json_encode(array("result"=>$result));
}
else
{
echo "No connection";
}
$conn->close();
?>
And this is my code from android studio:
// Description: This method will generate a url and send a request
// This method will call showJSON() method to start sending the response
private void getData(){
loading = ProgressDialog.show(getActivity(), "Please wait...","Fetching", false, false);
url = Config.LEADERSHIPBOARD_URL_ME + country;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
Toast.makeText(getActivity(), "Country in studio: " + country, Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), "Country in database: " + dcountry, Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), "Mcq count: " + McqCount, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(getActivity(),"No existing question", Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue= Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
// Description: This method will generate a response using JSON via php.
// Retreive and compare the participants answer with the correct answer
public void showJSON(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
McqCount = collegeData.getString(Config.MCQ_COUNT);
dcountry = collegeData.getString("Country");
} catch (JSONException e) {
e.printStackTrace();
}
}
Appreciate if someone could help me, thank you!
I'm trying to pass some values to server using JSONObjectRequest of Volley library. But somehow the data isn't being sent to server and the variable of server side script which is supposed to receive the data is empty.
Here is the JSONObjectRequest code
JSONObject obj = new JSONObject();
try {
obj.put("userid", "userid");
} catch (JSONException e) {
e.printStackTrace();
}
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.POST,
URL_FEED, obj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
Log.d(String.valueOf(getApplicationContext()),"Response generated");
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Log.d("Error - >",error.getMessage());
Toast.makeText(getApplicationContext(),"Error is -->> " + error.getMessage(),Toast.LENGTH_LONG).show();
}
});
php side to get the variable
$userid = $_POST['userid'];
Get it to work by changing the JSONObjectRequest to StringRequest and then convert the Onresponse String to JSONObject as follow
// making fresh volley request and getting json
StringRequest jsonReq = new StringRequest(Method.POST,
URL_FEED, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
VolleyLog.d(TAG, "Response: " + s.toString());
JSONObject response = null;
try {
response = new JSONObject(s);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(String.valueOf(getApplicationContext()), "Response generated");
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Log.d("Error - >",error.getMessage());
Toast.makeText(getApplicationContext(),"Error is -->> " + error.getMessage(),Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("userid", userid);
return params;
}
};
Can we post JsonObject or JsonArray using Android volley to the server?If yes can anyone please send the working sample.
If i post string then it works fine but i have some problem while posting jsonObject or jsonArray.
Yes you can. The JSON is added to the body of a POST request, like this:
JSONObject jsonObject; // your JSON here
requestQueue.add(new JsonObjectRequest(Method.POST, url, jsonObject, listener, errorListener);
Yes, just add data to JSONObject and pass that object in the request.
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", name);
jsonObject.put("password", password);
RequestQueue queue = Volley.newRequestQueue(context);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, URL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("volley", "response: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("volley", "error: " + error);
}
});