Capture image rotate after upload - android

I am uploading image to server but image is rotate after uploaded to server Even preview is showing correct.
So many people facing this problem i found this link but didn't work. And there is many solution but i am not figure out how to fit in my code.
Please help me.
Here is my code
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.fonts.Text.MyTextView;
import com.generalClass.files.UploadFile;
import com.hwindiapp.driver.db.sqLite.DBConnect;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
public class AddVehicleDocActivity extends AppCompatActivity {
private static final int FILE_SELECT_CODE = 124;
private Toolbar mToolbar;
TextView text_header;
MyTextView insuranceHTxt;
MyTextView permitHTxt;
MyTextView vRegHTxt;
MyTextView insNotFoundTxt;
MyTextView permitNotFoundTxt;
MyTextView vRegNotFoundTxt;
DBConnect dbConnect;
Button insBtn;
Button permitBtn;
Button vRegBtn;
LinearLayout insImgVIew;
LinearLayout permitImgVIew;
LinearLayout vRegImgVIew;
String language_labels_get_frm_sqLite = "";
String LBL_DOCUMENTS_TXT_str = "";
String LBL_YOUR_INSURANCE_TXT_str = "";
String LBL_WRONG_FILE_SELECTED_TXT_str = "";
String LBL_LOADING_TXT_str = "";
String LBL_YOUR_PERMIT_TXT_str = "";
String LBL_VEHICLE_REG_TXT_str = "";
String LBL_NOT_FOUND_TXT_str = "";
String LBL_BTN_OK_TXT_str = "";
String LBL_ERROR_TXT_str = "";
String LBL_TRY_AGAIN_LATER_TXT_str = "";
String LBL_DOC_UPLOAD_SUCCESS_TXT_str = "";
String LBL_ADD_TXT_str = "";
String LBL_EDIT_TXT_str = "";
String LBL_SUCCESS_TXT_str = "";
String LBL_BTN_TRIP_CANCEL_CONFIRM_TXT_str = "";
String LBL_NOTE_UPLOAD_DOC_TXT_str = "";
String LBL_CANCEL_TXT_str = "";
String currentDocType = "";
String carJson_str = "";
String vIns = "";
String vPermit = "";
String vReg = "";
android.support.v7.app.AlertDialog alertDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_vehicle_doc);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
dbConnect = new DBConnect(this, "UC_Partner_Labels.db");
text_header = (TextView) findViewById(R.id.text_header);
insuranceHTxt = (MyTextView) findViewById(R.id.insuranceHTxt);
permitHTxt = (MyTextView) findViewById(R.id.permitHTxt);
vRegHTxt = (MyTextView) findViewById(R.id.vRegHTxt);
insNotFoundTxt = (MyTextView) findViewById(R.id.insNotFoundTxt);
permitNotFoundTxt = (MyTextView) findViewById(R.id.permitNotFoundTxt);
vRegNotFoundTxt = (MyTextView) findViewById(R.id.vRegNotFoundTxt);
insImgVIew = (LinearLayout) findViewById(R.id.insImgArea);
permitImgVIew = (LinearLayout) findViewById(R.id.permitImgArea);
vRegImgVIew = (LinearLayout) findViewById(R.id.vRegImgArea);
insBtn = (Button) findViewById(R.id.insBtn);
permitBtn = (Button) findViewById(R.id.permitBtn);
vRegBtn = (Button) findViewById(R.id.vRegBtn);
insBtn.setOnClickListener(new setOnClickAct());
permitBtn.setOnClickListener(new setOnClickAct());
vRegBtn.setOnClickListener(new setOnClickAct());
insImgVIew.setOnClickListener(new setOnClickAct());
permitImgVIew.setOnClickListener(new setOnClickAct());
vRegImgVIew.setOnClickListener(new setOnClickAct());
carJson_str = getIntent().getStringExtra("CarJson");
/* Set Labels */
getLanguageLabelsFrmSqLite();
/* Set Labels Finished */
ImageView back_navigation = (ImageView) findViewById(R.id.back_navigation);
back_navigation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AddVehicleDocActivity.super.onBackPressed();
}
});
Log.d("carJson_str", ":" + carJson_str);
try {
parseCarJson(carJson_str);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getLanguageLabelsFrmSqLite() {
Cursor cursor = dbConnect.execQuery("select vValue from labels WHERE vLabel=\"Language_labels\"");
cursor.moveToPosition(0);
language_labels_get_frm_sqLite = cursor.getString(0);
JSONObject obj_language_labels = null;
try {
obj_language_labels = new JSONObject(language_labels_get_frm_sqLite);
LBL_DOCUMENTS_TXT_str = obj_language_labels.getString("LBL_DOCUMENTS_TXT");
LBL_YOUR_INSURANCE_TXT_str = obj_language_labels.getString("LBL_YOUR_INSURANCE_TXT");
LBL_WRONG_FILE_SELECTED_TXT_str = obj_language_labels.getString("LBL_WRONG_FILE_SELECTED_TXT");
LBL_LOADING_TXT_str = obj_language_labels.getString("LBL_LOADING_TXT");
LBL_YOUR_PERMIT_TXT_str = obj_language_labels.getString("LBL_YOUR_PERMIT_TXT");
LBL_VEHICLE_REG_TXT_str = obj_language_labels.getString("LBL_VEHICLE_REG_TXT");
LBL_NOT_FOUND_TXT_str = obj_language_labels.getString("LBL_NOT_FOUND_TXT");
LBL_BTN_OK_TXT_str = obj_language_labels.getString("LBL_BTN_OK_TXT");
LBL_ERROR_TXT_str = obj_language_labels.getString("LBL_ERROR_TXT");
LBL_TRY_AGAIN_LATER_TXT_str = obj_language_labels.getString("LBL_TRY_AGAIN_LATER_TXT");
LBL_DOC_UPLOAD_SUCCESS_TXT_str = obj_language_labels.getString("LBL_DOC_UPLOAD_SUCCESS_TXT");
LBL_ADD_TXT_str = obj_language_labels.getString("LBL_ADD_TXT");
LBL_EDIT_TXT_str = obj_language_labels.getString("LBL_EDIT_TXT");
LBL_SUCCESS_TXT_str = obj_language_labels.getString("LBL_SUCCESS_TXT");
LBL_BTN_TRIP_CANCEL_CONFIRM_TXT_str = obj_language_labels.getString("LBL_BTN_TRIP_CANCEL_CONFIRM_TXT");
LBL_NOTE_UPLOAD_DOC_TXT_str = obj_language_labels.getString("LBL_NOTE_UPLOAD_DOC_TXT");
LBL_CANCEL_TXT_str = obj_language_labels.getString("LBL_CANCEL_TXT");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (obj_language_labels != null) {
text_header.setText("" + LBL_DOCUMENTS_TXT_str);
insuranceHTxt.setText("" + LBL_YOUR_INSURANCE_TXT_str);
permitHTxt.setText("" + LBL_YOUR_PERMIT_TXT_str);
vRegHTxt.setText("" + LBL_VEHICLE_REG_TXT_str);
insNotFoundTxt.setText("" + LBL_NOT_FOUND_TXT_str);
permitNotFoundTxt.setText("" + LBL_NOT_FOUND_TXT_str);
vRegNotFoundTxt.setText("" + LBL_NOT_FOUND_TXT_str);
insBtn.setText(LBL_ADD_TXT_str);
permitBtn.setText(LBL_ADD_TXT_str);
vRegBtn.setText(LBL_ADD_TXT_str);
}
}
public void parseCarJson(String carJson) throws JSONException {
JSONObject obj_profile = new JSONObject(carJson);
vIns = obj_profile.getString("vInsurance");
vPermit = obj_profile.getString("vPermit");
vReg = obj_profile.getString("vRegisteration");
if (vIns == null || vIns.equals("")) {
insNotFoundTxt.setVisibility(View.VISIBLE);
} else {
setDocView(0);
}
if (vPermit == null || vPermit.equals("")) {
permitNotFoundTxt.setVisibility(View.VISIBLE);
} else {
setDocView(1);
}
if (vReg == null || vReg.equals("")) {
vRegNotFoundTxt.setVisibility(View.VISIBLE);
} else {
setDocView(2);
}
}
public void setDocView(int id) {
if (id == 0) {
insNotFoundTxt.setVisibility(View.GONE);
insBtn.setText(LBL_EDIT_TXT_str);
insImgVIew.setVisibility(View.VISIBLE);
} else if (id == 1) {
permitNotFoundTxt.setVisibility(View.GONE);
permitBtn.setText(LBL_EDIT_TXT_str);
permitImgVIew.setVisibility(View.VISIBLE);
} else if (id == 2) {
vRegNotFoundTxt.setVisibility(View.GONE);
vRegBtn.setText(LBL_EDIT_TXT_str);
vRegImgVIew.setVisibility(View.VISIBLE);
}
}
public class setOnClickAct implements View.OnClickListener {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.insBtn:
currentDocType = "vInsurance";
chooseFIle();
break;
case R.id.permitBtn:
currentDocType = "vPermit";
chooseFIle();
break;
case R.id.vRegBtn:
currentDocType = "vRegisteration";
chooseFIle();
break;
case R.id.insImgArea:
openDocument(vIns);
break;
case R.id.permitImgArea:
openDocument(vPermit);
break;
case R.id.vRegImgArea:
openDocument(vReg);
break;
}
}
}
public void openDocument(String documentName) {
Log.d("Open doc","::"+CommonUtilities.SERVER_URL_VEHICLE_DOCS + getIntent().getStringExtra("iDriverVehicleId") + "/" + documentName);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(CommonUtilities.SERVER_URL_VEHICLE_DOCS + getIntent().getStringExtra("iDriverVehicleId") + "/" + documentName));
startActivity(browserIntent);
}
public void chooseFIle() {
boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat) {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, FILE_SELECT_CODE);
} else {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, FILE_SELECT_CODE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == FILE_SELECT_CODE) {
Uri uri = data.getData();
// Log.d("Path", "::" + uri.getPath());
// Log.d("Path", "::" + getPath(uri));
String filePath = "";
filePath = (getPath(uri) == null) ? uri.getPath() : getPath(uri);
// Log.d("Ext", ":" + getFileExt(filePath));
final ArrayList<String[]> paramsList = new ArrayList<>();
paramsList.add(generateImageParams("iDriverVehicleId", "" + getIntent().getStringExtra("iDriverVehicleId")));
paramsList.add(generateImageParams("type", "UploadVehicleDoc"));
paramsList.add(generateImageParams("iDriverId", getIntent().getStringExtra("UserID")));
paramsList.add(generateImageParams("DocUploadType", currentDocType));
if (getFileExt(filePath).equalsIgnoreCase("jpg") || getFileExt(filePath).equalsIgnoreCase("gif") || getFileExt(filePath).equalsIgnoreCase("png")
|| getFileExt(filePath).equalsIgnoreCase("jpeg") || getFileExt(filePath).equalsIgnoreCase("bmp") || getFileExt(filePath).equalsIgnoreCase("pdf")
|| getFileExt(filePath).equalsIgnoreCase("doc") || getFileExt(filePath).equalsIgnoreCase("docx")) {
File selectedFile = new File(filePath);
if (selectedFile != null) {
android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(
AddVehicleDocActivity.this);
alertDialogBuilder.setTitle(LBL_BTN_TRIP_CANCEL_CONFIRM_TXT_str);
final String finalFilePath = filePath;
alertDialogBuilder
.setMessage(selectedFile.getName() + "\n" + LBL_NOTE_UPLOAD_DOC_TXT_str)
.setCancelable(true)
.setNegativeButton(LBL_CANCEL_TXT_str, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
alertDialog.dismiss();
}
})
.setPositiveButton(LBL_BTN_OK_TXT_str, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertDialog.dismiss();
new uploadDocument(finalFilePath, currentDocType + "." + getFileExt(finalFilePath), paramsList).execute();
}
});
alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else {
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
} else {
// showErrorOnSelection();
showMessage(LBL_ERROR_TXT_str, LBL_WRONG_FILE_SELECTED_TXT_str);
}
}
}
}
public String[] generateImageParams(String key, String content) {
String[] tempArr = new String[2];
tempArr[0] = key;
tempArr[1] = content;
return tempArr;
}
public class uploadDocument extends AsyncTask<String, String, String> {
String selectedPath;
String responseString = "";
ProgressDialog myPDialog;
String temp_File_Name = "";
ArrayList<String[]> paramsList;
public uploadDocument(String selectedPath, String temp_File_Name, ArrayList<String[]> paramsList) {
this.selectedPath = selectedPath;
this.temp_File_Name = temp_File_Name;
this.paramsList = paramsList;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
myPDialog = new ProgressDialog(AddVehicleDocActivity.this, R.style.DialogTheme_custom);
myPDialog.setMessage("" + LBL_LOADING_TXT_str);
myPDialog.setCancelable(false);
myPDialog.setCanceledOnTouchOutside(false);
myPDialog.show();
}
#Override
protected String doInBackground(String... strings) {
responseString = new UploadFile().uploadImageAsFile(selectedPath, temp_File_Name, "vFile", paramsList);
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
myPDialog.dismiss();
Log.d("responseString", "::" + responseString);
if (responseString != null && !responseString.equals("")) {
try {
JSONObject obj_temp = new JSONObject(responseString);
String action_str = obj_temp.getString("Action");
String fileName_str = obj_temp.getString("vFileName");
if (action_str.equals("1")) {
showMessage(LBL_SUCCESS_TXT_str, LBL_DOC_UPLOAD_SUCCESS_TXT_str);
JSONObject obj_CarJson = new JSONObject(carJson_str);
if (currentDocType.equals("vInsurance")) {
obj_CarJson.remove("vInsurance");
obj_CarJson.put("vInsurance", fileName_str);
vIns = fileName_str;
setDocView(0);
} else if (currentDocType.equals("vPermit")) {
obj_CarJson.remove("vPermit");
obj_CarJson.put("vPermit", fileName_str);
vPermit = fileName_str;
setDocView(1);
} else if (currentDocType.equals("vRegisteration")) {
obj_CarJson.remove("vRegisteration");
obj_CarJson.put("vRegisteration", fileName_str);
vReg = fileName_str;
setDocView(2);
}
obj_CarJson.remove("eStatus");
obj_CarJson.put("eStatus", "Inactive");
carJson_str = obj_CarJson.toString();
Intent setData = new Intent();
setData.putExtra("CarJson", carJson_str);
setData.putExtra("DriverProfileData", obj_temp.getString("DriverProfileData").toString());
setData.putExtra("iDriverVehicleId", "" + getIntent().getStringExtra("iDriverVehicleId"));
setResult(RESULT_OK, setData);
// Driver_main_profile.updated_json_responseString_profile = obj_profileJson.toString();
//
// Driver_main_profile.driverDocUpdated = true;
} else {
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
} catch (JSONException e) {
e.printStackTrace();
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
} else {
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
}
}
public String getFileExt(String fileName) {
return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
}
public String getPath(Uri uri) {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
} else {
return null;
}
}
public void showMessage(String title_str, String content_str) {
android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(
AddVehicleDocActivity.this);
alertDialogBuilder.setTitle(title_str);
alertDialogBuilder
.setMessage(content_str)
.setCancelable(true)
.setPositiveButton(LBL_BTN_OK_TXT_str, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertDialog.dismiss();
}
});
alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
Here is my Upload code
public class UploadFile {
public String uploadImageAsFile(String sourceFileUri, String fileName, String imageParamKey, ArrayList<String[]> params) {
ExifInterface exif = null; //Since API Level 5
try {
exif = new ExifInterface(sourceFileUri);
} catch (IOException e) {
e.printStackTrace();
}
String exifImage = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
String responseString = "";
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(exifImage));
byte[] data;
try {
data = convertToByteArray(inputStream);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(CommonUtilities.SERVER_URL);
InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), fileName);
MultipartEntity multipartEntity = new MultipartEntity(/*HttpMultipartMode.BROWSER_COMPATIBLE,"9999999999", Charset.defaultCharset()*/);
for (int i = 0; i < params.size(); i++) {
String[] paramsArr = params.get(i);
multipartEntity.addPart(paramsArr[0], new StringBody(paramsArr[1]));
}
ContentBody cbFile = new FileBody(new File(exifImage)/*, "multipart/form-data"*/);
multipartEntity.addPart(imageParamKey, cbFile);
httpPost.setEntity(multipartEntity);
// httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Test Browser");
// httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
// httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY);
// httpPost.setHeader("Content-Type", "multipart/form-data");
// httpPost.setHeader("Content-Type", "image/png");
// httpPost.setHeader("Connection", "Keep-Alive");
// httpPost.setRequestProperty("ENCTYPE", "multipart/form-data");
// httpPost.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// httpPost.addHeader("Content-Type", "multipart/form-data;charset=UTF-8;boundary=654654");
// httpPost.setHeader("Connection", "Keep-Alive");
// httpPost.setHeader("ENCTYPE", "multipart/form-data");
HttpResponse httpResponse = httpClient.execute(httpPost);
// Handle response back from script.
if (httpResponse != null) {
Log.d("success", "success:" + httpResponse.toString());
responseString = EntityUtils.toString(httpResponse.getEntity());
} else { // Error, no response.
Log.d("Failed", "failed:" + httpResponse.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
return responseString;
}
private byte[] convertToByteArray(InputStream inputStream) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int next = inputStream.read();
while (next > -1) {
bos.write(next);
next = inputStream.read();
}
bos.flush();
return bos.toByteArray();
}
/**
* #param encodedString
* #return bitmap (from given string)
*/
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;
}
}
}

