Can someone please help me ???
I have successfully store the image path and text into MySQL, and image in the folder.
This is the php code I use to upload image path and text.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if( !empty( $_POST['listItems'] ) ){
$listItems = json_decode( $_POST['listItems'], true );
$mysqli = new mysqli("127.0.0.1:3307", "root", "", "androiddb");
if( $mysqli->connect_errno ) echo "Failed to connect to MySQL";
$sql="INSERT INTO `staff_benefit`
( `type`, `amount`, `description`, `image`, `ts_id` )
VALUES ( ?, ?, ?, ?, ? )";
if($stmt=$mysqli->prepare($sql )){
$url="http://192.168.1.7:80/Android/CRUD/PhotoUpload/";
foreach( $listItems as $item ){
$id = uniqid();
$image_name = $id.".png";
$save_path = 'PhotoUpload/'.$image_name;
$image_url = $url.$image_name;
$bytes=file_put_contents($save_path, base64_decode($item['image']));
if( !$bytes ){
echo 'Error saving image';
}else{
$stmt->bind_param('sssss',
$item['type'],
$item['amount'],
$item['description'],
$image_url,
$item['ts_id'] );
if( !$res=$stmt->execute()){
echo 'Query failed with code: '.$stmt->errno;
}
}
}
}
$mysqli->close();
}
}
?>
But when I tried to update the row in android, the row did not changed but it display updated successfully in php.
This is my update php
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$id = $_POST['id'];
$type = $_POST['type'];
$amount = $_POST['amount'];
$description = $_POST['description'];
//importing database connection script
require_once('dbConnect.php');
if(isset($_POST['image']))
{
$id = uniqid();
$url="http://192.168.107.115:80/Android/CRUD/PhotoUpload/";
$image_name = $id.".png";
$save_path = 'PhotoUpload/'.$image_name;
$image_url = $url.$image_name;
$bytes =file_put_contents($save_path, base64_decode($_POST['image']));
$sql = "UPDATE staff_benefit SET type = '$type', amount = '$amount', description='$description', image='$image_url'
WHERE id = '$id'";
}
else{
$sql = "UPDATE staff_benefit SET type = '$type', amount = '$amount', description='$description' WHERE id = '$id'";
}
//Updating database table
if(mysqli_query($con,$sql)){
echo ' Updated Successfully';
}else{
echo mysqli_error($con);
exit;
}
//closing connection
mysqli_close($con);
}
?>
Update code
public void update( final String claimType, final String Amount, final String Description, final Uri imageUri)
{
class updateImageAndText extends AsyncTask<Void,Void,String>{
// ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
// loading = ProgressDialog.show(Edit_Staff.this,"Updating...","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// loading.dismiss();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
try {
Intent returnIntent = new Intent();
returnIntent.putExtra("ClaimType", claimType);
returnIntent.putExtra("Amount", Amount);
returnIntent.putExtra("Description", Description);
returnIntent.putExtra("photo", imageUri.toString());
setResult(Activity.RESULT_OK, returnIntent);
finish();
}catch(Exception e)
{
}
}
#Override
protected String doInBackground(Void... params) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put(Configs.KEY_ID, String.valueOf(ID));
Log.e("ID", ID + "");
hashMap.put(Configs.KEY_TYPE, claimType);
hashMap.put(Configs.KEY_AMOUNT, Amount);
hashMap.put(Configs.KEY_DESCRIPTION, Description);
if(imageUri != null){
Log.d("log", "photo " + imageUri);
hashMap.put(Configs.KEY_IMAGE,getStringImage(imageUri));
}else{
Log.d("log", "photo is null " );
}
RequestHandler rh = new RequestHandler();
String s = rh.sendPostRequest(Configs.URL_UPDATEDE_IMAGE_TEXT,hashMap);
return s;
}
}
updateImageAndText ue = new updateImageAndText();
ue.execute();
}
public String getStringImage(Uri imgUri) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imgUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
} catch (Exception e) {
}
return "";
}
public void updateWithoutImage( final String claimType, final String Amount, final String Description)
{
class updateImageAndText extends AsyncTask<Void,Void,String>{
// ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
// loading = ProgressDialog.show(Edit_Staff.this,"Updating...","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// loading.dismiss();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
try {
Intent returnIntent = new Intent();
returnIntent.putExtra("ClaimType", claimType);
returnIntent.putExtra("Amount", Amount);
returnIntent.putExtra("Description", Description);
returnIntent.putExtra("iD",ID);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}catch(Exception e)
{
}
}
#Override
protected String doInBackground(Void... params) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put(Configs.KEY_ID, String.valueOf(ID));
Log.e("ID", ID + "");
hashMap.put(Configs.KEY_TYPE, claimType);
Log.e("Type",claimType);
hashMap.put(Configs.KEY_AMOUNT, Amount);
hashMap.put(Configs.KEY_DESCRIPTION, Description);
RequestHandler rh = new RequestHandler();
String s = rh.sendPostRequest(Configs.URL_UPDATEDE_IMAGE_TEXT,hashMap);
return s;
}
}
updateImageAndText ue = new updateImageAndText();
ue.execute();
}
I have two functions, one is update and another is updateWithoutImage. They using the same php. But the php works for updateWithoutImage but not for update function.
ok,I know why the update() does not functioning.
In my php code, I have two $id. Change the $id inside the if(isset($_POST['image'])) to $id1, and now it can be updated.
Related
I'm trying to post some data using volley to a server.
The issue seems to with an encoded string image.
On this line
String name = namefield.getText().toString();
String age = agefield.getText().toString();
String gender = genderfield.getText().toString();
String color = colorfield.getText().toString();
String notes = notesfield.getText().toString();
String images = encodeImage(bitmap);
updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), images);
if I change image to empty string
updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), "");
then than the data sends to server, which is how I know the image is the problem.
I logged the image response and this is what I get:
Strings: /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wB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j/6Jp+zz/4cDx1/8y1H9v8A7cf/AETT9nn/AMOB46/+ZavtTlPraivnf4Q/FbXfGmt+
MfAPxA8GHwH8Q/A1npF/rOk2urrrvh2+0vXGuBoetaPrXlx70P8AZLK0MqLLFIGZg0jOR9EUAFFF
FAHE+C/+RW8Nf9i/o/8A6aa65/8AVj8f/Qq5HwX/AMit4a/7F/R//TTXXP8A6sfj/wChVw4X/dZ/
L/0k4cL/ALrP5f8ApJYryz4p/Cf4WfHL4c+K/hT8ZfA3hz4j/DjxjY/2b4w8E+K9Ii1Tw1renGUa
o0OsaPcKysDLGrEP87TFC6szmOvU6+Wv2wPCn7R3jv8AZf8AjV4I/ZI+IHg74Y/tE+J/B9/pHwk+
IPjizEvhrwh4r1FmB13XIf8AhFfGDEQaMdRMf/FK3UgumjZUSRVlHcdx/Or/AMFfv2ntN+Ivh6D/
AIN6f+CV3ws8N+LPj58VvCWk/Dz4p2XhbTY7D4PfsffAG3fSNY1ttdIUeH9A1658Py5twhL+DoZA
yAfEifwPBXxB/wAF3f2U9B/Yk/4J4f8ABDn9huLxBc+Ivg78O/2wPAXgr4la9eLDpum+LNRJn1jW
tZ1qONtqxzHXfHM0ZbDojudqvH5VeifsXf8ABGf/AIOKP2B7D4myfs//ALX3/BOa18V/F7xXqPjL
4mfE/wAceFPin8RPi1441WSSWTGu+OPEn7P7+ILi3eWSSYWyMoS4lMrSedtdv2
while the other data response are normal like:
Strings: red
The logcat says the problem is here:
try {
JSONObject jsonObject = new JSONObject(result);
Log.i("Check", result);
Here's the relevant code:
public void updatedetails(final String name, final String age, final String gender, final String color, final String notes, final String owner, final String id, final String pet_image) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Updating pet details");
progressDialog.show();
try {
String url = "https://happy-paws.co.za/dogwalking/apis/v1/pet/update_pet.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
String result = response.toString();
// Log.d("zzzz","res "+result);
Toast.makeText(update.this, response, Toast.LENGTH_SHORT).show();
getDataResponse1(result);
Log.i("Check", result);
Log.i("Check", response);
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(update.this, error.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("TAG", error.getMessage());
}
}) {
#Override
public byte[] getBody() throws com.android.volley.AuthFailureError {
String str = "{\"name\":\"" + name + "\",\"age\":\"" + age + "\",\"gender\":\"" + gender + "\",\"color\":\"" + color + "\",\"notes\":\"" + notes + "\",\"owner\":\"" + owner + "\",\"id\":\"" + id + "\",\"pet_image\":\"" + pet_image + "\"}";
return str.getBytes();
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
// params.put("email",email);
// params.put("password",password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
} catch (Exception e) {
//App.handleUncaughtException(e);
}
progressDialog.dismiss();
}
public void getDataResponse1(String result) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Please Wait.....");
progressDialog.show();
try {
JSONObject jsonObject = new JSONObject(result);
Log.i("Check", result);
JSONObject current = jsonObject.getJSONObject(result);
String message = current.getString("message");
String name = jsonObject.isNull("name") ? null : jsonObject.getString("name");
String age = jsonObject.isNull("age") ? null : jsonObject.getString("age");
String gender = jsonObject.isNull("gender") ? null : jsonObject.getString("gender");
String notes = jsonObject.isNull("notes") ? null : jsonObject.getString("notes");
String color = jsonObject.isNull("color") ? null : jsonObject.getString("color");
// String android_status=jsonObject.getString("android_status");
if (message.equals("Pet was updated.")) {
Toast.makeText(this, "" + message, Toast.LENGTH_SHORT).show();
// updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), pet_image);
} else {
Toast.makeText(this, "" + message, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
private void selectImage(Context context) {
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose your profile picture");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent takePicture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
} else if (options[item].equals("Choose from Gallery")) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK && data != null) {
bitmap = (Bitmap) data.getExtras().get("data");
profilepic.setImageBitmap(bitmap);
encodeImage(bitmap);
}
break;
case 1:
if (resultCode == RESULT_OK) {
bitmap = (Bitmap) data.getExtras().get("data");
Uri selectedImage = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(selectedImage);
bitmap = BitmapFactory.decodeStream(inputStream);
profilepic.setImageBitmap(bitmap);
encodeImage(bitmap);
// Glide.clear(profilepic);
} catch (FileNotFoundException e) {
Toast.makeText(update.this, "Pet added succesfully", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
}
public String encodeImage(Bitmap bitmap) {
ByteArrayOutputStream ba = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ba);
byte[] imagebyte = ba.toByteArray();
encode = android.util.Base64.encodeToString(imagebyte, Base64.DEFAULT);
return encode;
}
And then where I submit:
updatebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = namefield.getText().toString();
String age = agefield.getText().toString();
String gender = genderfield.getText().toString();
String color = colorfield.getText().toString();
String notes = notesfield.getText().toString();
String images = encodeImage(bitmap);
updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), images);
Log.d("Strings",images );
Log.d("Strings",color );
image response is ok. you must set image data type as LONGTEXT or LONGBLOB on database server. but a better solution is to use Multipart Image Upload for upload image on server.
you can try with Uploading Images to Server android
I have a table in ms sql this table contains FName and FInfo i want to get th FInfo according to the FName like if the FName in the app is equal to john it gets the FInfo of john in the same row.
i have tried everything including query's and Result set but it didn't work out for me.
here is my code:
public class InsideFamily extends AppCompatActivity {
private TextView inf;
private boolean success = false; // boolean
private ConnectionClass connectionClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inside_family);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
inf = (TextView) findViewById(R.id.thefamilyinf);
connectionClass = new ConnectionClass();
SyncData orderData = new SyncData();
orderData.execute("");
}
private class SyncData extends AsyncTask<String, String, String> {
String msg = "No Data Found";
ProgressDialog progress;
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(InsideFamily.this, "Synchronising",
"Please Wait...", true);
}
#Override
protected String doInBackground(String... strings)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Connection conn = connectionClass.CONN();
if (conn == null) {
msg = "Please Check Your Connection";
success = false;
} else {
String gettingfam = getIntent().getStringExtra("defamily");
String query = "SELECT * FROM family where FName='" + gettingfam + "'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) {
while (rs.next()) {
try {
inf.setText((rs.getString("FInfo")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
}
});
return msg;
}
#Override
protected void onPostExecute(String
msg)
{
progress.dismiss();
Toast.makeText(InsideFamily.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false) {
} else {
try {
} catch (Exception ex) {
}
}
}
}
}
the errors i get is that it brings a toast for me saying that "No Data Found!"
which means that that the result set equals null how can i fix it??
I found the answer
the wrong was in the query
because its nvarchar i have to wright
"SELECT * FROM family WHERE FName = (N'" +dta+ "')"
rather than
"SELECT * FROM family where FName='" + gettingfam + "'"
I have an app where I use the info provided by the user to get a list of data
Using the code below, I'm getting two different results:
When where username = '$username' is presented on the PHP side, I receive just the Toast message. However, ListView remains empty.
When I remove where username = '$username' from PHP side, Toast message is displayed and the ListView also shows some content
Could you please help me to undestand why the ListView remains empty on that specific case?
Thanks in advance
Java
public void current_user() {
String url = "http://websie/my.php";
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dayes = new SimpleDateFormat("dd-MM-yyyy");
final String created_date = dayes.format(calendar.getTime());
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//System.out.println(response);
// Toast.makeText(MainActivity.this,response,Toast.LENGTH_SHORT).show();
Toast.makeText(show_post_all_sales_2x100.this, response.toString(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
listViewAdapter = new ListViewAdapter(show_post_all_sales_2x100.this, R.layout.listview_items_layout, SubjectList);
listView.setAdapter(listViewAdapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(show_post_all_sales_2x100.this, error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("username", User.getUsername());
params.put("created_date", created_date);
return params;
}
};
RequestQueue requestQueue = com.android.volley.toolbox.Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpParseClass httpParseClass = new HttpParseClass(HttpURL);
try {
httpParseClass.ExecutePostRequest();
if (httpParseClass.getResponseCode() == 200) {
FinalJSonResult = httpParseClass.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Subjects subjects;
SubjectList = new ArrayList<Subjects>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String tempName = jsonObject.getString("username").toString();
String tempFullForm = jsonObject.getString("created_date").toString();
subjects = new Subjects(tempName, tempFullForm);
SubjectList.add(subjects);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
Toast.makeText(context, httpParseClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
progressBar.setVisibility(View.INVISIBLE);
listViewAdapter = new ListViewAdapter(show_post_all_sales_2x100.this, R.layout.listview_items_layout, SubjectList);
listView.setAdapter(listViewAdapter);
}
}
PHP
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'DatabaseConfig.php';
$username = $_POST['username'];
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM post_2x where username = '$username'" ;
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
}
?>
Result when where username = '$username' is present
Result when I remove where username = '$username'
this is my php script
<?php
try{
$con = new PDO('mysql:host=localhost;dbname=pfe'/*info db*/,'root'/*login*/, ''/*mdp*/);
}
catch (Exception $e)
{
die('Erreur : '.$e->getMessage());
}
$msg = $_GET['msg'];
$mail = $_GET['mail'];
$result = $con->prepare("INSERT INTO message ( `msg`, `mail`)
VALUES ('{$msg}', '{$mail}')");
$result->execute();
if($result == true) {
echo '{"query_result":"SUCCESS"}';
}
else{
echo '{"query_result":"FAILURE"}';
}
my script i think is good cause i tried it with my browser it works but with android does not insert the data
and this is java class,
EditText msg,mail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msg = (EditText) findViewById(R.id.editText);
mail = (EditText) findViewById(R.id.editText2);
}
public void signup(View v) {
String message = msg.getText().toString();
String email = mail.getText().toString();
Toast.makeText(this, "wait...", Toast.LENGTH_SHORT).show();
new Insertinto(this).execute(message, email);
}
public class Insertinto extends AsyncTask<String, Void, String> {
private Context context;
public Insertinto(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String msg = arg0[0];
String mail = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?msg=" + URLEncoder.encode(msg, "UTF-8");
data += "&mail=" + URLEncoder.encode(mail, "UTF-8");
link = "http://192.168.43.93/dysfonction.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
this is json
protected void onPostExecute(String result) {
String jsonStr = result;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully", Toast.LENGTH_SHORT).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Data could not be inserted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Couldn't connect to database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
}
when i execute it show me "Error parsing JSON data" i didn't find where is the pbm.
debug and check the result received in the postExecute(); and from next time paste the logcat as well..
Try to change this to
if($result == true) {
echo '{"query_result":"SUCCESS"}';
}else{
echo '{"query_result":"FAILURE"}';
}
this
if($result == true) {
$data = array(
'query_result' => 'SUCCESS'
);
}else{
$data = array(
'query_result' => 'FAILURE'
);
}
echo json_encode($data);
It seems to be your java code is so clear. So sent response from php code like above may be works.
in the place of
result = bufferedReader.readLine();
use
result = bufferedReader.readLine().toString();
What are the correct way to convert Uri image to Base64 String before send to server ?
public void update( final String claimType, final String Amount, final String Description, final String imageUri)
{
class updateImageAndText extends AsyncTask<Void,Void,String>{
// ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
// loading = ProgressDialog.show(Edit_Staff.this,"Updating...","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// loading.dismiss();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
try {
Intent returnIntent = new Intent();
returnIntent.putExtra("ClaimType", claimType);
returnIntent.putExtra("Amount", Amount);
returnIntent.putExtra("Description", Description);
returnIntent.putExtra("photo", imageUri);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}catch(Exception e)
{
}
}
#Override
protected String doInBackground(Void... params) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put(Configs.KEY_ID, String.valueOf(ID));
Log.e("ID", ID + "");
hashMap.put(Configs.KEY_TYPE, claimType);
hashMap.put(Configs.KEY_AMOUNT, Amount);
hashMap.put(Configs.KEY_DESCRIPTION, Description);
if(imageUri != null){
Log.d("log", "photo " + imageUri);
hashMap.put(Configs.KEY_IMAGE,getStringImage(imageUri)); // error
}else{
Log.d("log", "photo is null " );
}
RequestHandler rh = new RequestHandler();
String s = rh.sendPostRequest(Configs.URL_UPDATEDE_IMAGE_TEXT,hashMap);
return s;
}
}
updateImageAndText ue = new updateImageAndText();
ue.execute();
}
public String getStringImage(Uri imgUri) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imgUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
} catch (Exception e) {
}
return "";
}
Error
Error:incompatible types: String cannot be converted to Uri
In update you are passing imageUri as a String:
public void update( final String claimType, final String Amount, final String Description, final String imageUri)
hashMap.put(Configs.KEY_IMAGE,getStringImage(imageUri)); // error because imageUri is a String
But your method expect a Uri not String:
public String getStringImage(Uri imgUri){...}