Getting Open Failed EACCES(Permission Denied) - java

I want to write data into a SD card but I am getting the following error: Failed open failed: EACCES (Permission denied).
The Android version I am working on is jelly bean(4.3).
I have also given permission in manifest file.
Here is my code:
package com.example.androidsdcard;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
// GUI controls
EditText txtData;
Button btnWriteSDFile;
Button btnReadSDFile;
Button btnClearScreen;
Button btnClose;
File sample=null;
String SDCard_Path="/mnt/extsd";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// bind GUI elements with local controls
txtData = (EditText) findViewById(R.id.txtData);
txtData.setHint("Enter some lines of data here...");
btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
btnWriteSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
File storageDir = new File(SDCard_Path);
String sample1 = Environment.getExternalStorageDirectory().getPath();
Toast.makeText(MainActivity.this,sample1, Toast.LENGTH_LONG).show();
if(sample == null)
{
Toast.makeText(MainActivity.this,"Sample == null executed", Toast.LENGTH_LONG).show();
}
else
Toast.makeText(MainActivity.this,"Sample == null skipped", Toast.LENGTH_LONG).show();
if(storageDir.isDirectory())
{
String[] dirList = storageDir.list();
if(dirList==null)
{
Toast.makeText(getBaseContext(),"Failed to detect SD card",Toast.LENGTH_SHORT).show();
return;
}
else
Toast.makeText(getBaseContext(),"SD Card Detected",Toast.LENGTH_SHORT).show();
}
try {
File myFile = new File("/mnt/extsd/MedeQuip.txt");
/* if(myFile.createNewFile()==false)
{
Toast.makeText(getBaseContext(),"Unable to create File'",Toast.LENGTH_SHORT).show();
return;
}
else
Toast.makeText(getBaseContext(),"File Created'",Toast.LENGTH_SHORT).show();
*/ FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing SD mysdfile.txt'",Toast.LENGTH_SHORT).show();
} catch (Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}// onClick
}); // btnWriteSDFile
btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile);
btnReadSDFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// write on SD card file data in the text box
try
{
File myFile = new File(SDCard_Path+"/MedeQuip.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),"Done reading SD 'MedeQuip.txt'",Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}// onClick
}); // btnReadSDFile
btnClearScreen = (Button) findViewById(R.id.btnClearScreen);
btnClearScreen.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// clear text box
txtData.setText("");
}
}); // btnClearScreen
btnClose = (Button) findViewById(R.id.btnClose);
btnClose.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// clear text box
finish();
}
}); // btnClose
}// onCreate
}// AndSDcard
Here is my xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/txtData"
android:layout_width="fill_parent"
android:layout_height="180px"
android:textSize="18sp" />
<Button
android:id="#+id/btnWriteSDFile"
android:layout_width="143px"
android:layout_height="44px"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtData"
android:layout_marginTop="60dp"
android:text="1. Write SD File" />
<Button
android:id="#+id/btnClearScreen"
android:layout_width="141px"
android:layout_height="42px"
android:layout_alignBaseline="#+id/btnWriteSDFile"
android:layout_alignBottom="#+id/btnWriteSDFile"
android:layout_marginLeft="30dp"
android:layout_toRightOf="#+id/btnWriteSDFile"
android:text="2. Clear Screen" />
<Button
android:id="#+id/btnReadSDFile"
android:layout_width="140px"
android:layout_height="42px"
android:layout_alignTop="#+id/btnWriteSDFile"
android:layout_marginLeft="32dp"
android:layout_toRightOf="#+id/btnClearScreen"
android:text="3. Read SD File" />
<Button
android:id="#+id/btnClose"
android:layout_width="141px"
android:layout_height="43px"
android:layout_alignTop="#+id/btnClearScreen"
android:layout_marginLeft="61dp"
android:layout_toRightOf="#+id/btnReadSDFile"
android:text="4. Close" />
</RelativeLayout>
Here is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidsdcard"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</manifest>

You cannot assume external storage will always be at "/mnt/extsd". Very rarely will this be the case as it is up to the OEM where the mount points are. Use the standard APIs from the Context object to get the correct locations of interest: Context.getExternalFilesDir() and Context.getExternalFilesDirs().

