how to instantiate Uri from a String? - java

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){...}

Related

Android Studio org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

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/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAUAAk8DASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3
ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm
p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA
AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx
BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKj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/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

Android code to connect PHP response changed to null

I'm facing problem in getting a response back in android from PHP.
First, it gets the right response in try then I don't know what cause problem it goes to catch and change response to null. My PHP files are perfectly working I tested them by giving default values.
Below is the code:
This class is used to connect to server and send data to PHP:
public class DatabaseFunctionality extends AsyncTask <String, String, String>{
int flag;
Context context;
String username;
String password;
String rname;
String city;
int mnum;
String sname;
String area;
String sadd;
int snum1;
int snum2;
String cpic;
String ppic;
Bitmap coverpic, profpic;
public String resp;
//public String r;
StringBuilder sb;
public DatabaseFunctionality(Context context, int f){
this.context=context;
this.flag=f;
}
#Override
protected String doInBackground(String... params) {
if(this.flag==0){
username=params[0];
password=params[1];
resp = login();
}
else if(this.flag==1){
rname = params[0];
username = params[1];
password = params[2];
city = params[3];
mnum = Integer.parseInt(params[4]);
sname = params[5];
area = params[6];
sadd = params[7];
snum1 = Integer.parseInt(params[8]);
snum2 = Integer.parseInt(params[9]);
resp = signup();
}
return resp;
}
public String login() {
try {
String link = "http://192.168.0.105:80/directdukan/login.php";
String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
Log.e("string", sb.toString());
return sb.toString();
}
catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
public String signup(){
try{
String link = "http://192.168.0.105:80/directdukan/signup.php?rname="+rname+"&username="+username+"&password="+password+"&city="+city+"&mnum="+mnum+"&sname="+sname+"&area="+area+"&sadd="+sadd+"&sanum1="+snum1+"&snum2="+snum2;//+"& cpic="+coverpic+"& ppic="+profpic;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
Log.e("string", sb.toString());
return sb.toString();
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
public void addproduct(){
}
public void searchproduct(){
}
public void editproduct(){
}
public void deleteproduct(){
}
#Override
protected void onPostExecute(String result){
this.resp = result;
}
public Bitmap StringToBitMap(String encodedString){
try {
byte [] encodeByte=Base64.decode(encodedString, Base64.DEFAULT);
Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch(Exception e) {
e.getMessage();
return null;
}
}
}
// Below LoginActivity & SignupActivity is used to get data from activity and send it to DatabaseFunctionality class
public class LoginActivity extends AppCompatActivity {
EditText username, password;
Button login, signup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.button_login);
signup = (Button) findViewById(R.id.button_signup);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String uname = username.getText().toString();
String pass = password.getText().toString();
if(!"".equals(uname) && !"".equals(pass)) {
DatabaseFunctionality db = new DatabaseFunctionality(LoginActivity.this,0);
db.execute(uname,pass);
if(db.resp.equals("user exist")) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(),"Username or Password is incorrect",Toast.LENGTH_LONG).show();
username.setText(null);
password.setText(null);
}
}
else {
Toast.makeText(getApplicationContext(), "Please Enter Username or Password", Toast.LENGTH_LONG).show();
username.setText(null);
password.setText(null);
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(intent);
}
});
}
}
public class SignupActivity extends AppCompatActivity {
public int PICK_IMAGE_REQUEST = 1;
public Bitmap bitmap;
public Uri filePath;
String imgname;
EditText username, password, ownername, cnic, shopname, shopadd, shopphone, shopphone2, mobile;
TextView cpic, ppic;
Spinner citymenu, areamenu;
Button signup2, ucpic, uppic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
ownername = (EditText) findViewById(R.id.rname);
shopname = (EditText) findViewById(R.id.shopname);
shopadd = (EditText) findViewById(R.id.shopadd);
shopphone = (EditText) findViewById(R.id.shopphone);
shopphone2 = (EditText) findViewById(R.id.shopphone2);
mobile = (EditText) findViewById(R.id.mobile);
citymenu =(Spinner) findViewById(R.id.citymenu);
areamenu = (Spinner) findViewById(R.id.areamenu);
cpic = (TextView) findViewById(R.id.coverpic);
ppic = (TextView) findViewById(R.id.profpic);
signup2 = (Button) findViewById(R.id.signup2);
ucpic = (Button) findViewById(R.id.uploadcpicb);
uppic = (Button) findViewById(R.id.uploadppicb);
ucpic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
imgname = getStringImage(bitmap);
cpic.setText(imgname);
}
});
uppic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
imgname = getStringImage(bitmap);
ppic.setText(imgname);
}
});
signup2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String uname = username.getText().toString();
String pass = password.getText().toString();
String rname = ownername.getText().toString();
String city = citymenu.getSelectedItem().toString();
String mnum = mobile.getText().toString();
String sname = shopname.getText().toString();
String area = areamenu.getSelectedItem().toString();
String sadd = shopadd.getText().toString();
String snum1 = shopphone.getText().toString();
String snum2 = shopphone2.getText().toString();
if(!"".equals(rname) && !"".equals(city) && !"".equals(uname) && !"".equals(pass) && !"".equals(sname) && !"".equals(mnum) && !"".equals(area) && !"".equals(sadd) && !"".equals(snum1)) {
DatabaseFunctionality db = new DatabaseFunctionality(SignupActivity.this, 1);
db.execute(rname,uname,pass,city,mnum,sname,area,sadd,snum1,snum2);
if(db.resp.equals("Signup Successful")) {
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
startActivity(intent);
Toast.makeText(SignupActivity.this, "Signup Successful!",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(),"Fields with * are must",Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(getApplicationContext(),"Fields with * are must",Toast.LENGTH_LONG).show();
}
}
});
String[] items = new String[]{"*Select","Abbottabad",
"Adezai",
"Ali Bandar",
"Amir Chah",
/* snip */
"Wazirabad",
"Yakmach",
"Zhob",
"Other"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
citymenu.setAdapter(adapter);
String[] items2 = new String[]{"*Select","Johar Town","Faisal Town", "Main Boulevard","Cantt","Model Town"};
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items2);
areamenu.setAdapter(adapter2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
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;
}
}

