The app crashes when file is not selected by file picker - android

I am trying to build an OCR app using Google's API. Now this activity lets user select an image file using file picker, from where text is extracted. The app works fine if a user selects an image file but if you open file picker and do not select file then the app crashes.
Suppose you clicked on browse button and file picker opens but you do not select any file and press back button then it that case app crashes,but if you will select a file then it works fine.
Here I am attaching the code.
package com.example.rahulranjan.synthesize;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.text.Text;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.UUID;
public class ocr extends AppCompatActivity {
Button b, convert;
EditText t;
Uri uri;
InputStream inputStream = null;
String str = "";
StringBuffer buf = new StringBuffer();
String text;
Bitmap bitmap;
private String imagePath = "";
TextView txtView;
StringBuilder strBuilder2 = new StringBuilder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ocr);
b = (Button) findViewById(R.id.button);
convert = (Button) findViewById(R.id.button2);
t = (EditText) findViewById(R.id.editText);
txtView = (TextView) findViewById(R.id.textView5);
txtView.setMovementMethod(new ScrollingMovementMethod());
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(" */* ");
startActivityForResult(intent, 7);
}
});
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Syntesize Text");
imagesFolder.mkdirs();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String fileSelected = data.getStringExtra("fileSelected");
Bundle result = data.getExtras();
if (resultCode == RESULT_OK) {
if (data != null) {
// Get the URI of the selected file
Uri uri = data.getData();
t.setText(uri.getPath().toString());
try {
inputStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
TextRecognizer txtRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!txtRecognizer.isOperational()) {
// Shows if your Google Play services is not up to date or OCR is not supported for the device
// txtView.setText("Detector dependencies are not yet available");
Toast toast = Toast.makeText(getApplicationContext(), "Detector dependencies are not yet available", Toast.LENGTH_LONG);
toast.show();
} else {
// Set the bitmap taken to the frame to perform OCR Operations.
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray items = txtRecognizer.detect(frame);
StringBuilder strBuilder = new StringBuilder();
// The following Process is used to show how to use lines & elements as well
for (int i = 0; i < items.size(); i++) {
TextBlock item = (TextBlock) items.valueAt(i);
strBuilder.append(item.getValue());
strBuilder.append(".");
for (Text line : item.getComponents()) {
//extract scanned text lines here
Log.v("lines", line.getValue());
for (Text element : line.getComponents()) {
//extract scanned text words here
Log.v("element", element.getValue());
}
}
}
strBuilder2 = strBuilder;
}
txtView.setText(strBuilder2.toString());
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void clear(View view)
{
txtView.setText("");
}
public void convert(View view)
{
String data = strBuilder2.toString();
File gpxfile = new File(Environment.getExternalStorageDirectory().toString()+"/Syntesize Text"+"/"+ UUID.randomUUID().toString()+".txt");
try (FileWriter writer = new FileWriter(gpxfile)) {
try {
writer.append(data);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
writer.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
writer.close();
} catch (IOException e1) {
e1.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
}
}

might be NPE move these two lines
String fileSelected = data.getStringExtra("fileSelected");
Bundle result = data.getExtras();
inside
if (data != null) {
final result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (data != null) {
// Get the URI of the selected file
String fileSelected = data.getStringExtra("fileSelected");
Bundle result = data.getExtras();
Uri uri = data.getData();
t.setText(uri.getPath().toString());
try {
inputStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
TextRecognizer txtRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!txtRecognizer.isOperational()) {
// Shows if your Google Play services is not up to date or OCR is not supported for the device
// txtView.setText("Detector dependencies are not yet available");
Toast toast = Toast.makeText(getApplicationContext(), "Detector dependencies are not yet available", Toast.LENGTH_LONG);
toast.show();
} else {
// Set the bitmap taken to the frame to perform OCR Operations.
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray items = txtRecognizer.detect(frame);
StringBuilder strBuilder = new StringBuilder();
// The following Process is used to show how to use lines & elements as well
for (int i = 0; i < items.size(); i++) {
TextBlock item = (TextBlock) items.valueAt(i);
strBuilder.append(item.getValue());
strBuilder.append(".");
for (Text line : item.getComponents()) {
//extract scanned text lines here
Log.v("lines", line.getValue());
for (Text element : line.getComponents()) {
//extract scanned text words here
Log.v("element", element.getValue());
}
}
}
strBuilder2 = strBuilder;
}
txtView.setText(strBuilder2.toString());
}
}
super.onActivityResult(requestCode, resultCode, data);
}
also better check for requestCode too
condition should be
if (resultCode == RESULT_OK && data!=null && requestCode==7) {
//your code
}

Related

Using a Sent Email Intent with two attachments

I am writing a scavenger hunt type app that allows for the user to take one or two photos of a bonus location and then submit those images via email. However, I can't seem to get it to put both images in the email, it only gets the most recent one.
I found this answer: Cant send email with multiple attachment in android programmatically, which seems to say that I must do this using an array, but the example there doesn't seem to match at all what I'm doing so I'm not certain how to make the array.
Below is my current code. Could someone tell me how to make my two EXTRA_STREAMS into the requisite array (or point me in the correct direction if that is not the proper fix)?
package net.tommyc.android.tourofhonor;
import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.File;
import java.io.IOException;
public class captureBonus extends AppCompatActivity {
/**
* Opens an already installed Camera application
*/
static final int REQUEST_TAKE_PHOTO = 1;
int riderNumToH = 479;
int pillionNumToH = 000;
String submissionEmailAddress = "me#tommyc.net";
Button btnTakeMainPic;
Button btnSubmitBonus;
ImageView imageViewMain;
ImageView imageViewSecondary;
int tappedImageView = 3;
File mainPhotoUri = null;
File secondaryPhotoUri = null;
/**
* Saves the full size image to the public photo directory (similar to the Camera Roll on iOS)
* * saveImage(imageName: "2018_\(riderNumToH)_\(bonusCodeLabel.text!)_1.jpg")
*/
String mainPhotoPath;
String secondaryPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capture_bonus);
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
}
btnSubmitBonus = findViewById(R.id.btnSubmitBonus);
btnSubmitBonus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchSubmitBonusIntent();
}
});
imageViewMain = findViewById(R.id.bonusMainImage);
imageViewMain.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tappedImageView = 0;
dispatchTakeMainPictureIntent();
Log.v("User Action", "Main Image Tapped");
}
});
imageViewSecondary = findViewById(R.id.bonusSecondaryImage);
imageViewSecondary.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tappedImageView = 1;
dispatchTakeMainPictureIntent();
Log.v("User Action", "Main Image Tapped");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
if (tappedImageView == 0) {
Bitmap bitmap = BitmapFactory.decodeFile(mainPhotoPath);
imageViewMain.setImageBitmap(bitmap);
} else if (tappedImageView == 1) {
Bitmap bitmap = BitmapFactory.decodeFile(secondaryPhotoPath);
imageViewSecondary.setImageBitmap(bitmap);
} else {
Log.w("ERROR", "onActivityResult: valid view ID not found (" + tappedImageView + ")");
}
}
}
}
private void dispatchTakeMainPictureIntent() {
Intent takeMainPictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takeMainPictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
if (tappedImageView == 0) {
mainPhotoUri = createImageFile();
} else if (tappedImageView == 1) {
secondaryPhotoUri = createImageFile();
}
} catch (IOException ex) {
// Error occurred while creating the File
Log.e("fileCreationError", "An error occurred while creating the image file.");
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(captureBonus.this, "net.tommyc.android.tourofhonor", photoFile);
takeMainPictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takeMainPictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String imagePath = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).toString();
String mainImageFileName = "2019_" + riderNumToH + "_BonusCode_1.jpg";
String secondaryImageFileName = "2019_" + riderNumToH + "_BonusCode_2.jpg";
if (tappedImageView == 0) {
File capturedImage = new File(imagePath, mainImageFileName);
mainPhotoPath = capturedImage.getAbsolutePath();
return capturedImage;
} else if (tappedImageView == 1) {
File capturedImage = new File(imagePath, secondaryImageFileName);
secondaryPhotoPath = capturedImage.getAbsolutePath();
return capturedImage;
} else {
Log.w("ERROR", "createImageFile: valid view ID not found (" + tappedImageView + ")");
}
return null;
}
/**
* Submits the bonus images via email.
*/
private void dispatchSubmitBonusIntent() {
Intent sendEmailIntent = new Intent(Intent.ACTION_SEND);
sendEmailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sendEmailIntent.setType("plain/text");
sendEmailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{submissionEmailAddress});
sendEmailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "2019_" + riderNumToH + "_BonusCode");
sendEmailIntent.putExtra(Intent.EXTRA_TEXT, "Sent from TOH App\nAndroid Version 0.3.076");
if (mainPhotoPath != null) {
sendEmailIntent.putExtra(android.content.Intent.EXTRA_STREAM, FileProvider.getUriForFile(captureBonus.this, "net.tommyc.android.tourofhonor", mainPhotoUri));
Log.v("MainImageFound", mainPhotoPath + "|" + mainPhotoUri);
if (secondaryPhotoPath != null) {
sendEmailIntent.putExtra(android.content.Intent.EXTRA_STREAM, FileProvider.getUriForFile(captureBonus.this, "net.tommyc.android.tourofhonor", secondaryPhotoUri));
Log.v("SecondaryImageFound", secondaryPhotoPath + "|" + secondaryPhotoUri);
} else {
Log.e("NoImageFound", "Image Not Found");
}
}
this.startActivity(Intent.createChooser(sendEmailIntent, "Sending email..."));
}
}
You should put all your files Uri's to Arraylist<Parcelable> then put it to intent by intent.putParcelableArrayListExtra