the problem is with jelly bean
this work for me
String path = null;
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT){
path = getActivity().getCacheDir() + File.separator + "name";
} else{
path = Environment.getExternalStorageDirectory() + File.separator + "name";
}

Related

Issue in making UPI payment request from android

UPI payment failed in PhonePe while testing my android application.
The error it is showing is - For security reasons, you are not allowed to send money from your bank account for this payment. You don't have to enter UPI PIN to receive money/cashback.
MainActivity.java contains -
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private Button pay_btn;
final int UPI_PAYMENT = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pay_btn = (Button) findViewById(R.id.pay_btn);
pay_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
payUsingUpi("1","Test Payment","Ratnadeep Parya","parya.ratnadeep125#okaxis");
}
});
}
private void payUsingUpi(String amounttxt, String notetxt, String nametxt, String upitxt) {
Uri uri = Uri.parse("upi://pay").buildUpon()
.appendQueryParameter("pa",upitxt)
.appendQueryParameter("pn",nametxt)
.appendQueryParameter("tn",notetxt)
.appendQueryParameter("am",amounttxt)
.appendQueryParameter("cu","INR")
.build();
Intent upi_payment = new Intent(Intent.ACTION_VIEW);
upi_payment.setData(uri);
Intent chooser = Intent.createChooser(upi_payment,"Pay with");
if (null!=chooser.resolveActivity(getPackageManager())){
startActivityForResult(chooser,UPI_PAYMENT);
}
else {
Toast.makeText(this, "No UPI app found!", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case UPI_PAYMENT:
if ((RESULT_OK==resultCode|| (resultCode==11))){
if (data!=null){
String txt = data.getStringExtra("response");
Log.d("UPI", "onActivityResult: "+ txt);
ArrayList<String>dataLst=new ArrayList<>();
dataLst.add("Nothing");
upipaymentdataoperation(dataLst);
}
else {
Log.d("UPI", "onActivityResult: "+ "Return data is null!");
ArrayList<String>dataLst=new ArrayList<>();
dataLst.add("Nothing");
upipaymentdataoperation(dataLst);
}
}
else {
Log.d("UPI", "onActivityResult: "+ "Return data is null!");
ArrayList<String>dataLst=new ArrayList<>();
dataLst.add("Nothing");
upipaymentdataoperation(dataLst);
}
break;
}
}
private void upipaymentdataoperation(ArrayList<String> data) {
if (isConnectionAvailable(MainActivity.this)){
String str = data.get(0);
Log.d("UPIPAY", "upipaymentdataoperation: "+str);
String paymentCancel="";
if (str==null)str="discard";
String status = "";
String approvalref = "";
String response[]=str.split("&");
for (int i=0;i<response.length;i++){
String equalStr[]=response[i].split("=");
if (equalStr.length>=2){
if (equalStr[0].toLowerCase().equals("Status".toLowerCase())){
status=equalStr[1].toLowerCase();
}
else if(equalStr[0].toLowerCase().equals("approval Ref".toLowerCase())||
equalStr[0].toLowerCase().equals("txnRef".toLowerCase()))
{
approvalref=equalStr[1];
}
}
else {
paymentCancel="Payment cancelled by user";
if (status.equals("success")){
Toast.makeText(this, "Transaction success", Toast.LENGTH_SHORT).show();
Log.d("UPI", "responsestr: "+approvalref);
}
else if ("Payment cancelled by user".equals(paymentCancel)){
Toast.makeText(this, "Payment cancelled by user", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Transaction failed", Toast.LENGTH_SHORT).show();
}
}
}
}
else {
Toast.makeText(this, "No internet", Toast.LENGTH_SHORT).show();
}
}
private boolean isConnectionAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager!=null){
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo!=null && networkInfo.isConnected() && networkInfo.isConnectedOrConnecting() && networkInfo.isAvailable()){
return true;
}
}
return false;
}
}
AndroidManifest.xml contains -
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.UpiTesting"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml contains -
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
tools:context=".MainActivity">
<Button
android:id="#+id/pay_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pay_with_upi"
android:backgroundTint="#android:color/holo_green_dark"
android:layout_centerInParent="true"
android:textSize="20sp"/>
</RelativeLayout>
Please assist me to get rid of this issue.
I was trying to test UPI payment by sending request in UPI application.
In PhonePe it is showing that - For security reasons, you are not allowed to send money from your bank account for this payment. You don't have to enter UPI PIN to receive money/cashback.

