Starting Android Camera with Intent crashes - java

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;
}
}

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.

How to fix this Java code to upload file with webview element android studio

Developing very basic app for my site to upload files to server using a webview to emulate the desktop process, failing to get it to work.
I have copied code from GitHub to form this app, however when I press the input button on the HTML form I am prompted to select a file from my phone's storage, after doing so the selected file doesn't show up in the HTML form, and pressing the button again results in no action. I've no idea why and I really don't know Java, can anyone help? (YouTube video of original GitHub poster - https://www.youtube.com/watch?v=oFGQbXdWv-g) (Github page - https://github.com/tarikul1988/WebViewFileUploadWorking)
The entire project code is as follows;
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context="com.xyz.imagedrop.MainActivity">
<WebView
android:id="#+id/webview_sample"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
</LinearLayout>
MainActivity.java:
package com.xyz.imagedrop;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private final static int FCR = 1;
WebView webView;
private String mCM;
private ValueCallback<Uri> mUM;
private ValueCallback<Uri[]> mUMA;
#SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webview_sample);
if (Build.VERSION.SDK_INT >= 23 &&(ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
assert webView != null;
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
if (Build.VERSION.SDK_INT >= 21) {
webSettings.setMixedContentMode(0);
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else if (Build.VERSION.SDK_INT < 19) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new Callback());
//webView.loadUrl("https://infeeds.com/");
webView.loadUrl("http://imagedrop.xyz");
webView.setWebChromeClient(new WebChromeClient() {
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
if (mUMA != null) {
mUMA.onReceiveValue(null);
}
mUMA = filePathCallback;
// Intent takePictureIntent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Intent contentSelectionIntent = new
Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
// Intent[] intentArray;
//
// if (takePictureIntent != null) {
// intentArray = new Intent[]{takePictureIntent};
// } else {
// intentArray = new Intent[0];
// }
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT,
contentSelectionIntent);
// chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image
Chooser");
// chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
intentArray);
startActivityForResult(chooserIntent, FCR);
return true;
}
});
}
public class Callback extends WebViewClient {
public void onReceivedError(WebView view, int errorCode, String
description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Failed loading app!",
Toast.LENGTH_SHORT).show();
}
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xyz.imagedrop">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE">
</uses-permission>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
android:usesCleartextTraffic="true"
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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Why my app is crashing on clicking any of the buttons?

I am trying to use intents but on clicking any of the buttons,the app stops working and terminates.I am a beginner and I couldn't find the reason.I am providing my xml file,java file and menifest file.Please someone help.
here is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:orientation="vertical"
tools:context="com.example.shreya.intents.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Set Alarm"
android:id="#+id/alarm"
android:onClick="setAlarm"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Map"
android:id="#+id/map"
android:onClick="seeMap"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Mail"
android:id="#+id/mail"
android:onClick="email"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email ID"
android:inputType="textCapWords"
android:id="#+id/address"/>
</LinearLayout>
And here is my .java file:
package com.example.shreya.intents;
import android.content.Intent;
import android.net.Uri;
import android.provider.AlarmClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
import static com.example.shreya.intents.R.id.alarm;
public class MainActivity extends AppCompatActivity {
private Button mail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void setAlarm(){
String message="Wake Up";
int hour=7;
int minutes=0;
Intent intent = new Intent(AlarmClock.ACTION_SHOW_ALARMS);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
public void seeMap(){
String uri = String.format(Locale.ENGLISH, "geo:%f,%f", 28.699884, 77.273075);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(uri));
if(intent.resolveActivity(getPackageManager())!=null)
startActivity(intent);
}
public void email(){
EditText mail=(EditText)findViewById(R.id.address);
String add=mail.getText().toString();
composeEmail(add,"shreya");
}
public void composeEmail(String addresses, String subject) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT,"hello");
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
}
And finally this is my menifest file:
<?xml version="1.0" encoding="utf-8"?>
<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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
You have to add parameter View view to your onClick methods.
For example:
public void setAlarm(View view){
}
Add that parameter to other onClick methods also: email and seeMap.
Under the hood, the system uses reflection to figure out the exact onClick method in the Activity and the system uses the following exact pattern to find the method: a public void method with the specified method name in the xml onClick attribute and has a single parameter View.

Getting Open Failed EACCES(Permission Denied)

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";
}

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