Camera is giving very big size image on device

In my project, I am capturing image from the camera. I am taking the full-size image from the app (instead of taking thumbnail). Captured image is of very big size which is 7 to 18 mb. When I have taken image from my default camera app, the size was roughly 2.5 mb only. As well as it's taking lot of time(6-10 seconds) to load and save to the folder. This happening only when I am using the android device, on emulator it's working good. This is my code:
package com.stegano.strenggeheim.fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.stegano.strenggeheim.BuildConfig;
import com.stegano.strenggeheim.R;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
public class FragmentEncode extends Fragment {
private static final String MESSAGE_IMAGE_SAVED = "Image Saved!";;
private static final String MESSAGE_FAILED = "Failed!";
private static final String IMAGE_DIRECTORY = "/StrengGeheim";
private static final int GALLERY = 0, CAMERA = 1;
private File capturedImage;
TextView imageTextMessage;
ImageView loadImage;
public FragmentEncode() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
private void galleryIntent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri fileUri = getOutputMediaFileUri();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA);
}
private Uri getOutputMediaFileUri() {
try {
capturedImage = getOutputMediaFile();
return FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".provider", capturedImage);
}
catch (IOException ex){
ex.printStackTrace();
Toast.makeText(getContext(), MESSAGE_FAILED, Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_encode, container, false);
imageTextMessage = view.findViewById(R.id.imageTextMessage);
loadImage = view.findViewById(R.id.loadImage);
loadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
return view;
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(getContext());
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera",
"Cancel"
};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
galleryIntent();
break;
case 1:
cameraIntent();
break;
case 2:
dialog.dismiss();
break;
}
}
});
pictureDialog.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_CANCELED) {
return;
}
try {
if (requestCode == GALLERY && data != null) {
Bitmap bitmap = getBitmapFromData(data, getContext());
File mediaFile = getOutputMediaFile();
String path = saveImage(bitmap, mediaFile);
Log.println(Log.INFO, "Message", path);
Toast.makeText(getContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_SHORT).show();
loadImage.setImageBitmap(bitmap);
imageTextMessage.setVisibility(View.INVISIBLE);
} else if (requestCode == CAMERA) {
final Bitmap bitmap = BitmapFactory.decodeFile(capturedImage.getAbsolutePath());
loadImage.setImageBitmap(bitmap);
saveImage(bitmap, capturedImage);
Toast.makeText(getContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_SHORT).show();
imageTextMessage.setVisibility(View.INVISIBLE);
}
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(getContext(), MESSAGE_FAILED, Toast.LENGTH_SHORT).show();
}
}
private Bitmap getBitmapFromData(Intent intent, Context context){
Uri selectedImage = intent.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver()
.query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
return BitmapFactory.decodeFile(picturePath);
}
private String saveImage(Bitmap bmpImage, File mediaFile) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmpImage.compress(Bitmap.CompressFormat.PNG, 50, bytes);
try {
FileOutputStream fo = new FileOutputStream(mediaFile);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(getContext(),
new String[]{mediaFile.getPath()},
new String[]{"image/png"}, null);
fo.close();
return mediaFile.getAbsolutePath();
} catch (IOException ex) {
ex.printStackTrace();
}
return "";
}
private File getOutputMediaFile() throws IOException {
File encodeImageDirectory =
new File(Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
if (!encodeImageDirectory.exists()) {
encodeImageDirectory.mkdirs();
}
String uniqueId = UUID.randomUUID().toString();
File mediaFile = new File(encodeImageDirectory, uniqueId + ".png");
mediaFile.createNewFile();
return mediaFile;
}
}
Something you could do is download an available API online, or, if need be, dowload the source code of some online compressor. Then you could use it as a model. Never directly use the source code. One that is widely supported across languages is: https://optimus.keycdn.com/support/image-compression-api/
I am taking the image from the camera and getting the File. So, I am saving the image directly in file location which I generated using getOutputMediaFile() method. For that I am overloading saveImage() method like this:
private void saveImage(File mediaImage) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(mediaImage);
mediaScanIntent.setData(contentUri);
getContext().sendBroadcast(mediaScanIntent);
}
This method will put the image in the desired file location and also accessible to the Gallery for other apps. This method is same as galleryAddPic() method on this link Taking Photos Simply
But In the case of picking a photo from the Gallery, I will have to create the File in the desired location and write the bytes of the picked image into that file, so the old saveImage() method will not change.
In onActivityResult method, this is how I used overloaded saveImage() method:
else if (requestCode == CAMERA) {
saveImage(imageFile);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
loadImage.setImageBitmap(bitmap);
Toast.makeText(getContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_SHORT).show();
imageTextMessage.setVisibility(View.INVISIBLE);
}