Android Studio MediaRecorder won't record

I trying to build an audio recorder in the android studio. I followed this tutorial:
https://www.youtube.com/watch?v=XANjoeEeQ1Y
Which did not work for me? When I pushed the "record" button, nothing happened.
Therefrom I added action listeners with onClick() methods and such. Still didn't work. Then I added a text view to show me the status for debugging purpose.
After adding the status textView I found out that the beginRecording() method goes straight to the catch statement.
I watched another youtube video
https://www.youtube.com/watch?v=lWaypoRVfSc
which seems to do more or less the same thing regarding the MediaRecorder.
So.. My question is. What have I done wrong? How can I make it actually record when the RECORD button is pushed?
Thank you in advance.
Here comes my code:
package com.example.natalie.recorder;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPLayer;
private MediaRecorder recorder;
private String OUTPUT_FILE;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button startR = (Button) findViewById(R.id.startBtn);
Button stopR = (Button) findViewById(R.id.finishBtn);
Button playRecording = (Button) findViewById(R.id.playBtn);
Button stopPlaying = (Button) findViewById(R.id.stopBtn);
final TextView statusTV;
statusTV = (TextView) findViewById(R.id.statusTextView);
OUTPUT_FILE= Environment.getExternalStorageDirectory().getAbsolutePath()+"/audiorecorder.3gpp";
/*------START BUTTON------*/
startR.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
final TextView stv=statusTV;
try {
beginRecording();
stv.setText("Recording");
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
stv.setText("Error");
}
}
});
/*------STOP BUTTON------*/
stopR.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
final TextView stv=statusTV;
try {
stopRecording();
stv.setText("Stopped");
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
statusTV.setText("Error");
Log.d("here","dd",e);
}
}
});
playRecording.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
try {
playRecording();
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
statusTV.setText("Error");
}
}
});
stopPlaying.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
try {
stopPlayback();
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
statusTV.setText("Error");
}
}
});
}
private void stopPlayback() throws Exception{
if(mediaPLayer != null)
mediaPLayer.stop();
}
private void playRecording() throws IOException {
ditchMediaPLayer();
mediaPLayer = new MediaPlayer();
mediaPLayer.setDataSource(OUTPUT_FILE);
mediaPLayer.prepare();
mediaPLayer.start();
}
private void ditchMediaPLayer() {
if (mediaPLayer != null) {
try{
mediaPLayer.release();
} catch(Exception e) {
e.printStackTrace();
}
}
}
private void stopRecording() {
if(recorder != null)
recorder.stop();
}
private void beginRecording() throws Exception{
ditchMediaRecorder();
File outFile = new File(OUTPUT_FILE);
if (outFile.exists()) {
outFile.delete();
}
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
record.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(OUTPUT_FILE);
recorder.prepare();
recorder.start();
}
private void ditchMediaRecorder() {
if(recorder != null)
recorder.release();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The AndroidManifest look like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.natalie.recorder">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.RECORD_AUDIO"
/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The content_main.xml comes here:
<Button
android:id="#+id/stopBtn"
android:layout_width="249dp"
android:layout_height="56dp"
android:background="#color/colorAccent"
android:text="Stop PLayback"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/playBtn" />
<Button
android:id="#+id/playBtn"
android:layout_width="249dp"
android:layout_height="48dp"
android:background="#color/colorAccent"
android:text="Play Recording"
app:layout_constraintBottom_toTopOf="#+id/stopBtn"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/finishBtn" />
<Button
android:id="#+id/finishBtn"
android:layout_width="249dp"
android:layout_height="48dp"
android:background="#color/colorAccent"
android:text="Finish Recording"
app:layout_constraintBottom_toTopOf="#+id/playBtn"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/startBtn" />
<Button
android:id="#+id/startBtn"
android:layout_width="247dp"
android:layout_height="48dp"
android:background="#color/colorAccent"
android:text="Start Recording"
app:layout_constraintBottom_toTopOf="#+id/finishBtn"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/statusTextView"
android:layout_width="246dp"
android:layout_height="22dp"
android:text="Status"
android:textAlignment="center"
android:textSize="24sp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toTopOf="#+id/startBtn"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
You asked for CAMERA, WRITE_STORAGE and RECORD_AUDIO permission but you don't asked for at your activity. take a look at this.
use:
ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) to check the status of the permission and compare it with PackageManager.PERMISSION_GRANTED which mean that your permission is accepted like this :
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
}
and inside the onRequestPermissionsResult do something like this :
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//do work
}
}