You shouldn't rotate the image after upload. You need to rotate it before. The preview is correct maybe because you're respecting Exif values when showing it. But the server isn't.
You need to rotate the image according to it's exif rotation:
https://stackoverflow.com/a/20480741/3410697
And only then you should upload it to the server

Call this function where you get path of image
public void setImage(String _path) {
int orientation = CustomImageUtil.getExifOrientation(_path);
BitmapFactory.Options resample = new BitmapFactory.Options();
resample.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(_path, resample);
if (orientation == 90) {
bitmap = CustomImageUtil.rotate(bitmap, 90);
} else if (orientation == 180) {
bitmap = CustomImageUtil.rotate(bitmap, 180);
} else if (orientation == 270) {
bitmap = CustomImageUtil.rotate(bitmap, 270);
}
// use your bitmap here
}
CustomImageUtil.class:
public class CustomImageUtil {
public static String getRealPathFromURI(Context context,Uri contentURI) {
String result;
Cursor cursor = context.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
// method for bitmap to base64
public static String encodeTobase64(Bitmap image) {
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 60, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
/**
* getExifOrientation -- Roate the image on the right angel
* #param filepath -- path of the file to be rotated
* #return
*/
public static int getExifOrientation(String filepath) {
int degree = 0;
ExifInterface exif = null;
try {
exif = new ExifInterface(filepath);
} catch (IOException ex) {ex.printStackTrace();
}
if (exif != null) {
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, -1);
if (orientation != -1) {
// We only recognize a subset of orientation tag values.
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
}
}
return degree;
}
// Rotates the bitmap by the specified degree.
// If a new bitmap is created, the original bitmap is recycled.
public static Bitmap rotate(Bitmap b, int degrees) {
if (degrees != 0 && b != null) {
Matrix m = new Matrix();
m.setRotate(degrees, (float) b.getWidth() / 2,
(float) b.getHeight() / 2);
try {
Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(),
b.getHeight(), m, true);
if (b != b2) {
b.recycle();
b = b2;
}
} catch (OutOfMemoryError ex) {ex.printStackTrace();
}
}
return b;
}
}
To convert Bitmap to Uri
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}

Related

Android saving audio/mp3 file to external storage