Getting content from OnActivityResult

I am doing a texttospeech project to import txt file and read its contents using storage access framework . After OnActivityResult how to get the content to string variable and pass it to next activity . I need to copy the txt file content to next activity edittext
package com.texttospeech.texttospeech;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.texttospeech.Main2Activity;
public class MainActivity extends AppCompatActivity {
private static final int READ_REQUEST_CODE = 42;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
performFileSearch();
}
});
}
private static final int EDIT_REQUEST_CODE = 42;
/**
* Fires an intent to spin up the "file chooser" UI and select an image.
*/
private void performFileSearch() {
// ACTION_OPEN_DOCUMENT is the intent to choose a file via the system's
// file browser.
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
// Filter to only show results that can be "opened", such as a
// file (as opposed to a list of contacts or timezones).
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Filter to show only text files.
intent.setType("text/plain");
startActivityForResult(intent, EDIT_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData){
if(requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK){
Uri uri = null;
if (resultData!= null){
uri = resultData.getData();
}
}
}
}
You open an InputStream for the obtained uri and then read from the stream as you would do if you had used a FileInputStream.
InputStream is = getContentResolver().openInputStream(resultData.getData());
I guess this will help you:
String text = readText(uri);
private String readText(Uri uri) {
File f = new File(uri.toString());
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
Let me know if you had any question.
Problem I ran into was that the class couldn't reccognise getContentResolver() but later I realised that I am in fragment so for that you need to pass context first :
getActivity().getContentResolver() .. or simply
context.getContentResolver()

uploading a pdf using volley but gets null file on server folder

I am uploading a pdf file using volley library in database on hostinger domain and also in folder on same hostinger domain
Here it is my xml file
<?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:paddingTop="#dimen/activity_vertical_margin"
android:background="#color/colorAccent"
tools:context="com.example.singhharpal.fileupload_apr26.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="18sp"
android:id="#+id/tvHeading"
android:text="Touch the icon below to upload file to server"
android:textColor="#fff"
android:textStyle="bold"/>
<Button
android:id="#+id/ivAttachment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CHoose"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
<TextView
android:id="#+id/tv_file_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#fff"
android:layout_marginTop="10dp"
android:gravity="center"
android:layout_below="#+id/ivAttachment"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/b_upload"
android:text="Upload"
android:textStyle="bold"
android:textSize="20sp"
android:layout_alignParentBottom="true"
android:gravity="center"
android:textColor="#fff"
android:background="#039be5"/>
My java file
package com.example.singhharpal.fileupload_apr26;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
//import com.squareup.picasso.Picasso;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Hashtable;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements view.OnClickListener
{
private Button buttonClick;
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
File file;
private Bitmap bitmap;
private int PICK_IMAGE_REQUEST = 200;
String filename;
String s1,s2;
private String UPLOAD_URL ="http://harpal-projects.16mb.com/sbbs/php/file-upload2.php";
private String KEY_IMAGE = "image";
private String KEY_NAME = "fname";
private String KEY_ROLL = "roll_no";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
Button textView = (TextView) findViewById(R.id.userName);
TextView t1 = (TextView) findViewById(R.id.textView4);
TextView t2 = (TextView) findViewById(R.id.textView5);
*/
/*// SharedPreferences sharedPreferences=getActivity().getSharedPreferences("userInfo",getActivity().MODE_PRIVATE); //my settings is file name
s1=sharedPreferences.getString("username","");
s2=sharedPreferences.getString("password","");
t1.setText(s1);
t2.setText(s2);*/
//textView.setText("Welcome User " + intent.getStringExtra(RegisterStudent.KEY_USERNAME));
buttonChoose = (Button)findViewById(R.id.ivAttachment);
//buttonClick = (Button)findViewById(R.id.clickPic);
buttonUpload = (Button)findViewById(R.id.b_upload);
//imageView = (ImageView)findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
if(v == buttonChoose)
{
showFileChooser();
}
if(v == buttonUpload)
{
uploadImage();
}
}
private void showFileChooser()
{
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"), PICK_IMAGE_REQUEST);
/*Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("image*//*;application/pdf");
intent.addCategory(Intent.CATEGORY_OPENABLE);
// special intent for Samsung file manager
Intent sIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA_MULTIPLE");
// if you want any file type, you can skip next line
sIntent.putExtra("CONTENT_TYPE", "application/pdf");
sIntent.addCategory(Intent.CATEGORY_DEFAULT);
Intent chooserIntent;
if (getPackageManager().resolveActivity(sIntent, 0) != null)
{
// it is device with samsung file manager
chooserIntent = Intent.createChooser(sIntent, "Open file");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { intent});
}
else
{
chooserIntent = Intent.createChooser(intent, "Open file");
}
startActivityForResult(chooserIntent, 100);*/
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null)
{
Uri filePath = data.getData();
Toast.makeText(MainActivity.this, ""+filePath, Toast.LENGTH_SHORT).show();
filename=filePath.getLastPathSegment();
Toast.makeText(MainActivity.this, ""+filename, Toast.LENGTH_SHORT).show();
file = new File(filePath.toString());
getStringFile(file);
}
}
public String getStringFile(File f)
{
StringBuilder sb = new StringBuilder();
try
{
FileInputStream fileInputStream = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
String line ;
while ((line = reader.readLine()) != null)
{
sb.append(line).append("\n");
reader.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
return sb.toString();
}
private void uploadImage()
{
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s)
{
//Disimissing the progress dialog
loading.dismiss();
//Showing toast message of the response
Toast.makeText(getBaseContext(), s, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(getBaseContext(), volleyError.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String doc = getStringFile(file);
//Getting Image Name
//Creating parameters
Map<String,String> params = new Hashtable<String, String>();
//Adding parameters
params.put("file", doc);
params.put("fname", filename);
//returning parameters
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(){
#Override
public int getCurrentTimeout() {
return 50000;
}
#Override
public int getCurrentRetryCount() {
return 50000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
}
);
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(getBaseContext());
//Adding request to the queue
requestQueue.add(stringRequest);
}
}
I used php server script where i added a query to insert file into my database folder and in server folder named uploads
This is my php script
<?php
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
$file = $_POST['file'];
$fname = $_POST['fname'];
$file_path = "uploads/";
$actualpath = "http://harpal-projects.16mb.com/sbbs$file_path";
$sql = "INSERT INTO files (file,fname) VALUES ('$actualpath','$fname') ";
if(mysqli_query($con,$sql))
{
file_put_contents($file_path,base64_decode($file));
echo "success";
}else{
echo "fail";
}
?>
I dont know where i am getting problme as file is going into database table and also in folder in my server but it's size is 0 i.e. it is null so it is of no use ... tell me how to modify this code.??
I tried convertFileToBase64String but it gets null file too
in activtyonresult i tried this code
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null)
{
Uri filePath = data.getData();
Toast.makeText(MainActivity.this, ""+filePath, Toast.LENGTH_SHORT).show();
filename=filePath.getLastPathSegment();
Toast.makeText(MainActivity.this, ""+filename, Toast.LENGTH_LONG).show();
file = new File(filePath.toString());
try {
FileInputStream fileInputStreamReader = new FileInputStream(file);
byte[] bytes = new byte[(int)file.length()];
fileInputStreamReader.read(bytes);
encodedBase64 = new String(Base64.encodeBase64(bytes));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// doc=getStringFile(file);
//Toast.makeText(MainActivity.this, ""+doc.length(), Toast.LENGTH_SHORT).show();
}
and i used this to upload file
params.put("file", encodedBase64);
and when i used toast to see lenght of encodedBase64 it results 0 , same for 'file','fileinputreader','bytes'
so i think it is not right or may be i am wrong..correct me
i tried this code but it gets null value....as if i didnt pick any file or the fle get lost there somewhere...
public String convertFileToBase64String(File f) throws FileNotFoundException
{
InputStream inputStream = new FileInputStream(f.getAbsolutePath());
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {while ((bytesRead = inputStream.read(buffer)) != -1)
{
baos.write(buffer, 0, bytesRead);
}
}
catch (IOException e)
{
e.printStackTrace();
}
bytes = baos.toByteArray();
encodedFile = Base64.encodeToString(bytes, Base64.DEFAULT);
return encodedFile;
}
Try this,
In java:
String encode = Base64.encodeToString(bytes, Base64.DEFAULT);
in php:
$file = $_POST['file']['name'];
//$fname = $_POST['fname']['tmp_name'];
$fname = $_POST['file']['tmp_name'];
$file_path = "uploads/";
$actualpath = "http://harpal-projects.16mb.com/sbbs/$file_path/$file";
$sql = "INSERT INTO files (file,fname) VALUES ('$actualpath','$fname') ";
if(mysqli_query($con,$sql))
{
file_put_contents(base64_decode($file), $file_path);
echo "success";
}
else{
echo "fail";
}
You cannot put a pdf file in a string. What you can do however is put a pdf file base64 encoded in a string. So do that. The php script expects that. Name your functionconvertFileToBase64String().

Invoking audio recorder and getting the resulting file

I am trying to invoke the audio recorder on Android 2.2.1 (device Samsung Galaxy POP) using the following code:
private static final int ACTIVITY_RECORD_SOUND = 1;
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivityForResult(intent, ACTIVITY_RECORD_SOUND);
This invokes the recorder successfully. In my activity result i do the following:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case ACTIVITY_RECORD_SOUND:
data.getDataString();
break;
}
}
}
After i complete the recording i press back on the audio recorder which returns the control to the onActivityResult method as expected, but my resultCode is always 0 (which is Activity.RESULT_CANCELED) and my data is null. Am i missing out on something here? Kindly help me with this. This works on the emulator but not on the device. Thanks in advance.
This works for me:
#Override protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch(requestCode) {
case Flashum.TAKE_MUSIC:
case Flashum.TAKE_VOICE:
if (resultCode == Activity.RESULT_OK)
{
Log.i(Flashum.LOG_TAG, "onActivityResult got new music");
Bundle extras = data.getExtras();
try {
Uri u = data.getData();
String imageUri;
try {
imageUri = getRealPathFromURI(u);
} catch (Exception ex) {
imageUri = u.getPath();
}
File file = new File(imageUri);
FragmentFlash fragmentFlash = (FragmentFlash)mTabsAdapter.getFragment("flash");
if (fragmentFlash != null)
fragmentFlash.gotMusic(file.getPath());
} catch (Exception ex) {
String s = ex.toString();
Log.i(Flashum.LOG_TAG, "onActivityResult " + s);
}
}
else
{
Log.i(Flashum.LOG_TAG, "onActivityResult Failed to get music");
}
break;
}
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
I finally found a workaround for my problem by using the FileObserver. I achieved it by doing the following:
package com.pravaa.audiointent;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.FileObserver;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class AudioActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
private Button sampleButton;
private FileObserver mFileObserver;
private Vector<String> audioFileNames;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
audioFileNames = new Vector<String>();
LinearLayout finalContainer = new LinearLayout(this);
sampleButton = new Button(this);
sampleButton.setOnClickListener(this);
sampleButton.setText("Start Audio Intent");
finalContainer.addView(sampleButton);
setContentView(finalContainer);
addObserver();
}
private void addObserver() {
this.mFileObserver = new FileObserver("/sdcard/Sounds/") {
#Override
public void onEvent(int event, String path) {
if (event == FileObserver.CREATE) {
if (path != null) {
int index = path.indexOf("tmp");
String tempFileName = (String) path.subSequence(0,
index - 1);
audioFileNames.add(tempFileName);
}
} else if (event == FileObserver.DELETE) {
if (path != null) {
int index = path.indexOf("tmp");
String tempFileName = (String) path.subSequence(0,
index - 1);
if (audioFileNames.contains(tempFileName)) {
audioFileNames.remove(tempFileName);
}
}
}
}
};
}
private void readFile(String fileName) {
File attachment = new File("/sdcard/Sounds/" + fileName);
if (attachment.exists()) {
FileInputStream fis;
try {
fis = new FileInputStream(attachment);
byte[] bytes = new byte[(int) attachment.length()];
try {
fis.read(bytes);
fis.close();
attachment.delete();
saveMedia("Test" + fileName, bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mFileObserver.startWatching();
}
public void saveMedia(String fileName, byte[] data) {
String imagePath = "/sdcard/sam/";
System.out.println("Inside Folder");
File file = new File(imagePath, fileName);
System.out.println("File Created");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
DataOutputStream dataOutputStream = new DataOutputStream(
fileOutputStream);
System.out.println("Writting File");
dataOutputStream.write(data, 0, data.length);
System.out.println("Finished writting File");
dataOutputStream.flush();
dataOutputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivityForResult(intent, 2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
// TODO Auto-generated method stub
if (requestCode == 2) {
if (mFileObserver != null) {
mFileObserver.stopWatching();
}
Enumeration<String> audioFileEnum = audioFileNames.elements();
while (audioFileEnum.hasMoreElements()) {
readFile((String) audioFileEnum.nextElement());
}
}
}}
i was facing the same issue.. So instead of using an intent, I used the MediaRecorder class and its associated methods like setAudioEncoder, setAudioSource, prepare, start, stop, setOutputFormat and setOutputFile..It works fine now..
I also agree with the best answer so far (voted by question-owner), but it cannot read the file as it is a different path. my suggestion is to store the filename as a member-variable and call getFilename() only once.
There is a known issue with Galaxy Android devices where result intents are null where you would expect them to contain a photo. This might also apply here. See http://kevinpotgieter.wordpress.com/2011/03/30/null-intent-passed-back-on-samsung-galaxy-tab/.
One way to solve this, is to add
intent.putExtra(MediaStore.EXTRA_OUTPUT, someFileUri);
to your intent, explicitly telling the target app where to store the resulting file.
Check out this example if you need help creating a good file Uri.

Categories

Resources