Starting Android Camera with Intent crashes

i am new in the programming for Android. And I get a inexplicable Exception in my App and i hope you can help me. The app covers the following Use-Case:
The user press on the "take photo" Button
The Google Camera will be open
The Image will be save in the storage of the device
The Path, where the image stored will be listet in a listview
The user can click again on the button "take photo" (goto 2)
At firsttime the user can take photo succesful and the path will be show correctly in the app. But in case of clicking again the user can take a photo but the app crashes without a Exception when i want to save the image.
Scanning.java
package de.des;
import android.content.Intent;
import android.content.res.Configuration;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import de.auftrag.R;
public class Scanning extends AppCompatActivity {
private List<String> pathlist;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanning);
final ListView listview = (ListView) findViewById(R.id.listView);
mimageView = (ImageView) this.findViewById(R.id.imageView);
pathlist = new ArrayList<>();
adapter = new ArrayAdapter<String>(this,R.layout.mylist, pathlist);
listview.setAdapter(adapter);
}
private static final int TAKE_PHOTO_CODE = 1;
public void takePhoto(View view) {
File file = new File(Environment.getExternalStorageDirectory(), "fname_" +
String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
file.createNewFile();
this.pathlist.add(file.getAbsolutePath());
this.adapter.notifyDataSetChanged();
} catch (IOException e) {
Log.d("Scanning",e.getMessage());
}
Uri outputFileUri = Uri.fromFile(file);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, 3);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
activity_scanning.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="de.des.Scanning">
<Button
android:id="#+id/btnTakePhoto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/str_take_foto"
android:onClick="takePhoto"/>
<Button
android:id="#+id/btnSelectFile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/str_read_file"
android:onClick="selectFile"
android:layout_below="#+id/btnTakePhoto"
android:layout_alignParentStart="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_below="#+id/btnSelectFile"
android:layout_alignParentStart="true"
android:layout_marginTop="73dp" />
</RelativeLayout>
AndroidMainifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.auftrag">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA"/>
<application
android:allowBackup="true"
android:icon="#mipmap/logo"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name="de.des.Scanning"
android:configChanges="orientation|screenSize"/>
<activity android:name="de.des.ObjektdatenMap" />
</application>
</manifest>
Best wishes
Dominik
Try this:
private static final int TAKE_PHOTO_CODE = 1;
public void takePhoto(View view) {
File file = new File(Environment.getExternalStorageDirectory(), "fname_" +
String.valueOf(System.currentTimeMillis()) + ".jpg");
Uri outputFileUri = Uri.fromFile(file);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra("pic_path", file.getAbsolutePath());
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PHOTO_CODE:
if(resultCode == Activity.RESULT_OK) {
Uri imageUri = data.getData();
String path = data.getExtras().getString("pic_path");
pathlist.add(path);
adapter.notifyDataSetChanged();
}
break;
}
}

FileNotFoundException when try to generate PDF in android