Getting bitmap null while converting url to bitmap

I want to download the image from server and convert it to bitmap. I tried to download the image and convert it to bitmap but it returns null. I get bitmap as null.
To convert image to bitmap I have created one asyncTask.
Passing url to Async task :
String url = ServiceUrl.getBaseUrl() + ServiceUrl.getImageUserUrl() + profileImage;
Log.e("url", url);
new ImageUserTask(mContext, url, profileImage).execute();
ImageUserAsync Task:
public class ImageUserTask extends AsyncTask<Void, Void, Bitmap> {
String imageprofile;
private String url;
private Bitmap mBitmap;
private Context mContext;
public ImageUserTask(Context context, String url, String imageprofile) {
this.url = url;
this.imageprofile = imageprofile;
this.mContext = context;
}
#Override
protected Bitmap doInBackground(Void... params) {
try {
//Url
URL urlConnection = new URL(url);
//Conntecting httpUrlConnection
HttpURLConnection connection = (HttpURLConnection) urlConnection.openConnection();
connection.setDoInput(true);
//Connected to server
connection.connect();
//downloading image
InputStream input = connection.getInputStream();
//converting image to bitmap
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result != null) {
result = mBitmap;
new ImageServer(mContext).save(result);
}
}
}
EDIT :
Tried to use picasso :
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
count=0;
if (response.has("message")) {
JSONObject userJson = null;
String message = null;
count++;
try {
if (response.getString("message").equalsIgnoreCase(KEY_SUCCESS)) {
Toast.makeText(mContext, "user authenticated successfully", Toast.LENGTH_LONG).show();
userJson = response.getJSONObject("user");
String userId = userJson.getString("user_id");
String userName = userJson.getString("user_name");
String profileImage = userJson.getString("profile_image");
String mobileNo = userJson.getString("mobile_no");
String url = ServiceUrl.getBaseUrl() + ServiceUrl.getImageUserUrl() + profileImage;
Log.e("url", url);
User user = new User();
user.setmUserId(userId);
user.setmUserName(userName);
user.setmProfileImage(profileImage);
user.setmMobileNo(mobileNo);
SharedPreferences.Editor editor = mContext.getSharedPreferences("username",mContext.MODE_PRIVATE).edit();
editor.putString("UserUsername",userName);
editor.commit();
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
File f = new File(mContext.getCacheDir(), "Profile");
f.createNewFile();
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
Log.e("File",String.valueOf(f));
}
catch (IOException e)
{
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
Picasso.with(mContext).load(url).into(target);
Toast.makeText(mContext, "user authenticated successfully", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
mContext.startActivity(intent);
Picasso.with(mContext).cancelRequest(target);
}
}
What's going wrong?
Try this I am getting image by this method.
URL url1l = new URL("<Image url>");
URLConnection connection = url1l.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream is = new BufferedInputStream(connection.getInputStream());
bitmap = BitmapFactory.decodeStream(is);
The most likely reason is that you are getting an error from the server or that the data you are getting back cannot be decoded. First of all, check the response code after the connection is opened:
connection.connect();
int respCode = connection.getResponseCode();
Log.d("resp code", "response code " + respCode);
If you get anything other than 200, then something is wrong with retrieving data (wrong url, auth, or server error). If you do get 200, then the issue is with the data you are receiving. Read the data into a byte array and dump it into a file to examine.
First check with image is really exists or not as #aman grover said
if available use Picasso Lib to download image and from url.
here is sample code
private Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
//Note : here you can get Bitmap
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
private void someMethod() {
Picasso.with(this).load("url").into(target);
}
#Override
public void onDestroy() { // could be in onPause or onStop
Picasso.with(this).cancelRequest(target);
super.onDestroy();
}

Row cannot be updated

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.

Image taken from camera cannot display in image view android 5.0, but working in android 4.4

This is my activity code, when click on capture picture button, it will load camera from your phone. after i take a picture with camera, the picture will show at the imageView. Then i will click upload image picture button to upload my picture to server. Here the problem i faced, the code works well on all android version 4.4 and below, when i test this code with android 5.0, the picture taken from camera wasn't show on the imageView. I had tried many solution and yet keep fail. Can anyone help me with this? thank you.
Activity code
public class TestUpload extends Activity implements OnItemSelectedListener {
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String IMAGE_DIRECTORY_NAME = "Hello camera";
private Uri fileUri;
private ImageView imgPreview;
private Button btnCapturePicture, btnUploadImage;
private EditText itemname;
private EditText description;
private EditText price;
private EditText contact;
private String randNum, uname;
Random random = new Random();
private static final String _CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
private static final int RANDOM_STR_LENGTH = 12;
private Spinner spinCat, spinLoc;
private String [] Category = {"IT Gadgets","Men Fashion","Women Fashion","Beauty","Sports","Cars and Motors","Furnitures","Music Instrument","Books","Property","Photography","Games and Toys","kids and Baby","Others"};
private String [] Location = {"Kuala Lumpur","Melacca","Johor","Selangor","Kelantan","Kedah","Negeri Sembilan",
"Pahang","Perak","Perlis","Penang","Sabah","Sarawak","Terengganu"};
private static final String TAG_SUCCESS = "success";
JSONParser2 jsonParser2 = new JSONParser2();
private static String url_create_image = "http://gemini888.tk/GP_trade_api_v2/image_connect/create_product.php";
private SweetAlertDialog pDialog;
long totalSize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload_test);
ActionBar ab = getActionBar();
ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#96ead7")));
ab.setDisplayHomeAsUpEnabled(true);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
btnCapturePicture = (Button) findViewById(R.id.btn_camera);
btnUploadImage = (Button) findViewById(R.id.btn_upload);
itemname = (EditText) findViewById(R.id.input_upload_item_name);
description = (EditText) findViewById(R.id.input_item_desc);
price = (EditText) findViewById(R.id.upload_input_item_price);
contact = (EditText) findViewById(R.id.input_contact);
spinCat = (Spinner) findViewById(R.id.spin_category);
spinLoc = (Spinner) findViewById(R.id.spin_location);
ArrayAdapter<String> adapter_Category = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, Category);
ArrayAdapter<String> adapter_Location = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, Location);
adapter_Category.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter_Location.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinCat.setAdapter(adapter_Category);
spinLoc.setAdapter(adapter_Location);
spinCat.setOnItemSelectedListener(this);
spinLoc.setOnItemSelectedListener(this);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String, String> user = new HashMap<String, String>();
user = db.getUserDetails();
uname = user.get("uname");
//timeStamp = new SimpleDateFormat ("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
randNum = getRandomString();
//capture image button click event
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//capture image
captureImage();
}
});
btnUploadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//uploading the file to server
new UploadFileToServer().execute();
}
});
}
//capturing Camera image will lunch camera app request image capture
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
//Start image capture intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
//Receiving activity result method will be called after closing the camera
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//if the result i capture image
if(requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
//success capture image, display it on imageview
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
//user cancel image capture
Toast.makeText(getApplicationContext(), "User cancelled image capture", Toast.LENGTH_SHORT).show();
} else {
//failed to capture image
Toast.makeText(getApplicationContext(), "Sorry, failed to capture image", Toast.LENGTH_SHORT).show();
}
}
}
//Display image from a path to imageview
private void previewCapturedImage() {
imgPreview.setVisibility(View.VISIBLE);
//bitmap factory
BitmapFactory.Options options = new BitmapFactory.Options();
//downsize image as it throws Outofmemory execption for larger images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
imgPreview.setImageBitmap(bitmap);
}
//store the file url as it will be null after returning from camera app
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//save file url in bundle as it will be null on screen orientation change
outState.putParcelable("file_uri", fileUri);
}
//restore the fileUri again
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//get the Urifile
fileUri = savedInstanceState.getParcelable("file_uri");
}
//create file Uri to store image
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
//returning image
private File getOutputMediaFile(int type) {
//External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), UserFunctions.IMAGE_DIRECTORY_NAME);
//create the storage directory if it does not exist
if(!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Failed create" + UserFunctions.IMAGE_DIRECTORY_NAME + "directory");
return null;
}
}
//Create a media file name
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator + uname + randNum + ".jpg");
} else {
return null;
}
return mediaFile;
}
//upload image to server
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new SweetAlertDialog(TestUpload.this, SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
pDialog.setTitleText("Picture uploading, please wait..");
//pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(Void...params) {
String iname = itemname.getText().toString();
String des = description.getText().toString();
String iprice = price.getText().toString();
String icontact = contact.getText().toString();
String cat = spinCat.getSelectedItem().toString();
String loc = spinLoc.getSelectedItem().toString();
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("name", iname));
param.add(new BasicNameValuePair("description", des));
param.add(new BasicNameValuePair("price", iprice));
param.add(new BasicNameValuePair("username", uname));
param.add(new BasicNameValuePair("category", cat));
param.add(new BasicNameValuePair("location", loc));
param.add(new BasicNameValuePair("timestamp", randNum));
param.add(new BasicNameValuePair("contact", icontact));
JSONObject json = jsonParser2.makeHttpRequest(url_create_image,
"POST", param);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Log.d("Create Response", "success");
} else {
// failed to create product
Toast.makeText(getApplicationContext(),"failed",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return uploadFile();
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
super.onPostExecute(result);
}
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(UserFunctions.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
setProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(fileUri.getPath());
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("http://gemini888.tk"));
entity.addPart("email", new StringBody("thegemini888#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
public String getRandomString() {
StringBuffer randStr = new StringBuffer();
for (int i =0; i<RANDOM_STR_LENGTH; i++) {
int number = getRandomNumber();
char ch = _CHAR.charAt(number);
randStr.append(ch);
}
return randStr.toString();
}
private int getRandomNumber() {
int randomInt = 0;
randomInt = random.nextInt(_CHAR.length());
if (randomInt - 1 == -1) {
return randomInt;
} else {
return randomInt - 1;
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
spinCat.setSelection(position);
String CatList = (String) spinCat.getSelectedItem();
CatList.toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go home
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
in captureImage() method try this.
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
//Start image capture intent
}
//first of all create a directory to store your captured Images
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/PGallery");
if (!myDir.exists()) {
myDir.mkdirs();
}
//Give name to your captured Image
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss",java.util.Locale.getDefault());
Date date = new Date();
String sDate = formatter.format(date);
imageName = "PRAVA"+sDate+".jpg";
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
filePath = new File(myDir,imageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(filePath));
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
catch (ActivityNotFoundException e) {
String errorMessage = "Whoops - your device doesn't support capturing images!";
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
On Actvity Result:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
ImagePath = filePath.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(ImagePath, bitmapOptions);
ImageView mImageView = (ImageView) findViewById(R.id.ivCamreaPic);
mImageView.setImageBitmap(bitmap);
}

Categories

Resources