Related
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();
}
}
}
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
I am trying to store video in sd card while sending live streaming on wowza sever. I am sending successfully live video to wowza server but I am not able to store corresponding video to sd card.I am using this library to send video to wowza sever.
surfaceView=(SurfaceView) findViewById(R.id.surface);
myChronometer = (Chronometer) findViewById(R.id.chronometer1);
chat32=(Button) findViewById(R.id.chat32);
chatedit=(EditText) findViewById(R.id.chatedit);
send=(Button) findViewById(R.id.send);
chatlist=(ListView) findViewById(R.id.camerachatlist);
chat32.setOnClickListener(this);
mButtonVideo = (Button) findViewById(R.id.video);
mButtonSave = (Button) findViewById(R.id.save);
mButtonStart = (Button) findViewById(R.id.start);
mButtonFlash = (Button) findViewById(R.id.flash);
mButtonCamera =(Button) findViewById(R.id.camera);
mButtonSettings = (Button) findViewById(R.id.settings);
mSurfaceView = (SurfaceView) findViewById(R.id.surface);
mEditTextURI = (EditText) findViewById(R.id.uri);
mEditTextUsername = (EditText) findViewById(R.id.username);
mEditTextPassword = (EditText) findViewById(R.id.password);
mTextBitrate = (TextView) findViewById(R.id.bitrate);
mLayoutVideoSettings = (FrameLayout) findViewById(R.id.video_layout);
mLayoutServerSettings = (FrameLayout) findViewById(R.id.server_layout);
mRadioGroup = (RadioGroup) findViewById(R.id.radio);
mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
mRadioGroup.setOnCheckedChangeListener(this);
mRadioGroup.setOnClickListener(this);
mButtonStart.setOnClickListener(this);
mButtonSave.setOnClickListener(this);
mButtonFlash.setOnClickListener(this);
mButtonCamera.setOnClickListener(this);
mButtonVideo.setOnClickListener(this);
mButtonSettings.setOnClickListener(this);
mButtonFlash.setTag("off");
SharedPreferences mPrefs = PreferenceManager
.getDefaultSharedPreferences(VideoStream.this);
if (mPrefs.getString("uri", null) != null)
mLayoutServerSettings.setVisibility(View.GONE);
mEditTextURI.setText(mPrefs.getString("uri",
getString(R.string.default_stream)));
System.out.println("text get from edittext" + mEditTextURI.getText());
mEditTextPassword.setText(mPrefs.getString("password", "********"));
System.out.println("text get from edittext"
+ mEditTextPassword.getText());
mEditTextUsername.setText(mPrefs.getString("username", "*******"));
System.out.println("text get from edittext"
+ mEditTextUsername.getText());
// Configures the SessionBuilder
SessionBuilder sessionbuilder = SessionBuilder.getInstance();
mSession = SessionBuilder.getInstance().setCallback(VideoStream.this)
.setContext(getApplicationContext())
.setAudioEncoder(SessionBuilder.AUDIO_AAC)
.setAudioQuality(new AudioQuality(8000, 16000))
.setVideoEncoder(SessionBuilder.VIDEO_H264)
.setSurfaceView(mSurfaceView).setPreviewOrientation(0)
.build();
// Configures the RTSP client
mClient = new RtspClient();
mClient.setSession(mSession);
mClient.setCallback(VideoStream.this);
System.out.println("helllllllloooo");
// Use this to force streaming with the MediaRecorder API
mSession.getVideoTrack().setStreamingMethod(
MediaStream.MODE_MEDIARECORDER_API);
// Use this to stream over TCP, EXPERIMENTAL!
mClient.setTransportMode(RtspClient.TRANSPORT_TCP);
// Use this if you want the aspect ratio of the surface view to
// respect the aspect ratio of the camera preview
mSurfaceView.setAspectRatioMode(SurfaceView.ASPECT_RATIO_PREVIEW);
mSurfaceView.getHolder().addCallback(this);
selectQuality();
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
System.out.println("############## onCheckedChanged");
mLayoutVideoSettings.setVisibility(View.GONE);
mLayoutServerSettings.setVisibility(View.VISIBLE);
selectQuality();
}
// =================================================================
// on click
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
mLayoutServerSettings.setVisibility(View.GONE);
toggleStream();
break;
case R.id.flash:
if (mButtonFlash.getTag().equals("on")) {
mButtonFlash.setTag("off");
mButtonFlash
.setBackgroundResource(R.drawable.ic_flash_on_holo_light);
} else {
mButtonFlash
.setBackgroundResource(R.drawable.ic_flash_off_holo_light);
mButtonFlash.setTag("on");
}
mSession.toggleFlash();
break;
case R.id.camera:
mSession.switchCamera();
break;
case R.id.settings:
if (mLayoutVideoSettings.getVisibility() == View.GONE
&& mLayoutServerSettings.getVisibility() == View.GONE) {
mLayoutServerSettings.setVisibility(View.VISIBLE);
} else {
mLayoutServerSettings.setVisibility(View.GONE);
mLayoutVideoSettings.setVisibility(View.GONE);
}
break;
case R.id.video:
mRadioGroup.clearCheck();
mLayoutServerSettings.setVisibility(View.GONE);
mLayoutVideoSettings.setVisibility(View.VISIBLE);
break;
case R.id.save:
mLayoutServerSettings.setVisibility(View.GONE);
break;
case R.id.chat32:
chatedit.setVisibility(View.VISIBLE);
send.setVisibility(View.VISIBLE);
break;
case R.id.send:
chatlist.setVisibility(View.VISIBLE);
}
}
// ===================================================
#Override
public void onDestroy() {
super.onDestroy();
mClient.release();
mSession.release();
mSurfaceView.getHolder().removeCallback(this);
}
private void selectQuality() {
System.out.println("############## selectQuality");
int id = mRadioGroup.getCheckedRadioButtonId();
RadioButton button = (RadioButton) findViewById(id);
if (button == null)
return;
String text = button.getText().toString();
System.out.println("text " + text);
Pattern pattern = Pattern.compile("(\\d+)x(\\d+)\\D+(\\d+)\\D+(\\d+)");
Matcher matcher = pattern.matcher(text);
matcher.find();
int width = Integer.parseInt(matcher.group(1));
int height = Integer.parseInt(matcher.group(2));
int framerate = Integer.parseInt(matcher.group(3));
int bitrate = Integer.parseInt(matcher.group(4)) * 1000;
mSession.setVideoQuality(new VideoQuality(width, height, framerate,
bitrate));
Toast.makeText(this, ((RadioButton) findViewById(id)).getText(),
Toast.LENGTH_SHORT).show();
Log.d(TAG, "Selected resolution: " + width + "x" + height);
}
private void enableUI() {
System.out.println("############## logError");
mButtonStart.setEnabled(true);
mButtonCamera.setEnabled(true);
}
// Connects/disconnects to the RTSP server and starts/stops the stream
public void toggleStream() {
mProgressBar.setVisibility(View.VISIBLE);
if (!mClient.isStreaming()) {
String ip, port, path;
// We save the content user inputs in Shared Preferences
SharedPreferences mPrefs = PreferenceManager
.getDefaultSharedPreferences(VideoStream.this);
Editor editor = mPrefs.edit();
editor.putString("uri", "********");
editor.putString("password", "***********");
editor.putString("username", "********");
editor.commit();
// String ip, port, path;
// We parse the URI written in the Editext
Pattern uri = Pattern.compile("rtsp://(.+):(\\d+)/(.+)");
Matcher m = uri.matcher(AppConfig.STREAM_URL);
m.find();
ip = m.group(1);
port = m.group(2);
path = m.group(3);
System.out.println("ip " + ip);
System.out.println("port " + port);
System.out.println("path " + path);
/*
* // We parse the URI written in the Editext Pattern uri =
* Pattern.compile("rtsp://(.+):?(\\d*)/(.+)"); Matcher m =
* uri.matcher(mEditTextURI.getText()); m.find(); ip = m.group(1);
* port = m.group(2); path = m.group(3);
* System.out.println("path is "+path);
*
* System.out.println("port is "+port);
* System.out.println("ip is "+ip);
*/
mClient.setCredentials(AppConfig.PUBLISHER_USERNAME,
AppConfig.PUBLISHER_PASSWORD);
mClient.setServerAddress(ip, Integer.parseInt(port));
mClient.setStreamPath("/" + path);
mClient.startStream();
fileUri = getOutputMediaFileUri();
// Start camera preview
mSession.startPreview();
} else {
// Stops the stream and disconnects from the RTSP server
mClient.stopStream();
// stop camera preview
mSession.stopPreview();
}
}
private void logError(final String msg) {
System.out.println("############## logError");
final String error = (msg == null) ? "Error unknown" : msg;
// Displays a popup to report the eror to the user
AlertDialog.Builder builder = new AlertDialog.Builder(VideoStream.this);
builder.setMessage(msg).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
#Override
public void onBitrateUpdate(long bitrate) {
System.out.println("############## onBitrateUpdate");
mTextBitrate.setText("" + bitrate / 1000 + " kbps");
}
#Override
public void onPreviewStarted() {
System.out.println("############## onPreviewStarted");
if (mSession.getCamera() == CameraInfo.CAMERA_FACING_FRONT) {
mButtonFlash.setEnabled(false);
mButtonFlash.setTag("off");
mButtonFlash.setBackgroundResource(R.drawable.ic_flash_on_holo_light);
} else {
mButtonFlash.setEnabled(true);
}
}
#Override
public void onSessionConfigured() {
System.out.println(" ############## onSessionConfigured");
}
#Override
public void onSessionStarted() {
System.out.println("onSessionStarted");
enableUI();
mButtonStart.setBackgroundResource(R.drawable.record_pressed);
myChronometer.setVisibility(View.VISIBLE);
startTimer();
mProgressBar.setVisibility(View.GONE);
chat32.setVisibility(View.VISIBLE);
}
private void startTimer() {
// TODO Auto-generated method stub
myChronometer.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
myChronometer.start();
}
#Override
public void onSessionStopped() {
System.out.println(" ############## onSessionStopped");
enableUI();
mButtonStart.setBackgroundResource(R.drawable.record_stop);
mButtonStart.setBackgroundResource(R.drawable.record_stop);
stopTimer();
chat32.setVisibility(View.INVISIBLE);
chatedit.setVisibility(View.INVISIBLE);
send.setVisibility(View.INVISIBLE);
mProgressBar.setVisibility(View.GONE);
}
private void stopTimer() {
// TODO Auto-generated method stub
myChronometer.setBase(SystemClock.elapsedRealtime());
myChronometer.stop();
showElapsedTime();
}
private void showElapsedTime() {
// TODO Auto-generated method stub
long elapsedMillis = SystemClock.elapsedRealtime()
- myChronometer.getBase();
Toast.makeText(VideoStream.this,
"Elapsed milliseconds: " + elapsedMillis, Toast.LENGTH_SHORT).show();
}
#Override
public void onSessionError(int reason, int streamType, Exception e) {
System.out.println(" ############## onSessionError");
mProgressBar.setVisibility(View.GONE);
switch (reason) {
case Session.ERROR_CAMERA_ALREADY_IN_USE:
break;
case Session.ERROR_CAMERA_HAS_NO_FLASH:
mButtonFlash.setBackgroundResource(R.drawable.ic_flash_on_holo_light);
mButtonFlash.setTag("off");
break;
case Session.ERROR_INVALID_SURFACE:
break;
case Session.ERROR_STORAGE_NOT_READY:
break;
case Session.ERROR_CONFIGURATION_NOT_SUPPORTED:
VideoQuality quality = mSession.getVideoTrack().getVideoQuality();
logError("The following settings are not supported on this phone: "
+ quality.toString() + " " + "(" + e.getMessage() + ")");
e.printStackTrace();
return;
case Session.ERROR_OTHER:
break;
}
if (e != null) {
logError(e.getMessage());
e.printStackTrace();
}
}
#Override
public void onRtspUpdate(int message, Exception e) {
System.out.println(" ############## onRtspUpdate");
switch (message) {
case RtspClient.ERROR_CONNECTION_FAILED:
case RtspClient.ERROR_WRONG_CREDENTIALS:
mProgressBar.setVisibility(View.GONE);
enableUI();
logError(e.getMessage());
e.printStackTrace();
break;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
System.out.println(" ############## surfaceChanged");
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
mSession.startPreview();
System.out.println(" ############## surfaceCreated");
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
mClient.stopStream();
System.out.println(" ############## surfaceDestroyed");
}
}
you can try this ,
// Video from gallery
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(
Intent.createChooser(intent, "Select Video"),
SELECT_VIDEO);
// Video from Camera
state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mVideoFileTemp = new File(Environment
.getExternalStorageDirectory(),
"Nameofthefile");
} else {
mVideoFileTemp = new File(getApplicationContext()
.getFilesDir(), "Nameofthefile");
}
intent = new Intent(
android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
try {
Uri mImageCaptureUri = null;
// String state = Environment.getExternalStorageState();
if (mVideoFileTemp == null) {
System.out.println("no file found");
} else {
System.out.println("file found");}
if (Environment.MEDIA_MOUNTED.equals(state)) {
mImageCaptureUri = Uri.fromFile(mVideoFileTemp);
} else {
mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
}
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, SELECT_CAMERA_VIDEO_REQUEST);
} catch (ActivityNotFoundException e) {
Log.d("Tag", "cannot take video", e);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_VIDEO && resultCode == Activity.RESULT_OK
&& null != data) {
Uri selectedVideo = data.getData();
String[] filePathColumn = { MediaStore.Video.Media.DATA };
Cursor cursor = getApplicationContext().getContentResolver()
.query(selectedVideo, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String videoPath = cursor.getString(columnIndex);
cursor.close();
videoFile = new File(videoPath);
bitmap_postImage = ThumbnailUtils.createVideoThumbnail(
videoPath, Thumbnails.MICRO_KIND);
setImagePreview(bitmap_postImage);
}
if (requestCode == SELECT_CAMERA_VIDEO_REQUEST
&& resultCode == Activity.RESULT_OK) {
videoFile = mVideoFileTemp;
bitmap_postImage = ThumbnailUtils.createVideoThumbnail(
videoFile.getPath(), Thumbnails.MICRO_KIND);
setImagePreview(bitmap_postImage);
}
}
}
My Problem is, that I capture audio by pressing the record button, but I can't see any audioFile in the specific path.
I capture sound, when I press the capture button:
private void startRecord()
{
ImageButton soundStop = (ImageButton)findViewById(R.id.soundstop);
soundStop.setVisibility(View.VISIBLE);
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
//mediaRecorder.setOutputFormat(sound);
//mediaRecorder.setOutputFile(soundFilePath);
//mediaRecorder.setAudioEncoder(audioEncoder);
//Log.d("hier ", "hier" + soundFilePath);
try {
mediaRecorder.prepare();
mediaRecorder.start();
}catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Aufnahme gestartet", Toast.LENGTH_LONG).show();
}
When I press the Stop Recording Button the file should be saved in the specific path. I tried it with Directory Musik and Downloads, but I can't find any file there
final OnClickListener soundRecordStop = new OnClickListener(){
#Override
public void onClick(View v) {
soundStop();
}
};
public void soundStop(){
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss");
Timestamp time = new Timestamp(System.currentTimeMillis());
String actualTime = sdf.format(time);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = sharedPreferences.getString("soundformat", "format");
int audioEncoder = sharedPreferences.getInt("audioEncoder", Property.getAudioEncoderInt());
String dateiendung = ".aac";
int sound = 6;
if(name == "aac"){
dateiendung = ".aac";
sound = 6;
} else if(name == "amr_nb"){
dateiendung = ".3gp";
sound = 3;
}
else if( name == "amr_wb"){
dateiendung = ".3gp";
sound = 4;
}
else if( name == "default" ){
dateiendung = ".default";
sound = 0;
}
else if( name == "mpeg"){
dateiendung = ".mp4";
sound = 2;
}
else if( name == "gpp" ){
Log.d("in gpp", "in gpp");
dateiendung = ".3gp";
sound = 1;
}
soundFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
soundFilePath = soundFile.getAbsolutePath() + actualTime + dateiendung;
Log.d("hier ", "hier1" + mediaRecorder);
if(mediaRecorder != null){
Log.d("hier ", "hier2" + mediaRecorder);
try {
//mediaRecorder.prepare();
mediaRecorder.stop();
mediaRecorder.release();
//mediaRecorder = null;
Log.d("hier ", "hier4" + mediaRecorder);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mediaRecorder.setOutputFormat(sound);
mediaRecorder.setOutputFile(soundFilePath);
Log.d("hier ", "hier2");
String pfad = soundFile.getAbsolutePath();
Toast.makeText(getApplicationContext(), "Aufnahme in " + pfad + " gespeichert", Toast.LENGTH_LONG).show();
ImageButton soundStop = (ImageButton)findViewById(R.id.soundstop);
soundStop.setVisibility(View.INVISIBLE);
}
The path seems to be correct: pfad /storage/sdcard0/Download17.07.2014 11:55:58.aac
Thanks for the comment the missing File Separator wasn't intentionally. I insert the missing Separator in Order to save the audio File in Downloads Directory. But no File nevertheless 😑
Please help me to find my file ;)
I have several editText in my FirstActivity for CSV:
Button save;
CSV csv;
StringBuffer filePathc;
public final static String EXTRA_MESSAGE = "com.example.mapcard.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_card);
txtName= (EditText) findViewById(R.id.txtName);
txtCompany= (EditText) findViewById(R.id.txtCompany);
txtPhone= (EditText) findViewById(R.id.txtPhone);
txtMobile = (EditText) findViewById(R.id.txtMobile);
txtAddress = (EditText) findViewById(R.id.txtAddress);
txtEmail = (EditText) findViewById(R.id.txtEmail);
txtWebsite = (EditText) findViewById(R.id.txtWebsite);
txtTitle = (EditText) findViewById(R.id.txtTitle);
filePathc = new StringBuffer();
filePathc.append("/sdcard/Android/data/");
file = new File(filePathc+filename.toString());
csv = new CSV(file);
save=(Button)findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
csv.writeHeader(txtName.getText().toString()+ ","
+txtCompany.getText().toString()
+ "," +txtPhone.getText().toString()
+ "," +txtMobile.getText().toString()
+ "," +txtAddress.getText().toString()
+ "," +txtEmail.getText().toString()
+ "," +txtWebsite.getText().toString()
+ "," +txtTitle.getText().toString());
Intent intent = new Intent(NewCard.this, Template.class);
intent.putExtra("name", Name);
intent.putExtra("company", Company);
intent.putExtra("phone", Phone);
intent.putExtra("mobile", Mobile);
intent.putExtra("address", Address);
intent.putExtra("email", Email);
intent.putExtra("website", Website);
intent.putExtra("title", Title);
startActivity(intent);
SecondActivity is to write this data into .csv file:
public class CSV {
private PrintWriter csvWriter;
private File file;
public CSV(File file) {
this.file = file;
}
public void writeHeader(String data) {
try {
if (data != null) {
csvWriter = new PrintWriter(new FileWriter(file, true));
csvWriter.print("\r\n"+",");
csvWriter.print(data);
csvWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}}
File in directory is successfully created and data is inserted. I am trying to check the data like Name or Email, if it is duplicate/already recorded to not save into .csv and warn user with Toast "same data".
I think it is something to do with line:
try {
if (data != null) {
Your helps and suggestions are appreciated. Thank you.
Use following function
public boolean exist(String newData){
try {
FileInputStream fIn = new FileInputStream(file);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
if(aDataRow.contains(newData))//<--check if data exists
return true;
}
txtData.setText(aBuffer);
myReader.close();
} catch (Exception e) {
}
return false;
}
And change your write header function to:
public void writeHeader(String data) {
try {
if (data != null&&!data.isEmpty()&&!exist(data)) {
csvWriter = new PrintWriter(new FileWriter(file, true));
csvWriter.print("\r\n"+",");
csvWriter.print(data);
csvWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
data != null doesnt cover the case that the String is just empty, but not null. So basically you get "" from the textview by calling getText(). adding && !"".equals(data) should fix that problem
UPDATE
Well, there is a difference between an empty, and an uninitalized String. An uninitalized String means you declared it like String a; but nothing further.
If you use editText.getText() the editText will return a String which has been initialized but contains only what is currently in it. So basically if there is nothing in the editext it will return "".
And to sum this up:
String a;
null == "" // false
a == null // true
"".equals(editText.getTExt()) // true if the editext doesnt contain anything