In here i'm try to generate a pdf file in android, but in the run time i get this execption
ioException:java.io.FileNotFoundException: /storage/sdcard/PDF/Demo.pdf: openfailed: ENOENT (No such file or directory)
this is my code
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfWriter;
public class MainActivity extends Activity {
private Button createPDF , openPDF;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createPDF = (Button)findViewById(R.id.button1);
createPDF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
createPDF();
}
});
openPDF = (Button)findViewById(R.id.button2);
openPDF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
openPdf();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void createPDF(){
Document doc =new Document();
try {
String parth = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
File dir = new File(parth);
if(!dir.exists())
dir.mkdir();
Log.d("PDFCreater", "PDF PARTH "+parth);
File file = new File(dir,"demo.pdf");
Log.d("PDFCreater", "Create");
FileOutputStream fOut = new FileOutputStream(file);
Log.d("PDFCreater", "1");
PdfWriter.getInstance(doc, fOut);
Log.d("PDFCreater", "2");
doc.open();
Log.d("PDFCreater", "open");
Paragraph p1= new Paragraph("Customer History");
Font paraFont = new Font(Font.HELVETICA);
paraFont.setSize(16);
p1.setAlignment(Paragraph.ALIGN_CENTER);
p1.setFont(paraFont);
doc.add(p1);
Log.d("PDFCreater", "add");
/* Inserting Image in PDF */
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.apple);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
//add image to document
doc.add(myImg);
Phrase footerText = new Phrase("This is an example of a footer");
HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
doc.setFooter(pdfFooter);
Toast.makeText(getApplicationContext(), "Created...", Toast.LENGTH_LONG).show();
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
}
finally
{
doc.close();
}
}
void openPdf()
{
Intent intent = new Intent(Intent.ACTION_VIEW);
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
File file = new File(path, "demo.pdf");
intent.setDataAndType( Uri.fromFile( file ), "application/pdf" );
startActivity(intent);
}
}
here is my xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginLeft="56dp"
android:layout_marginTop="50dp"
android:text="Create" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_below="#+id/button1"
android:layout_marginTop="38dp"
android:text="Open" />
</RelativeLayout>
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.isuru.mypdf"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.isuru.mypdf.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I think that the exception throws on this line
FileOutputStream fOut = new FileOutputStream(file);
please help me , thank you !
Have you declared this permission in the android manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Add read and write permission in manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Check here:
Getting file from sdcard with Uri

Tesseract ANPR for Android

I'm using tesseract-android-tools (pre-built lib) for ANPR. But having problem when the image background is worse. Can anybody suggest how can I focus/get rectangular area of/from image taken from camera. Despite of searching the forum I'm unable to get a working example on this.
Here is my code:~
1) AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ocrtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.ocrtest.OcrActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
2) main.xml (layout)
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="Output"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Take Pic" />
</LinearLayout>
<TextView
android:id="#+id/field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="N/A" />
</LinearLayout>
</ScrollView>
3) OcrActivity.java
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.googlecode.tesseract.android.TessBaseAPI;
public class OcrActivity extends Activity implements View.OnClickListener {
protected Button _button;
protected ImageView _image;
protected TextView _field;
protected String _path;
protected boolean _taken;
protected static final String PHOTO_TAKEN = "photo_taken";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
_image = (ImageView) findViewById(R.id.image);
_field = (TextView) findViewById(R.id.field);
_button = (Button) findViewById(R.id.button);
_button.setOnClickListener(this);
File f = new File(Environment.getExternalStorageDirectory()
+ "/tessaract_languages");
if (f.isDirectory()) {
File imgDirectory = new File(
Environment.getExternalStorageDirectory() + "/images/");
imgDirectory.mkdirs();
} else {
Toast.makeText(getApplicationContext(),
"OCR library files missing.", Toast.LENGTH_LONG).show();
finish();
}
_path = Environment.getExternalStorageDirectory()
+ "/images/make_machine_example.jpg";
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button:
Log.i("MakeMachine", "ButtonClickHandler.onClick()");
startCameraActivity();
break;
}
}
protected void startCameraActivity() {
Log.i("MakeMachine", "startCameraActivity()");
File file = new File(_path);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("MakeMachine", "resultCode: " + resultCode);
switch (resultCode) {
case 0:
Log.i("MakeMachine", "User cancelled");
break;
case -1:
try {
onPhotoTaken();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
protected void onPhotoTaken() throws IOException {
_taken = true;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(_path, options);
_image.setImageBitmap(bitmap);
// _field.setVisibility(View.GONE);
ExifInterface exif = new ExifInterface(_path);
int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL);
int rotate = 0;
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
}
if (rotate != 0) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
} else {
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
}
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.init(Environment.getExternalStorageDirectory()+ "/tessaract_languages/", "eng");
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
System.out.println(recognizedText);
_field.setText(recognizedText);
baseApi.end();
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.i("MakeMachine", "onRestoreInstanceState()");
if (savedInstanceState.getBoolean(OcrActivity.PHOTO_TAKEN)) {
try {
onPhotoTaken();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(OcrActivity.PHOTO_TAKEN, _taken);
}
}

Categories

Resources