I have question about saving audio/mp3
file to external storage
after saving the file it show in external storage
but when I open any android music player the file not showing there
I try to change the folder to "/storage/emulated/0/Music/" still not showing
even on download folder nothing.
the app is for download music from YouTube using API
public class DownloadedActivity extends AppCompatActivity implements AdapterMusicDownloaded.ClickCallBack, View.OnClickListener {
private RecyclerView lvManager;
private AdapterMusicDownloaded adapterMusicSearch;
private ArrayList<ItemMusicDownloaded> arrayList = new ArrayList<>();
private LinearLayout llEmptyFile;
private static final String AUTHORITY = "com.free.music.downloader" + ".fileprovider";
public static final String PATH = Environment.getExternalStorageDirectory().toString() + "/FreeMusic/";
public static final String UPDATE_MUSIC = "update_music";
private ImageView imgBackSearch;
private InterstitialAd mInterstitialAd;
private AdView adView;
private ProgressBar loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_downloaded_songs);
initViews();
}
private void initViews() {
loading = findViewById(R.id.loading);
adView = findViewById(R.id.adView);
initAdsFull();
MobileAds.initialize(this, getResources().getString(R.string.mobile_id));
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
llEmptyFile = findViewById(R.id.ll_empty_file);
imgBackSearch = findViewById(R.id.img_back_downloaded);
imgBackSearch.setOnClickListener(this);
lvManager = findViewById(R.id.lv_main);
LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setOrientation(LinearLayoutManager.VERTICAL);
adapterMusicSearch = new AdapterMusicDownloaded(arrayList, this);
adapterMusicSearch.setCallBack(this);
lvManager.setLayoutManager(manager);
lvManager.setAdapter(adapterMusicSearch);
LoadAsync loadAsync = new LoadAsync();
loadAsync.execute();
}
#Override
public void clickItemMusic(int position) {
Intent playIntent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
final File photoFile = new File(arrayList.get(position).getLink());
Uri photoURI = FileProvider.getUriForFile(this, AUTHORITY, photoFile);
playIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
playIntent.setDataAndType(photoURI, "audio/*");
} else {
playIntent.setDataAndType(Uri.parse(arrayList.get(position).getLink()), "audio/*");
}
startActivity(playIntent);
}
#Override
public void clickOptionItemMusic(final int postion, View view) {
PopupMenu popupMenu = new PopupMenu(this, view);
popupMenu.inflate(R.menu.menu_option_main);
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete:
File file = new File(arrayList.get(postion).getLink());
boolean deleted = file.delete();
if (deleted) {
Toast.makeText(DownloadedActivity.this, getResources().getString(R.string.delete_finish), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(DownloadedActivity.this, getResources().getString(R.string.delete_error), Toast.LENGTH_SHORT).show();
}
arrayList.remove(postion);
adapterMusicSearch.notifyDataSetChanged();
break;
case R.id.menu_share_main:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
final File photoFile = new File(arrayList.get(postion).getLink());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri photoURI = FileProvider.getUriForFile(DownloadedActivity.this, AUTHORITY, photoFile);
shareIntent.putExtra(Intent.EXTRA_STREAM, photoURI);
} else {
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(photoFile));
}
shareIntent.setType("audio/*");
startActivity(Intent.createChooser(shareIntent, "Share music"));
break;
default:
break;
}
return false;
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.img_back_downloaded) {
onBackPressed();
}
}
#Override
public void onBackPressed() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
finish();
}
}
private class LoadAsync extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
llEmptyFile.setVisibility(View.GONE);
loading.setVisibility(View.VISIBLE);
}
#SuppressLint("WrongThread")
#Override
protected String doInBackground(Void... voids) {
arrayList.clear();
File f = new File(PATH);
File[] files = f.listFiles();
if (f.exists()) {
if (files.length <= 0) {
Log.d("sizearrList", "0");
return "OK";
} else {
Log.d("sizearrList", "2");
arrayList.clear();
Arrays.sort(files, new Comparator() {
public int compare(Object o1, Object o2) {
if (((File) o1).lastModified() > ((File) o2).lastModified()) {
return -1;
} else if (((File) o1).lastModified() < ((File) o2).lastModified()) {
return +1;
} else {
return 0;
}
}
});
for (File aFile : files) {
if (!aFile.isDirectory()) {
String name = aFile.getName();
String path = aFile.getPath();
getTimeVideo(aFile.getAbsolutePath());
Date lastModified = getFileLastModified(path);
arrayList.add(new ItemMusicDownloaded(name, path, lastModified, getTimeVideo(aFile.getAbsolutePath())))
;
} else {
Log.d("myLog", "Do not add");
}
}
Log.d("sizeArrsss", arrayList.size() + "");
for (int i = 0; i < arrayList.size(); i++) {
Log.d("sizeArr", arrayList.get(i).getTitle());
}
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (arrayList.size() == 0) {
llEmptyFile.setVisibility(View.VISIBLE);
} else {
llEmptyFile.setVisibility(View.GONE);
}
loading.setVisibility(View.GONE);
adapterMusicSearch.notifyDataSetChanged();
}
}
public static Date getFileLastModified(String pathFile) {
File file = new File(pathFile);
return new Date(file.lastModified());
}
private void initAdsFull() {
mInterstitialAd = new InterstitialAd(this);
MobileAds.initialize(this,
getResources().getString(R.string.mobile_id));
mInterstitialAd.setAdUnitId(getResources().getString(R.string.ads_full));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
finish();
}
});
}
public long getTimeVideo(String pathFile) {
try {
MediaPlayer mp = MediaPlayer.create(this, Uri.parse(pathFile));
int duration = mp.getDuration();
mp.release();
return duration;
} catch (Exception e) {
return 0;
}
}
}
public class DownloadVideoAsyn extends AsyncTask<String, Integer, String> {
private String title;
private int check;
private NotificationCompat.Builder builder;
private NotificationManager manager;
private String CHANNEL_ID = "download_video_tiktok_auto";
private String pathVideo = title + ".mp3";
private int id = 1232;
private Context mContext;
private NotificationChannel mChannel;
Notification noti;
public DownloadVideoAsyn(String title, int check, Context context) {
this.title = title;
this.check = check;
this.mContext = context;
}
public static final String PATH = Environment.getExternalStorageDirectory().toString() + "/FreeMusic/";
private EventDownloadVideoCallBack callBack;
public void setCallBack(EventDownloadVideoCallBack callBack) {
this.callBack = callBack;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (check == 2) {
manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(mContext, CHANNEL_ID);
Intent iCancel = new Intent();
id = id + 1;
iCancel.putExtra("id", id);
iCancel.putExtra("pathVideo", pathVideo);
iCancel.setAction("CANCEL_ACTION");
PendingIntent PICancel = PendingIntent.getBroadcast(mContext, 0, iCancel, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setSmallIcon(R.drawable.ic_download)
.setContentTitle(title.replace("'", "") + ".mp3")
.setContentText(mContext.getString(R.string.download))
.setChannelId(CHANNEL_ID)
.setPriority(Notification.PRIORITY_MAX)
.addAction(R.drawable.ic_cancel, "Cancel", PICancel)
.setAutoCancel(true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
mChannel = new NotificationChannel(CHANNEL_ID, "channel-name", importance);
mChannel.setSound(null, null);
manager.createNotificationChannel(mChannel);
}
}
}
#Override
protected String doInBackground(String... strings) {
String link = strings[0];
try {
URL url = new URL(link);
// check folder exist
File folder = new File(PATH);
if (!folder.exists()) {
folder.mkdir();
}
String path = PATH + title.replace("'", "") + ".mp3";
File file = new File(path);
long total = 0;
FileOutputStream fileOutputStream = new FileOutputStream(file);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
int fileLength = connection.getContentLength();
//=============================
byte[] b = new byte[1024];
int count = inputStream.read(b);
while (count != -1) {
total += count;
fileOutputStream.write(b, 0, count);
count = inputStream.read(b);
int progress = (int) (total * 100 / fileLength);
publishProgress(progress);
if (check == 2) {
builder.setProgress(100, progress, false);
builder.setContentText(mContext.getString(R.string.download) + " " + progress + "%");
noti = builder.build();
noti.flags = Notification.FLAG_ONLY_ALERT_ONCE;
manager.notify(id, noti);
if (progress == 100) {
manager.cancel(id);
}
}
}
inputStream.close();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
try {
URL url = new URL(link);
// check folder exist
File folder = new File(PATH);
if (!folder.exists()) {
folder.mkdir();
}
Date currentTime = Calendar.getInstance().getTime();
title = currentTime.getTime() + "";
String path = PATH + title + ".mp3";
File file = new File(path);
long total = 0;
FileOutputStream fileOutputStream = new FileOutputStream(file);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
int fileLength = connection.getContentLength();
//=============================
byte[] b = new byte[1024];
int count = inputStream.read(b);
while (count != -1) {
total += count;
fileOutputStream.write(b, 0, count);
count = inputStream.read(b);
int progress = (int) (total * 100 / fileLength);
publishProgress(progress);
if (check == 2) {
builder.setProgress(100, progress, false);
builder.setContentText(mContext.getString(R.string.download) + " " + progress + "%");
noti = builder.build();
noti.flags = Notification.FLAG_ONLY_ALERT_ONCE;
manager.notify(id, noti);
if (progress == 100) {
manager.cancel(id);
}
}
}
inputStream.close();
fileOutputStream.close();
} catch (Exception ex) {
return null;
}
}
return PATH + title + ".mp3";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
Uri uri = Uri.parse("file://" + "/storage/emulated/0/FreeMusic/" + s);
Intent scanFileIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
mContext.sendBroadcast(scanFileIntent);
callBack.downloadVideoFinish(s);
}
else {
callBack.downloadVideoFail("Error");
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (check == 1) {
if (callBack != null) {
callBack.updateProgress(values[0]);
}
}
}
public interface EventDownloadVideoCallBack {
void downloadVideoFinish(String s);
void updateProgress(int pro);
void downloadVideoFail(String fail);
}
}

Memory usage increases with every reload of intent in Android. Why?

I have an activity/intent in which a text file (which contains a JSON array) is read from the device.
On every reload another row from the array is being processes.
The text file isn't that large (20 Kb) and is being downloaded in the MainActivity together with some images (up to 50) which are between 20 and 70 Kb.
Everytime the intent is reloaded and another row is processes, another image is being loaded into an ImageView. Also several TextViews are updated with Strings that are read from the JSON array.
The issue is that with every reload of the intent, the memory usage increases with about 1 Mb.
I show this through the use of:
Runtime runtime = Runtime.getRuntime();
long usedMemory=runtime.totalMemory() / (1024 * 1024);
The Bitmap is recycled,
BufferedWriter is closed,
FileInputStream is closed,
BufferedReader is closed and
InputStreamReader is closed
What am I missing that causes the memory usage to increase?
This is the code form the Activity:
public class LoadRaaplijstActivity extends AppCompatActivity {
private TextView locatieText;
private TextView totaalText;
private TextView inhoudText;
private TextView descriptionText;
private TextView eanText;
private TextView ditpadText;
private TableLayout layout16;
private TableLayout layout32;
private Button raapbuttonNext;
private Menu menu;
private Toast toast;
private String next;
private String prev;
private String deze;
private String ean;
private String foto;
private String description;
private String voorraad;
private String totaal;
private String inhoud;
private JSONArray bakken;
private int aantalbakken;
private String einde = "";
private String loadeinde = "0";
private String picked;
private String locatie;
private String locatiepadclean;
private String locatiemeterclean;
private String locatieplankclean;
private String locatievakjeclean;
private String pijl;
private String totaalditpad;
private String batch;
private String kar;
private String raper;
private String afmaken;
String spinneridSelected;
String spinnerkarSelected;
String spinnerraperSelected;
String radioAfmakenSelected;
Bitmap myBitmap;
ArrayList<Integer> gehadArray = new ArrayList<Integer>();
//JSON array
private JSONArray raaplijstresult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
setContentView(R.layout.activity_load_raaplijst);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
findViewById(R.id.productimage).setVisibility(View.GONE);
findViewById(R.id.wificonnectie).setVisibility(View.GONE);
findViewById(R.id.probeeropnieuw).setVisibility(View.GONE);
findViewById(R.id.raapbuttonNext).setVisibility(View.VISIBLE);
findViewById(R.id.raapbuttonPrev).setVisibility(View.VISIBLE);
raapbuttonNext = (Button) findViewById(R.id.raapbuttonNext);
raapbuttonNext.setFocusable(true);
raapbuttonNext.setFocusableInTouchMode(true);
raapbuttonNext.requestFocus();
locatieText = (TextView) findViewById(R.id.locatieText);
totaalText = (TextView) findViewById(R.id.totaalText);
inhoudText = (TextView) findViewById(R.id.inhoudText);
eanText = (TextView) findViewById(R.id.eanText);
ditpadText = (TextView) findViewById(R.id.ditpadTxt);
descriptionText = (TextView) findViewById(R.id.descriptionText);
layout16 = (TableLayout) findViewById(R.id.layout16);
layout32 = (TableLayout) findViewById(R.id.layout32);
Intent intent = getIntent();
spinneridSelected = intent.getStringExtra("spinneridSelected");
spinnerkarSelected = intent.getStringExtra("spinnerkarSelected");
spinnerraperSelected = intent.getStringExtra("spinnerraperSelected");
radioAfmakenSelected = intent.getStringExtra("radioAfmakenSelected");
deze = intent.getStringExtra("load");
batch = spinneridSelected;
kar = spinnerkarSelected;
raper = spinnerraperSelected;
afmaken = radioAfmakenSelected;
if(afmaken.equals("ja")){
deze = getLaatstgehad();
}
Integer gehad = Integer.parseInt(deze.toString());
gehadArray = intent.getIntegerArrayListExtra("gehadArray");
if(!gehadArray.contains(gehad)) {
try {
gehadArray.add(gehad);
} catch (NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
}else{
locatieText.setTextColor(Color.GREEN);
}
saveGehad();
getRaaplijstRegel();
}
private void saveGehad() {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/Raaplijst");
File file = new File(dir, "/gehad.txt");
if(file.exists()) file.delete();
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
buf.write(deze.toString());
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getLaatstgehad() {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/Raaplijst");
File file = new File(dir, "/gehad.txt");
String ret = deze;
if(file.exists()){
try {
FileInputStream inputStream = new FileInputStream (file);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStreamReader.close();
bufferedReader.close();
inputStream.close();
String gehadFromFile = stringBuilder.toString();
ret = gehadFromFile;
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
ret = deze;
}
return ret;
}
public void loadPrev (View view){
loadRaaplijstPrev();
}
public void loadRaaplijstPrev (){
if (prev.equals("-1")) {
Intent intent = new Intent(this, GratisProducten.class);
Bundle extras = new Bundle();
extras.putString("spinneridSelected", batch);
extras.putString("spinnerkarSelected", kar);
extras.putString("spinnerraperSelected", raper);
extras.putString("radioAfmakenSelected", "nee");
extras.putIntegerArrayList("gehadArray", gehadArray);
intent.putExtras(extras);
startActivity(intent);
finish();
} else {
Intent intent = new Intent(this, LoadRaaplijstActivity.class);
Bundle extras = new Bundle();
extras.putString("load", prev);
extras.putString("spinneridSelected", batch);
extras.putString("spinnerkarSelected", kar);
extras.putString("spinnerraperSelected", raper);
extras.putString("radioAfmakenSelected","nee");
extras.putIntegerArrayList("gehadArray", gehadArray);
intent.putExtras(extras);
startActivity(intent);
finish();
}
}
public void loadBegin (View view){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
public void loadBegin(){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
public void loadNext (View view){
loadRaaplijstNext();
}
public void loadRaaplijstNext (){
if (loadeinde.equals("1")) {
loadEnd();
} else {
Intent intent = new Intent(this, LoadRaaplijstActivity.class);
Bundle extras = new Bundle();
extras.putString("spinneridSelected", batch);
extras.putString("spinnerkarSelected", kar);
extras.putString("spinnerraperSelected", raper);
extras.putString("radioAfmakenSelected","nee");
extras.putString("load", next);
extras.putIntegerArrayList("gehadArray", gehadArray);
intent.putExtras(extras);
startActivity(intent);
finish();
}
}
public void loadEnd(){
Intent intent = new Intent(this, EndActivity.class);
Bundle extras = new Bundle();
extras.putString("einde", einde);
extras.putString("load", deze);
extras.putString("spinneridSelected", batch);
extras.putString("spinnerkarSelected", kar);
extras.putString("spinnerraperSelected", raper);
extras.putString("radioAfmakenSelected", "nee");
extras.putIntegerArrayList("gehadArray", gehadArray);
intent.putExtras(extras);
startActivity(intent);
finish();
}
private String readRaaplijstFromFile() {
String ret = "Raaplijst niet gevonden";
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/Raaplijst");
try {
FileInputStream inputStream = new FileInputStream (new File(dir + "/raaplijstJSON.txt"));
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStreamReader.close();
bufferedReader.close();
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
private void getRaaplijstRegel(){
String raaplijstJson = readRaaplijstFromFile();
if(raaplijstJson.equals("Raaplijst niet gevonden")){
}else{
try {
JSONObject j = new JSONObject(raaplijstJson);
raaplijstresult = j.getJSONArray(Config.JSON_ARRAY_RAAPLIJST);
getRegel(raaplijstresult);
} catch (JSONException e) {StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
writeExceptionToFile(stacktrace);
e.printStackTrace();
}
}
}
private void getRegel(JSONArray j) {
for (int h = 0; h < j.length(); h++) {
try {
JSONObject sorteerObj = j.getJSONObject(h);
JSONArray sorteer = sorteerObj.getJSONArray("sorteer");
int i = Integer.parseInt(deze);
try {
JSONObject json = sorteer.getJSONObject(i);
einde = json.getString("einde");
loadeinde = json.getString("loadeinde");
if(loadeinde.equals("1")){
loadEnd();
}
ean = json.getString("ean");
eanText.setText("EAN: " + ean);
locatie = json.getString("locatie");
locatieText.setText(locatie);
locatiepadclean = json.getString("locatiepad");
if(locatiepadclean.equals("leeg")){
locatiepadclean = "";
}
locatiemeterclean = json.getString("locatiemeter");
if(locatiemeterclean.equals("leeg")){
locatiemeterclean = "";
}
locatieplankclean = json.getString("locatieplank");
if(locatieplankclean.equals("leeg")){
locatieplankclean = "";
}
locatievakjeclean = json.getString("locatievakje");
if(locatievakjeclean.equals("leeg")){
locatievakjeclean = "";
}
picked = json.getString("picked");
if(picked.equals("1")) {
locatieText.setTextColor(Color.GREEN);
}
foto = json.getString("foto");
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/Raaplijst");
File imgFile = new File(dir + "/" + foto);
if(imgFile.exists()){
if (myBitmap != null) {
myBitmap.recycle();
myBitmap = null;
}
myBitmap = decodeFile(imgFile, 231, 231);
ImageView bindImage = (ImageView) findViewById(R.id.productimage);
bindImage.setImageBitmap(myBitmap);
}else{
toast = Toast.makeText(getApplicationContext(), imgFile.toString(), Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 20);
toast.show();
}
findViewById(R.id.loadingPanel).setVisibility(View.GONE);
findViewById(R.id.productimage).setVisibility(View.VISIBLE);
description = json.getString("description");
descriptionText.setText(description);
voorraad = json.getString("voorraad");
aantalbakken = Integer.parseInt(json.getString("aantalbakken"));
if(aantalbakken == 32){
findViewById(R.id.layout16).setVisibility(View.GONE);
findViewById(R.id.layout32).setVisibility(View.VISIBLE);
findViewById(R.id.layout32).setOnTouchListener(new OnSwipeTouchListener(LoadRaaplijstActivity.this) {
public void onSwipeTop() {
}
public void onSwipeRight() {
loadRaaplijstPrev();
}
public void onSwipeLeft() {
loadRaaplijstNext();
}
public void onSwipeBottom() {
}
});
}else{
findViewById(R.id.layout32).setVisibility(View.GONE);
findViewById(R.id.layout16).setVisibility(View.VISIBLE);
findViewById(R.id.layout16).setOnTouchListener(new OnSwipeTouchListener(LoadRaaplijstActivity.this) {
public void onSwipeTop() {
}
public void onSwipeRight() {
loadRaaplijstPrev();
}
public void onSwipeLeft() {
loadRaaplijstNext();
}
public void onSwipeBottom() {
}
});
}
int b = 0;
int[] textViewIds;
int[] bakdrawables;
if(aantalbakken == 32) {
textViewIds = new int[]{R.id.b32, R.id.b33, R.id.b34, R.id.b35, R.id.b36, R.id.b37, R.id.b38, R.id.b39,
R.id.b40, R.id.b41, R.id.b42, R.id.b43, R.id.b44, R.id.b45, R.id.b46, R.id.b47,
R.id.b48, R.id.b49, R.id.b50, R.id.b51, R.id.b52, R.id.b53, R.id.b54, R.id.b55,
R.id.b56, R.id.b57, R.id.b58, R.id.b59, R.id.b60, R.id.b61, R.id.b62, R.id.b63
};
bakdrawables = new int[]{R.drawable.vbbb1, R.drawable.vbbb2, R.drawable.vbbb3, R.drawable.vbbb4, R.drawable.vbbb5, R.drawable.vbbb6, R.drawable.vbbb7, R.drawable.vbbb8,
R.drawable.vbbb9, R.drawable.vbbb10, R.drawable.vbbb11, R.drawable.vbbb12, R.drawable.vbbb13, R.drawable.vbbb14, R.drawable.vbbb15, R.drawable.vbbb16,
R.drawable.vbbb17, R.drawable.vbbb18, R.drawable.vbbb19, R.drawable.vbbb20, R.drawable.vbbb21, R.drawable.vbbb22, R.drawable.vbbb23, R.drawable.vbbb24,
R.drawable.vbbb25, R.drawable.vbbb26, R.drawable.vbbb27, R.drawable.vbbb28, R.drawable.vbbb29, R.drawable.vbbb30, R.drawable.vbbb31, R.drawable.vbbb32
};
}else{
textViewIds = new int[]{R.id.b16, R.id.b17, R.id.b18, R.id.b19,
R.id.b20, R.id.b21, R.id.b22, R.id.b23,
R.id.b24, R.id.b25, R.id.b26, R.id.b27,
R.id.b28, R.id.b29, R.id.b30, R.id.b31
};
bakdrawables = new int[]{R.drawable.vbb1, R.drawable.vbb2, R.drawable.vbb3, R.drawable.vbb4, R.drawable.vbb5, R.drawable.vbb6, R.drawable.vbb7, R.drawable.vbb8,
R.drawable.vbb9, R.drawable.vbb10, R.drawable.vbb11, R.drawable.vbb12, R.drawable.vbb13, R.drawable.vbb14, R.drawable.vbb15, R.drawable.vbb16
};
}
for (int z = 0; z < aantalbakken; z++) {
String prefixbakdrawable = "vbb";
if(aantalbakken == 32){
prefixbakdrawable = "vbbb";
}
Integer inhoudBak = Integer.parseInt(json.getString("b" + z));
if (inhoudBak > 0) {
((TextView) findViewById(textViewIds[z])).setText(inhoudBak.toString());
((TextView) findViewById(textViewIds[z])).setTextColor(Color.WHITE);
findViewById(textViewIds[z]).setBackgroundResource(bakdrawables[z]);
} else {
((TextView) findViewById(textViewIds[z])).setText(" ");
}
}
totaal = json.getString("totaal");
totaalText.setText(totaal);
inhoud = json.getString("inhoud");
inhoudText.setText(inhoud);
prev = json.getString("prev");
next = json.getString("next");
pijl = json.getString("pijl");
if(pijl.equals("left")){
locatieText.setBackgroundResource(R.drawable.left);
}
totaalditpad = json.getString("totaalditpad");
ditpadText.setText(totaalditpad);
if (sorteerObj.has("bakken")) {
bakken = sorteerObj.getJSONArray("bakken");
}
} catch (JSONException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
e.printStackTrace();
}
} catch (JSONException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
writeExceptionToFile(stacktrace);
e.printStackTrace();
}
}
}
public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
final int REQUIRED_WIDTH=WIDTH;
final int REQUIRED_HIGHT=HIGHT;
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
scale*=2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
public void probeerOpnieuw (View v){
loadAgain("ja");
}
public void loadAgain(String doorgaan) {
Intent intent = new Intent(this, LoadRaaplijstActivity.class);
Bundle extras = new Bundle();
extras.putString("load", deze);
extras.putString("spinneridSelected", batch);
extras.putString("spinnerkarSelected", kar);
extras.putString("spinnerraperSelected", raper);
extras.putString("radioAfmakenSelected", doorgaan);
extras.putIntegerArrayList("gehadArray", gehadArray);
intent.putExtras(extras);
startActivity(intent);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_load_raaplijst, menu);
this.menu = menu;
String headerTxtTxt = "Batch: " + batch + "- Kar: " + kar + "- Raper: " + raper;
Runtime runtime = Runtime.getRuntime();
long maxMemory=runtime.maxMemory() / (1024 * 1024);
long usedMemory=(runtime.totalMemory() / (1024 * 1024)) - (runtime.freeMemory() / (1024 * 1024));
if(!Config.DEBUG.equals("")) headerTxtTxt = headerTxtTxt + " MaxMem:" + maxMemory + "Mb CurMem:" + usedMemory;
setTitle(headerTxtTxt);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.stopraaplijst:
Intent intent = new Intent(this, MainActivity.class);
Bundle extras = new Bundle();
intent.putExtras(extras);
startActivity(intent);
finish();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
loadAgain(radioAfmakenSelected);
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
loadRaaplijstPrev();
return true;
case KeyEvent.KEYCODE_ENTER:
loadRaaplijstNext();
return true;
default:
return true;
}
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_BACK:
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_ENTER:
return true;
default:
return true;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void writeExceptionToFile(String exception){
File root = android.os.Environment.getExternalStorageDirectory();
String currentDateTimeString = DateFormat.getDateTimeInstance().format(
new Date());
File dir = new File(root.getAbsolutePath() + "/Lograaplijst");
if (!dir.exists()) {
dir.mkdirs();
}
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmss");
String formattedDate = df.format(c.getTime());
File file = new File(dir, "log_h_" + formattedDate + "_" + batch + "_" + kar + ".txt");
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
buf.append(currentDateTimeString + ":" + exception.toString());
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Take Picture From Camera And Show it to the ImageView Android

before i'm so sorry if my post maybe duplicated, but i have another case in this problem, i wanna show an image that i capture from camera in ImageView and after that i save it or upload it into my json file, but after i take the picture, it's stopped in Log.i ("Error", "Maybe Here");
no error in my code but the image cant saved into thumbnail ImageView
Here is my code, i'm using Asyntask
public class StoreTodoDisplayActivity extends AppCompatActivity {
public Context ctx;
Uri imgUri;
ActionBar actionBar;
public static CategoryData category_data_ar[];
public static CategoryData category_data_ar2[];
String targetUrl;
String path = Environment.getExternalStorageDirectory()
+ "/DCIM/Camera/img11.jpg";
public static final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings;
RestData restData;
ImageData imgData;
public Uri mCapturedImageURI;
public String image_path = "";
Toolbar toolbar;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.camera_display);
targetUrl = Config.getEndPointUrl();
ctx = this.getApplicationContext();
System.gc();
set_Spinner();
set_Spinner2();
// Toolbar show
toolbar = (Toolbar) findViewById(R.id.actionbarCameraDisplay);
setSupportActionBar(toolbar);
final android.support.v7.app.ActionBar abar = getSupportActionBar();
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
// Back button pressed
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
settings = getSharedPreferences(PREFS_NAME, 0);
}
#Override
public void onResume() {
if (!UserInfo.loginstatus) {
finish();
}
super.onResume();
}
public void get_pic(View view) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intent, 12345);
}
public void save_img(View view) {
EditText te = (EditText) findViewById(R.id.camera_display_txt);
String msg = te.getText().toString();
Spinner sp = (Spinner) findViewById(R.id.spinner1);
int catid = (int) sp.getSelectedItemId();
String cat = category_data_ar[catid].catid;
Spinner sp2 = (Spinner) findViewById(R.id.spinner2);
int catid2 = (int) sp2.getSelectedItemId();
String cat2 = category_data_ar2[catid2].catid;
ImageUploader uploader = new ImageUploader("display", msg, cat, cat2);
uploader.execute(Config.getEndPointUrl() + "/uploadimage.json");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 12345) {
if (resultCode == RESULT_OK) {
getimage getm = new getimage();
getm.execute();
}
}
}
public void set_Spinner2() {
Spinner sp = (Spinner) findViewById(R.id.spinner2);
sp.setVisibility(View.VISIBLE);
CatProductHelper helper = new CatProductHelper(ctx);
category_data_ar2 = helper.getCategories();
String[] isidesc = new String[category_data_ar2.length];
for (int k = 0; k < category_data_ar2.length; k++) {
isidesc[k] = category_data_ar2[k].catdesc;
Log.i("AndroidRuntime", "Desc -- " + category_data_ar2[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(
StoreTodoDisplayActivity.this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
}
public void set_Spinner() {
// set list activity
Spinner sp = (Spinner) findViewById(R.id.spinner1);
category_data_ar = StoreInfo.storeDisplayCat;
try {
String[] isidesc = new String[category_data_ar.length];
Log.i("toTry", "Normal");
for (int k = 0; k < category_data_ar.length; k++) {
isidesc[k] = category_data_ar[k].catdesc;
Log.i("AndroidRuntime", "Desc -- "
+ category_data_ar[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(
StoreTodoDisplayActivity.this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
} catch (Exception e) {
Log.i("toCatch", "NULL EXCEPTION");
DisplayCatHelper helperDisplayCat = new DisplayCatHelper(ctx);
CategoryData[] displayCat = helperDisplayCat.getCategories();
String[] isidesc = new String[displayCat.length];
for (int k = 0; k < displayCat.length; k++) {
isidesc[k] = displayCat[k].catdesc;
Log.i("AndroidRuntime", "Desc -- " + displayCat[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
}
}
private class ImageUploader extends AsyncTask<String, String, String> {
ProgressDialog dialog;
private String url;
private String cameraType;
private String cameraMsg;
private String cameraCat;
private String catproduct;
public ImageUploader(String type, String msg, String cat, String cat2) {
cameraType = type;
cameraMsg = msg;
cameraCat = cat;
catproduct = cat2;
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(StoreTodoDisplayActivity.this, "",
"Uploading...", false);
// none
}
#Override
protected String doInBackground(String... params) {
url = params[0];
Log.i("ncdebug", "upload image to: " + url);
try {
if (image_path.equals("")) {
Log.i("ncdebug", "bmp kosong!!!!");
} else {
Log.i("ncdebug", "Ok bmp gak kosong, mari kirim");
restData = new RestData();
imgData = new ImageData();
restData.setTitle("Display : " + StoreInfo.storename);
restData.setRequestMethod(RequestMethod.POST);
restData.setUrl(url);
imgData.setImageData(url, image_path, cameraMsg, cameraCat
+ "-" + catproduct, UserInfo.username,
StoreInfo.storeid, cameraType, UserInfo.checkinid);
saveToDb();
return "Success";
}
} catch (Exception e) {
//saveToDb();
}
return "Penyimpanan gagal, ulangi tahap pengambilan gambar";
}
#Override
protected void onPostExecute(String Result) {
dialog.dismiss();
if (Result.equals("Success")) {
Toast.makeText(ctx, "Data tersimpan", Toast.LENGTH_SHORT)
.show();
// checked todo
String vVar = StoreInfo.storeid + "-" + UserInfo.username
+ "-displaycam";
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(vVar, true);
editor.commit();
Intent intent = new Intent(ctx, StoreTodoActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(ctx, Result, Toast.LENGTH_LONG)
.show();
}
}
}
public void saveToDb() {
Log.i("eris", "connection failed so save to db");
RestHelper helper = new RestHelper(ctx);
helper.insertRest(restData);
imgData.setRestId(helper.getRestId());
Log.i("REST ID", helper.getRestId());
ImageHelper imgHelper = new ImageHelper(ctx);
imgHelper.insertRest(imgData);
}
public class getimage extends AsyncTask<String, String, String> {
String orientation = "";
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// Log.i("INI BACKGROUND", "LIHAT");
try {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(mCapturedImageURI, projection,
null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor
.getString(column_index_data);
String parentPath = Environment.getExternalStorageDirectory()
+ "/Nestle Confect";
String filename = System.currentTimeMillis() + ".jpg";
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
Bitmap bmp = BitmapFactory.decodeFile(capturedImageFilePath,
opts);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File file = new File(parentPath);
file.mkdir();
try {
file.createNewFile();
Log.i("absoulute path", file.getAbsolutePath());
FileOutputStream fo = new FileOutputStream(file + "/"
+ filename, true);
// 5
fo.write(bytes.toByteArray());
fo.close();
image_path = parentPath + "/" + filename;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
image_path = capturedImageFilePath;
}
byte[] thumb = null;
try {
ExifInterface exif = new ExifInterface(
capturedImageFilePath);
orientation = exif
.getAttribute(ExifInterface.TAG_ORIENTATION);
thumb = exif.getThumbnail();
} catch (IOException e) {
}
if (thumb != null) {
Log.i("IMAGEVIEW", "THUMBNAIL");
bitmap = BitmapFactory.decodeByteArray(thumb, 0,
thumb.length);
} else {
Log.i("IMAGEVIEW", "REALFILE");
return "not fine";
}
return "fine";
} catch (Exception e) {
return "not fine";
}
}
#Override
public void onPostExecute(String result) {
// PROBLEM HERE
Log.i("ERROR", "HERE MAYBE");
if (result.equals("fine")) {
ImageView gambarHasil = (ImageView) findViewById(R.id.camera_display_img);
gambarHasil.setImageBitmap(bitmap);
if (!orientation.equals("1")) {
Log.i("ORIENTATION", orientation);
float angel = 0f;
if (orientation.equals("6")) {
angel = 90f;
} else if (orientation.equals("8")) {
angel = -90f;
}
Matrix matrix = new Matrix();
gambarHasil.setScaleType(ScaleType.MATRIX); // required
matrix.postRotate((float) angel, gambarHasil.getDrawable()
.getBounds().width() / 2, gambarHasil.getDrawable()
.getBounds().height() / 2);
gambarHasil.setImageMatrix(matrix);
}
} else {
Toast.makeText(
ctx,
"Error, Try To Take Picture Again",
Toast.LENGTH_LONG).show();
}
}
}
}
I think your activity just got restarted you need to put below code in manifest where you declare. and save your uri on saveInstanceState and restore it on onrestoreinstancestate. it will be resolve your issue
android:configChanges="orientation|keyboardHidden|screenSize"
Use this lib,Provides support above API 14
https://github.com/google/cameraview

My application can't store the image taken with OpenCV Library

I am developping an android application for face recognition ,and when i press the button to store the picture , My app stopped !!
Here is my code the the Activity Add Picture :
public class Add_Picture extends FragmentActivity implements CvCameraViewListener2 {
static {
if (!OpenCVLoader.initDebug()) {
// Handle initialization error
Log.e("no","no");
}
else {
Log.e("ok","ok");
}
}
static
{
// If you use opencv 2.4, System.loadLibrary("opencv_java")
System.loadLibrary("opencv_java3");
}
private static final String TAG = "Reconnaissance Faciale";
public static final int VIEW_MODE_LISTFRAMES= 1;
private MenuItem listframes;
public static int viewMode;
private Mat mRgba;
private CameraBridgeViewBase mOpenCvCameraView;
private DBhelper dbhelper;
private Button store;
private Button back;
private EditText text;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
public Add_Picture() {
Log.i(TAG, "Instantiated new " + this.getClass());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(com.example.opencv_java_androidstudio.R.layout.activity_add__picture);
// setContentView(R.layout.activity_add__picture);
//setContentView(R.layout.activity_add__picture);
//mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.camera);
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(com.example.opencv_java_androidstudio.R.id.camera);
mOpenCvCameraView.setCvCameraViewListener(this);
mOpenCvCameraView.setCameraIndex(1);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
//mOpenCvCameraView.setRotation(90);
//store= (Button) findViewById(R.id.store);
store= (Button) findViewById(com.example.opencv_java_androidstudio.R.id.store);
store.setRotation(90);
Mat test = new Mat(200, 200, CvType.CV_8UC1);
Imgproc.equalizeHist(test, test);
//mOpenCvCameraView.getDisplay();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
listframes = menu.add("Faces list");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item == listframes){
viewMode = VIEW_MODE_LISTFRAMES;
// Intent intent = new Intent(AjoutframeActivity.this, ListframeActivity.class);
// startActivity(intent);
}
return true;
}
#Override
public void onPause()
{
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this, mLoaderCallback);
}
public void onDestroy() {
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
public void onCameraViewStarted(int width, int height) {
mRgba = new Mat(height, width, CvType.CV_8UC4);
}
public void onCameraViewStopped() {
mRgba.release();
}
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
mRgba=inputFrame.rgba();
store.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v1){
storeframesiDB(mRgba);
}
});
return mRgba;
}
public void storeframesiDB(Mat mat){
MatOfKeyPoint points = new MatOfKeyPoint();
FeatureDetector surf = FeatureDetector.create(FeatureDetector.ORB);
DescriptorExtractor extractor = DescriptorExtractor.create(DescriptorExtractor.BRIEF);
surf.detect(mat, points);
Mat descriptors = new Mat();
extractor.compute(mat, points, descriptors);
int rows=descriptors.rows();
String str=Frametraitement.matToJson(descriptors);
dbhelper = new DBhelper(this);
//text= (EditText) findViewById(R.id.storage);
text= (EditText) findViewById(com.example.opencv_java_androidstudio.R.id.storage);
String textstore= text.getText().toString();
Frameclass fr = new Frameclass(textstore,str,rows);
text.setText("");
dbhelper.open();
dbhelper.insertframeDetails(fr);
dbhelper.close();
}
}
My Logcat shows me that : Canno't load info library for OpenCV.
And here is my class for the image's traitement :
public class Frametraitement {
private static final String TAG = "RF";
private DBhelper dbhelper;
public static Mat matRetrieve(String filePath, int rows, int cols, int type){
Log.d(TAG, "matRetrieve - path: " + filePath);
if(isExternalStorageReadable()){
File matFile = new File(filePath);
InputStream in = null;
try {
in = new FileInputStream(matFile);
byte[] data = convertInputStreamToByteArray(in);
//Mat result = new Mat(320, 212, CvType.CV_8UC1);
Mat result = new Mat(rows, cols, type);
result.put(0, 0, data);
return result;
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
Log.e(TAG, "External Storage not readable.");
}
return null;
}
public static byte[] matStore( Mat mat){
//Log.d(TAG, "matStore - path: "+filePath);
byte[] data=null;
if(isExternalStorageWritable() && mat.isContinuous()){
int cols = mat.cols();
int rows = mat.rows();
int elemSize = (int) mat.elemSize(); // or mat.channels() ?
data= new byte[cols * rows * elemSize];
mat.get(0, 0, data);
Log.e(TAG, "data"+ data);
Log.e(TAG, "mat"+ mat);
} else {
Log.e(TAG, "External Storage not writable.");
}
return data;
}
public static String matToJson(Mat mat){
Log.i(TAG, "matToJson");
JsonObject obj = new JsonObject();
if(mat.isContinuous()){
int cols = mat.cols();
int rows = mat.rows();
int elemSize = (int) mat.elemSize();
byte[] data = new byte[cols * rows * elemSize];
mat.get(0, 0, data);
obj.addProperty("rows", mat.rows());
obj.addProperty("cols", mat.cols());
obj.addProperty("type", mat.type());
String dataString = new String(Base64.encode(data, Base64.DEFAULT));
Log.d(TAG, "matToJson - boooom: "+dataString);
obj.addProperty("data", dataString);
Gson gson = new Gson();
String json = gson.toJson(obj);
return json;
} else {
Log.e(TAG, "Mat not continuous.");
}
return "{}";
}
public static Mat matFromJson(String json){
Log.d(TAG, "matToJson");
JsonParser parser = new JsonParser();
JsonObject JsonObject = parser.parse(json).getAsJsonObject();
int rows = JsonObject.get("rows").getAsInt();
int cols = JsonObject.get("cols").getAsInt();
int type = JsonObject.get("type").getAsInt();
String dataString = JsonObject.get("data").getAsString();
byte[] data = Base64.decode(dataString.getBytes(), Base64.DEFAULT);
Mat mat = new Mat(rows, cols, type);
mat.put(0, 0, data);
Log.e(TAG,"matfromjson"+mat);
return mat;
}
private static byte[] convertInputStreamToByteArray(InputStream inputStream) {
byte[] bytes= null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte buff[] = new byte[1024];
int count;
while ((count = inputStream.read(buff)) != -1) {
bos.write(buff, 0, count);
}
bos.flush();
bos.close();
inputStream.close();
bytes = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
/* Checks if external storage is available for read and write */
public static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public static boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
public static byte[] getBytes(String ch) {
Mat mat=matFromJson(ch);
//Log.e(TAG,"chaine"+ch);
return matStore(mat);
}
public static Mat getmatfrombyte(byte[] data, int rows, int cols) {
Mat result = new Mat(rows, cols, CvType.CV_8UC1);
result.put(0, 0, data);
return result;
}
public static Mat calculdescriptors(Mat mat){
MatOfKeyPoint points = new MatOfKeyPoint();
FeatureDetector surf = FeatureDetector.create(FeatureDetector.ORB);
DescriptorExtractor extractor = DescriptorExtractor.create(DescriptorExtractor.BRIEF);
surf.detect(mat, points);
int nbrepts= points.toList().size();
Mat descriptors = new Mat();
extractor.compute(mat, points, descriptors);
return descriptors;
}
public static MatOfDMatch matching(Mat matcour,Mat mattrain){
DescriptorMatcher matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING);
MatOfDMatch matches = new MatOfDMatch();
matcher.match(matcour, mattrain, matches);
matches.toList();
Log.e(TAG,"matches "+matches.toList());
return filterMatchesByDistance(matches);
}
public static MatOfDMatch filterMatchesByDistance(MatOfDMatch matches){
List<org.opencv.core.DMatch> matches_original = matches.toList();
List<org.opencv.core.DMatch> matches_filtered = new ArrayList<>();
int DIST_LIMIT = 30;
// Check all the matches distance and if it passes add to list of filtered matches
Log.d("DISTFILTER", "ORG SIZE:" + matches_original.size() + "");
for (int i = 0; i < matches_original.size(); i++) {
org.opencv.core.DMatch d = matches_original.get(i);
if (Math.abs(d.distance) <= DIST_LIMIT) {
matches_filtered.add(d);
}
}
Log.d("DISTFILTER", "FIL SIZE:" + matches_filtered.size() + "");
MatOfDMatch mat = new MatOfDMatch();
mat.fromList(matches_filtered);
return mat;
}
}

How can I fix (The left-hand side of an assignment must be a variable) and (Type mismatch: cannot convert from Object to String) in this code?

I have this code for compressing pictures , I have two error , I have separated these errors with line in code like this (...........) first is : The left-hand side of an assignment must be a variable .......... and the second is Type mismatch: cannot convert from Object to String ................. how can I fix them ???
package com.example.resizingimages;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.media.MediaScannerConnection.OnScanCompletedListener;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.provider.MediaStore.Images.Media;
import android.provider.MediaStore.Video.Media;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsoluteLayout;
import android.widget.AbsoluteLayout.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.InputStream;
import java.io.PrintStream;
public class GetImageActivity extends Activity
implements MediaScannerConnection.MediaScannerConnectionClient, DialogInterface
{
private static final int CAMERA_REQUEST = 1800;
private static final int GALLERY_KITKAT_INTENT_CALLED = 1500;
private static final int SELECT_PICTURE = 1;
static String filePath;
private TextView Name;
private TextView Size;
MediaScannerConnection conn;
File file;
private String filename;
private int height;
Uri imageUri;
private ImageView img;
private Uri outputFileUri;
Uri outputFileUri1;
String path1;
private String path2;
private Bitmap picture;
private File root;
File sdImageMainDirectory;
private Uri selectedImageUri;
private int width;
private void cameraaa(String paramString, Uri paramUri)
{
while (true)
{
try
{
InputStream localInputStream = getContentResolver().openInputStream(paramUri);
BitmapFactory.Options localOptions = new BitmapFactory.Options();
localOptions.inSampleSize = 2;
localOptions.inPurgeable = true;
byte[] arrayOfByte = new byte[1024];
localOptions.inPreferredConfig = Bitmap.Config.RGB_565;
localOptions.inTempStorage = arrayOfByte;
this.picture = BitmapFactory.decodeStream(localInputStream, null, localOptions);
switch (new ExifInterface(paramString).getAttributeInt("Orientation", 1))
{
case 4:
case 5:
default:
this.img.setImageBitmap(this.picture);
String str = sizee(paramUri);
Toast.makeText(getApplicationContext(), "Size of Image " + str, 0).show();
System.out.println("Image Path : " + paramString);
return;
case 6:
rotateImage(this.picture, 90);
continue;
case 3:
}
}
catch (Exception localException)
{
Toast.makeText(getApplicationContext(), "Error " + localException.getMessage(), 0).show();
return;
}
rotateImage(this.picture, 180);
}
}
public static String getDataColumn(Context paramContext, Uri paramUri, String paramString, String[] paramArrayOfString)
{
Cursor localCursor = null;
String[] arrayOfString = { "_data" };
try
{
localCursor = paramContext.getContentResolver().query(paramUri, arrayOfString, paramString, paramArrayOfString, null);
if ((localCursor != null) && (localCursor.moveToFirst()))
{
String str = localCursor.getString(localCursor.getColumnIndexOrThrow("_data"));
return str;
}
}
finally
{
if (localCursor != null)
localCursor.close();
}
if (localCursor != null)
localCursor.close();
return null;
}
public static String getPathl(Context paramContext, Uri paramUri)
{
int i;
if (Build.VERSION.SDK_INT >= 19)
i = 1;
while ((i != 0) && (DocumentsContract.isDocumentUri(paramContext, paramUri)))
if (isExternalStorageDocument(paramUri))
{
String[] arrayOfString3 = DocumentsContract.getDocumentId(paramUri).split(":");
if (!"primary".equalsIgnoreCase(arrayOfString3[0]))
break label271;
return Environment.getExternalStorageDirectory() + "/" + arrayOfString3[1];
i = 0;
}
else
{
if (isDownloadsDocument(paramUri))
{
String str2 = DocumentsContract.getDocumentId(paramUri);
return getDataColumn(paramContext, ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(str2).longValue()), null, null);
}
if (!isMediaDocument(paramUri))
break label271;
String[] arrayOfString1 = DocumentsContract.getDocumentId(paramUri).split(":");
String str1 = arrayOfString1[0];
Uri localUri;
if ("image".equals(str1))
localUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
while (true)
{
String[] arrayOfString2 = new String[1];
arrayOfString2[0] = arrayOfString1[1];
return getDataColumn(paramContext, localUri, "_id=?", arrayOfString2);
if ("video".equals(str1))
{
localUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
}
else
{
boolean bool = "audio".equals(str1);
localUri = null;
if (bool)
localUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
}
}
if ("content".equalsIgnoreCase(paramUri.getScheme()))
return getDataColumn(paramContext, paramUri, null, null);
if ("file".equalsIgnoreCase(paramUri.getScheme()))
return paramUri.getPath();
label271: return filePath;
}
public static boolean isDownloadsDocument(Uri paramUri)
{
return "com.android.providers.downloads.documents".equals(paramUri.getAuthority());
}
public static boolean isExternalStorageDocument(Uri paramUri)
{
return "com.android.externalstorage.documents".equals(paramUri.getAuthority());
}
public static boolean isMediaDocument(Uri paramUri)
{
return "com.android.providers.media.documents".equals(paramUri.getAuthority());
}
private void openAddPhoto()
{
String[] arrayOfString = { "Camera", "Gallery" };
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setTitle(getResources().getString(2130968578));
localBuilder.setItems(arrayOfString, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
if (paramAnonymousInt == 0)
{
ContentValues localContentValues = new ContentValues();
localContentValues.put("title", "new-photo-name.jpg");
localContentValues.put("description", "Image capture by camera");
GetImageActivity.this.imageUri = GetImageActivity.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, localContentValues);
Intent localIntent1 = new Intent("android.media.action.IMAGE_CAPTURE");
localIntent1.putExtra("output", GetImageActivity.this.imageUri);
GetImageActivity.this.startActivityForResult(localIntent1, 1800);
}
if (paramAnonymousInt == 1)
{
if (Build.VERSION.SDK_INT < 19)
{
Intent localIntent2 = new Intent();
localIntent2.setType("image/*");
localIntent2.setAction("android.intent.action.GET_CONTENT");
GetImageActivity.this.startActivityForResult(Intent.createChooser(localIntent2, "Select Picture"), 1);
}
}
else
return;
Intent localIntent3 = new Intent("android.intent.action.PICK", MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GetImageActivity.this.startActivityForResult(Intent.createChooser(localIntent3, "Select Picture"), 1500);
}
});
localBuilder.setNeutralButton("cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
paramAnonymousDialogInterface.dismiss();
}
});
localBuilder.show();
}
private void startScan()
{
if (this.conn != null)
this.conn.disconnect();
this.conn = new MediaScannerConnection(this, this);
this.conn.connect();
}
public void cancel()
{
}
public void dismiss()
{
}
public String getPath(Uri paramUri)
{
Cursor localCursor = managedQuery(paramUri, new String[] { "_data" }, null, null, null);
String str = null;
if (localCursor != null)
{
int i = localCursor.getColumnIndexOrThrow("_data");
localCursor.moveToFirst();
str = localCursor.getString(i);
}
return str;
}
public String name(String paramString)
{
int i = 0;
for (int j = 0; ; j++)
{
if (j >= paramString.length())
{
this.filename = filePath.substring(i + 1, paramString.length());
return this.filename;
}
if (paramString.charAt(j) == '/')
i = j;
}
}
public void onActivityResult(int paramInt1, int paramInt2, Intent paramIntent)
{
if (paramInt2 == -1)
{
if (paramInt1 == 1)
while (true)
{
try
{
this.selectedImageUri = paramIntent.getData();
Toast.makeText(getApplicationContext(), "DATA " + filePath, 0).show();
filePath = getPath(this.selectedImageUri);
InputStream localInputStream2 = getContentResolver().openInputStream(this.selectedImageUri);
BitmapFactory.Options localOptions2 = new BitmapFactory.Options();
localOptions2.inSampleSize = 2;
localOptions2.inPurgeable = true;
byte[] arrayOfByte2 = new byte[1024];
localOptions2.inPreferredConfig = Bitmap.Config.RGB_565;
localOptions2.inTempStorage = arrayOfByte2;
this.picture = BitmapFactory.decodeStream(localInputStream2, null, localOptions2);
switch (new ExifInterface(filePath).getAttributeInt("Orientation", 1))
{
case 4:
case 5:
default:
this.img.setImageBitmap(this.picture);
String str4 = sizee(this.selectedImageUri);
Toast.makeText(getApplicationContext(), "Size of Image " + str4, 0).show();
return;
case 6:
rotateImage(this.picture, 90);
continue;
case 3:
}
}
catch (Exception localException3)
{
Toast.makeText(getApplicationContext(), "Error " + localException3.getMessage(), 0).show();
return;
}
rotateImage(this.picture, 180);
}
if (paramInt1 == 1500)
while (true)
{
try
{
this.selectedImageUri = paramIntent.getData();
getPathl(getApplicationContext(), this.selectedImageUri);
getContentResolver();
filePath = getPathl(getApplicationContext(), this.selectedImageUri);
InputStream localInputStream1 = getContentResolver().openInputStream(this.selectedImageUri);
BitmapFactory.Options localOptions1 = new BitmapFactory.Options();
localOptions1.inSampleSize = 2;
localOptions1.inPurgeable = true;
byte[] arrayOfByte1 = new byte[1024];
localOptions1.inPreferredConfig = Bitmap.Config.RGB_565;
localOptions1.inTempStorage = arrayOfByte1;
this.picture = BitmapFactory.decodeStream(localInputStream1, null, localOptions1);
switch (new ExifInterface(filePath).getAttributeInt("Orientation", 1))
{
case 4:
case 5:
default:
this.img.setImageBitmap(this.picture);
String str3 = sizee(this.selectedImageUri);
Toast.makeText(getApplicationContext(), "Size of Image " + str3, 0).show();
return;
case 6:
case 3:
}
}
catch (Exception localException2)
{
Toast.makeText(getApplicationContext(), "Error " + localException2.getMessage(), 0).show();
return;
}
rotateImage(this.picture, 90);
continue;
rotateImage(this.picture, 180);
}
if (paramInt1 == 1800)
{
filePath = null;
this.selectedImageUri = this.imageUri;
if (this.selectedImageUri != null)
while (true)
{
String str1;
try
{
str1 = this.selectedImageUri.getPath();
String str2 = getPath(this.selectedImageUri);
if (str2 != null)
{
filePath = str2;
if (filePath == null)
break;
Toast.makeText(getApplicationContext(), " path" + filePath, 1).show();
new Intent(getApplicationContext(), GetImageActivity.class);
cameraaa(filePath, this.selectedImageUri);
return;
}
}
catch (Exception localException1)
{
Toast.makeText(getApplicationContext(), "Internal error", 1).show();
Log.e(localException1.getClass().getName(), localException1.getMessage(), localException1);
return;
}
if (str1 != null)
{
filePath = str1;
}
else
{
Toast.makeText(getApplicationContext(), "Unknown path", 1).show();
Log.e("Bitmap", "Unknown path");
}
}
}
}
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
requestWindowFeature(1);
getWindow().setFlags(1024, 1024);
setContentView(2130903040);
Display localDisplay = getWindowManager().getDefaultDisplay();
this.width = localDisplay.getWidth();
this.height = localDisplay.getHeight();
final Button localButton = (Button)findViewById(2131296257);
final Spinner localSpinner = (Spinner)findViewById(2131296260);
final TextView localTextView = (TextView)findViewById(2131296259);
localButton.setVisibility(4);
localSpinner.setVisibility(4);
localTextView.setVisibility(4);
if (this.height <= 480)
{
localSpinner.setLayoutParams(new AbsoluteLayout.LayoutParams(-1, -2, 0, 20 + (this.height - this.height / 3)));
localTextView.setLayoutParams(new AbsoluteLayout.LayoutParams(this.width, 60, 0, -20 + (this.height - this.height / 3)));
localTextView.setText("Image Quality");
localTextView.setText("Image Quality");
this.img = ((ImageView)findViewById(2131296258));
this.img.setBackgroundResource(2130837504);
//first error is here
.......................................................................................
***(-160 + this.height);***
(-160 + this.height);
((int)(0.8D * this.width));
AbsoluteLayout.LayoutParams localLayoutParams1 = new AbsoluteLayout.LayoutParams((int)(0.8D * this.width), (int)(0.5D * this.height), (int)(this.width - 0.9D * this.width), (int)(this.height - 0.9D * this.height));
this.img.setLayoutParams(localLayoutParams1);
ImageView localImageView = this.img;
View.OnClickListener local1 = new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
GetImageActivity.this.img.setImageDrawable(null);
GetImageActivity.this.img.setBackgroundResource(2130837504);
localButton.setVisibility(0);
localSpinner.setVisibility(0);
localTextView.setVisibility(0);
GetImageActivity.this.openAddPhoto();
}
};
localImageView.setOnClickListener(local1);
if (this.height > 480)
break label505;
localButton.setBackgroundResource(2130837507);
(-160 + this.height);
}
for (AbsoluteLayout.LayoutParams localLayoutParams2 = new AbsoluteLayout.LayoutParams(50, 50, -25 + this.width / 2, -51 + this.height); ; localLayoutParams2 = new AbsoluteLayout.LayoutParams(170, 170, -85 + this.width / 2, -170 + this.height))
{
localButton.setLayoutParams(localLayoutParams2);
View.OnClickListener local2 = new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
}
};
localButton.setOnClickListener(local2);
return;
localSpinner.setLayoutParams(new AbsoluteLayout.LayoutParams(-1, -2, 0, 30 + (this.height - this.height / 3)));
localTextView.setLayoutParams(new AbsoluteLayout.LayoutParams(this.width, 60, 0, -10 + (this.height - this.height / 3)));
break;
label505: localButton.setBackgroundResource(2130837506);
(-160 + this.height);
}
}
public boolean onCreateOptionsMenu(Menu paramMenu)
{
getMenuInflater().inflate(2131230720, paramMenu);
return true;
}
public void onMediaScannerConnected()
{
try
{
this.conn.scanFile(filePath, "image/*");
return;
}
catch (IllegalStateException localIllegalStateException)
{
}
}
public boolean onOptionsItemSelected(MenuItem paramMenuItem)
{
if (paramMenuItem.getItemId() == 2131296262)
shareagain();
while (true)
{
return true;
if (paramMenuItem.getItemId() == 2131296263)
try
{
startActivity(new Intent(this, readddme.class));
}
catch (Exception localException)
{
Toast.makeText(getApplicationContext(), "Error " + localException.getMessage(), 0).show();
}
else if (paramMenuItem.getItemId() == 2131296264)
System.exit(0);
}
}
public void onScanCompleted(String paramString, Uri paramUri)
{
this.conn.disconnect();
}
public void rotateImage(Bitmap paramBitmap, int paramInt)
{
Matrix localMatrix = new Matrix();
localMatrix.setRotate(paramInt);
this.picture = Bitmap.createBitmap(paramBitmap, 0, 0, paramBitmap.getWidth(), paramBitmap.getHeight(), localMatrix, true);
}
public void share()
{
Intent localIntent = new Intent("android.intent.action.SEND");
localIntent.setType("text/plain");
localIntent.putExtra("android.intent.extra.SUBJECT", "#RABIDO");
localIntent.putExtra("android.intent.extra.TEXT", "#RABIDO");
localIntent.setType("image/*");
localIntent.putExtra("android.intent.extra.STREAM", this.selectedImageUri);
startActivity(Intent.createChooser(localIntent, "Share Image"));
}
public void shareagain()
{
Intent localIntent = new Intent("android.intent.action.SEND");
localIntent.setType("text/plain");
localIntent.putExtra("android.intent.extra.TEXT", "Check out 'RABIDO' - https://play.google.com/store/apps/details?id=decrease.image.uploader");
startActivity(Intent.createChooser(localIntent, "Share via"));
}
public String sizee(Uri paramUri)
{
Object localObject;
try
{
InputStream localInputStream = getContentResolver().openInputStream(paramUri);
byte[] arrayOfByte = new byte[1024];
int i = 0;
float f;
while (true)
{
if (localInputStream.read(arrayOfByte) == -1)
{
f = i / 1000;
if (f >= 1000.0F)
break;
localObject = " " + i / 1000 + " KB";
break label164;
}
i += arrayOfByte.length;
}
String str = " " + f / 1000.0F + " MB";
localObject = str;
}
catch (Exception localException)
{
Toast.makeText(getApplicationContext(), "Error 5 " + localException.getMessage(), 0).show();
return "";
}
//second is here
..................................................................
label164: return localObject;
}
}
For the First error can you try something like this:
(this.height = this.height - 160);
The error indicates you are trying to make an assignment operation but you have not put a variable in the left hand side of the equation.
there may also be a short hand way to do this such as:
(this.height =- 160);
for the second error is seems that you have declared "localObject" as an Object.
can you just declare it as a String. seems that you are assigning a string to it and then wanting to return a string. See if that works.

Categories

Resources