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().
Related
I have 2 activity, Tambah and Tampil activity.
I use Tambah activity to add new data (form and button submit), and after submit, it will move to Tampil activity. in Tampil activity will show the list view of data (i'm using Volley). all script works, no error. but in Tampil activity only showing old data (like before add), not showing the newest data.
here my Tambah acitivity
package com.example.arif.upload;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
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.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
import java.io.IOException;
import java.util.UUID;
public class Tambah extends AppCompatActivity implements View.OnClickListener{
//Declaring views
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editText;
//Image request code
private int PICK_IMAGE_REQUEST = 1;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
private Bitmap bitmap;
//Uri to store the image uri
private Uri filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tambah);
//Requesting storage permission
requestStoragePermission();
//Initializing views
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
editText = (EditText) findViewById(R.id.editTextName);
//Setting clicklistener
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
/*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this method
* */
public void uploadMultipart() {
//getting name for the image
String name = editText.getText().toString().trim();
//getting the actual path of the image
String path = getPath(filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Konfigurasi.url_tambah_tentor)
.addFileToUpload(path, "foto") //Adding file
.addParameter("nama", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
Intent move = new Intent(getApplicationContext(),Tampil.class);
startActivity(move);
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//method to show file chooser
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
#Override
protected 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) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//method to get the file path from uri
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
//Requesting permission
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadMultipart();
}
}
}
and here Tampil activity
package com.example.arif.upload;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Tampil extends AppCompatActivity {
ListView list_tentor;
ArrayList<String>nama;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tampil);
list_tentor = (ListView)findViewById(R.id.list_tentor);
nama = new ArrayList<String>();
list_tentor.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent pindah = new Intent(Tampil.this,Tambah.class);
pindah.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(pindah);
finish();
}
});
RequestQueue req = Volley.newRequestQueue(getApplicationContext());
StringRequest sr = new StringRequest(Request.Method.GET, Konfigurasi.url_tampil_tentor, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jo = new JSONObject(response);
JSONArray tentor = jo.getJSONArray("tentor");
for (int i = 0; i < tentor.length(); i++){
JSONObject pertentor = tentor.getJSONObject(i);
nama.add(pertentor.getString("nama"));
}
Tampiladapter ta = new Tampiladapter(getApplicationContext(),nama);
list_tentor.setAdapter(ta);
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
req.add(sr);
}
}
how can when Intent from Tambah activity to Tampil activity, the Tampil activity reload all data include newest data)?
It seems that you are not waiting until data is uploaded and redirecting to next screen.
Try this answer
Implementing ProgressDialog in Multipart Upload Request
onCompleted redirect to next screen
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
}
I have problem, that I have been searching for whole week. I'm creating app that sends photo and some data to server. The problem is that when I start activity, camera has to start but, for some devices app crashes. I cant describe the error because devices are in other cities. I have LG G3 and HUAWEI P7 on both of them works fine. I think this might be something wrong with permissions but I'm not sure.
package com.fishingtournaments.ZvejysZvejui;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.support.v4.os.EnvironmentCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.Semaphore;
public class SendImageActivity extends AppCompatActivity implements View.OnClickListener {
public static final int CAMERA_PERMISSION_REQUEST_CODE = 8675809;
TextView fish_n, fish_s, points;
public static final int REQUEST_CAPTURE = 1;
public static String path;
public String fish_name, fish_length, fish_points, colleague_id, fish_size, fish_photo, fish_id,
user_id, user_name = "";
//Declaring views
private Button buttonUpload;
private ImageView imageView;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
//Uri to store the image uri
private Uri imageUri; /*, uriSavedImage*/
private File imagesFolder, image;
private String fixedURI;
//----------------------------------//
// Storage for camera image URI components
private final static String CAPTURED_PHOTO_PATH_KEY = "mCurrentPhotoPath";
private final static String CAPTURED_PHOTO_URI_KEY = "uriSavedImage";
// Required for camera operations in order to save the image file on resume.
private String mCurrentPhotoPath = null;
private Uri uriSavedImage = null;
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
if (mCurrentPhotoPath != null) {
savedInstanceState.putString(CAPTURED_PHOTO_PATH_KEY, mCurrentPhotoPath);
}
if (uriSavedImage != null) {
savedInstanceState.putString(CAPTURED_PHOTO_URI_KEY, uriSavedImage.toString());
}
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.containsKey(CAPTURED_PHOTO_PATH_KEY)) {
mCurrentPhotoPath = savedInstanceState.getString(CAPTURED_PHOTO_PATH_KEY);
}
if (savedInstanceState.containsKey(CAPTURED_PHOTO_URI_KEY)) {
uriSavedImage = Uri.parse(savedInstanceState.getString(CAPTURED_PHOTO_URI_KEY));
}
super.onRestoreInstanceState(savedInstanceState);
}
//-++-+-+-+-+-+-+-+-+-+-+-+-+---//
#Override
protected void onCreate(Bundle savedInstanceState) {
//Requesting storage permission
//TODO INTERFACE,
//TODO CHECK PERMISSIONS
//TODO TEST ON OTHER PHONES
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
setContentView(R.layout.activity_send_image);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
buttonUpload.setOnClickListener(this);
} else {
setContentView(R.layout.activity_send_image);
if (ContextCompat.checkSelfPermission(SendImageActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
imagesFolder = new File(Environment.getExternalStorageDirectory(), "FishingTournament");
image = new File(imagesFolder, "QR_" + timeStamp + ".png");
uriSavedImage = Uri.fromFile(image);
i.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(i, REQUEST_CAPTURE);
} else {
String[] permissionRequest = {Manifest.permission.CAMERA};
ActivityCompat.requestPermissions(SendImageActivity.this, permissionRequest, CAMERA_PERMISSION_REQUEST_CODE);
}
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
buttonUpload.setOnClickListener(this);
}
}
/*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this method
* */
public void uploadMultipart() {
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", "asd") //Adding text parameter to the request
.addParameter("colleague_id", colleague_id)
.addParameter("fish_length", fish_size)
.addParameter("fish_points", fish_points)
.addParameter("fish_photo", fish_photo)
.addParameter("fish_id", fish_id)
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//handling the image chooser activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CAPTURE) {
if (data != null) {
fixedURI = String.valueOf(uriSavedImage);
fixedURI = fixedURI.replace("file://", "");
path = fixedURI;
// Bitmap bitmap = ImageUtils.getInstant().getCompressedBitmap(path);
// imageView.setImageBitmap(bitmap);
} else {
fixedURI = String.valueOf(uriSavedImage);
fixedURI = fixedURI.replace("file://", "");
path = fixedURI;
// Bitmap bitmap = ImageUtils.getInstant().getCompressedBitmap(path);
// imageView.setImageBitmap(bitmap);
}
}
}
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);
}
//Requesting permission
private void requestStorageReadPermission() {
if (ContextCompat.checkSelfPermission(SendImageActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(SendImageActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
Toast.makeText(SendImageActivity.this, "Norint siųsti nuotrauką reikalingas leidimas prie failų saugyklos", Toast.LENGTH_SHORT).show();
}
//And finally ask for the permission
ActivityCompat.requestPermissions(SendImageActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonUpload) {
uploadMultipart();
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
onBackPressed();
}
return false;
}
#Override
public void onBackPressed() {
super.onBackPressed();
final String user_name = getIntent().getStringExtra("user_name");
final String colleague_id = getIntent().getStringExtra("colleague_id");
final String user_id = getIntent().getStringExtra("user_id");
Intent intent = new Intent(SendImageActivity.this, ChooseFishActivity.class);
intent.putExtra("colleague_id", colleague_id);
intent.putExtra("user_name", user_name);
intent.putExtra("user_id", user_id);
startActivity(intent);
finish();
}
}
It might look dumb why I have if in onCreate() method, it's because in my LG G3 camera is restarting on taking photo. And thats why my onActivityResult() method looks strange.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.fishingtournaments.ZvejysZvejui">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/descicon"
android:label="Žvejys žvejui"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".LoginActivity"
android:configChanges="orientation"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ChooseFishActivity"
android:configChanges="orientation"
android:parentActivityName=".LoginActivity"
android:screenOrientation="portrait" />
<activity
android:name=".ResultActivity"
android:configChanges="orientation"
android:parentActivityName=".ChooseFishActivity"
android:screenOrientation="portrait" />
<activity
android:name=".ShowResultsActivity"
android:configChanges="orientation"
android:parentActivityName=".LoginActivity"
android:screenOrientation="portrait" />
<activity android:name=".SendImageActivity"
android:configChanges="orientation"
android:parentActivityName=".LoginActivity"
android:screenOrientation="portrait" />
</application>
</manifest>
P.S. My code might look unclean, sorry for that, I have been doing everything and testing everything to solve that problem.
BTW I'm requesting permission for storage in my LoginActivity and there I'm creating folder for photos.
LoginActivity
package com.fishingtournaments.ZvejysZvejui;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
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.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
public class LoginActivity extends AppCompatActivity {
private static final int STORAGE_PERMISSION_CODE = 123;
EditText qrCode_edit;
Button check_button;
// Button result_button;
public String colleague_id;
public String colleague_name;
public String user_id, user_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if(ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(LoginActivity.this, "Užklausa permissionų", Toast.LENGTH_SHORT).show();
if (ActivityCompat.shouldShowRequestPermissionRationale(LoginActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(LoginActivity.this, "Norint siųsti nuotrauką reikalingas leidimas prie failų saugyklos", Toast.LENGTH_SHORT).show();
}
//And finally ask for the permission
ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}else{
Toast.makeText(LoginActivity.this, "Teisės suteiktos", Toast.LENGTH_SHORT).show();
}
File direct = new File(Environment.getExternalStorageDirectory()+"/FishingTournament");
if(!direct.exists()) {
if (direct.mkdir())
Toast.makeText(LoginActivity.this, "Direktorija sukurta", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(LoginActivity.this, "Nesukurta direktorija, nes ji jau egzistuoja", Toast.LENGTH_SHORT).show();
}
// it will create two folder in your internal storage first is specifyfoldername and another one inside the mentioned folder which is nestedfoldername
qrCode_edit = (EditText) findViewById(R.id.qrCode_editText);
check_button = (Button) findViewById(R.id.check_button);
// result_button = (Button) findViewById(R.id.results);
//QR Code
final Activity activity = this;
/**
* Button for scanning QR code
*
*/
check_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
check_button.setEnabled(false);
String qrCode = qrCode_edit.getText().toString();
//QR Code
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Užveskite kamerą ant QR kodo");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
check_button.setEnabled(true);
//---
/*Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success){
Intent intent = new Intent(LoginActivity.this, ChooseFishActivity.class);
colleague_id = jsonResponse.getString("colleague_id");
colleague_name = jsonResponse.getString("colleague_name");
user_id = jsonResponse.getString("user_id");
intent.putExtra("colleague_id",colleague_id);
intent.putExtra("user_name",colleague_name);
intent.putExtra("user_id",user_id);
startActivity(intent);
// finish();
//startActivity(new Intent(LoginActivity.this, ChooseFishActivity.class));
}else{
String message = jsonResponse.getString("message");
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
*//*ats.setText(message);*//*
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(qrCode, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);*/
}
});
/**
* Button for launching ShowResultsActivity
*/
/*result_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, ShowResultsActivity.class);
startActivity(intent);
finish();
}
});*/
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null){
if(result.getContents()==null){
Toast.makeText(this, "Atšaukėte skanavimą", Toast.LENGTH_LONG).show();
}else{
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
/*If correct QR-code*/
if (success){
Intent intent = new Intent(LoginActivity.this, ChooseFishActivity.class);
colleague_id = jsonResponse.getString("colleague_id");
colleague_name = jsonResponse.getString("colleague_name");
user_id = jsonResponse.getString("user_id");
user_name = jsonResponse.getString("user_name");
intent.putExtra("colleague_id",colleague_id);
intent.putExtra("user_name",colleague_name);
intent.putExtra("user_id",user_id);
Toast.makeText(getApplicationContext(),"Sveiki, " + user_name,Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}else{
String message = jsonResponse.getString("message");
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(result.getContents(), responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
}else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
So I figured out where the problem was.
The error was exposed beyond app through ClipData.Item.getUri() . Basicly the problem was in this line i.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);. After searching for this error I found solution in this post
I'm having 4 activities other than MainActivity.
I have added results button and when the user click on that button a random activity should be opened.
Here's my MainActivity class and its XML:
package tk.crazyapps.www.volleyupload;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
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 java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;
import java.util.Random;
MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editTextName;
private Bitmap bitmap;
private int PICK_IMAGE_REQUEST = 1;
private String UPLOAD_URL ="http://crazyapps.tk/VolleyUpload/upload.php";
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
editTextName = (EditText) findViewById(R.id.editText);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
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(MainActivity.this, s , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(MainActivity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap);
//Getting Image Name
String name = editTextName.getText().toString().trim();
//Creating parameters
Map<String,String> params = new Hashtable<String, String>();
//Adding parameters
params.put(KEY_IMAGE, image);
params.put(KEY_NAME, name);
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected 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();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v) {
if(v == buttonChoose){
showFileChooser();
}
if(v == buttonUpload){
uploadImage();
}
}
Here's the XML of MainActivity:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choose Image"
android:id="#+id/buttonChoose" />
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="#+id/imageView" />
<EditText
android:id="#+id/editText"
android:hint="Enter ur Name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Upload Image"
android:id="#+id/buttonUpload" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Results"
android:id="#+id/buttonresult" />
int min = 0;
int max = 4;
Random r = new Random();
int random = r.nextInt(max - min + 1) + min;
switch (random) {
case 0:
// start activity 0
break;
case 1:
// start activity 1
break;
case 2:
// start activity 2
break;
case 3:
// start activity 3
break;
}
I am new at android as well as parse.com. I need a way in which a user can click a button to take a photo or another button to choose a photo from the gallery. Then store the image in my parse.com database so that I can manipulate it with other events in the system. So far I am able to have the user update his status and save to my parse database but I do not know how to manipulate images and ImageViews. Here is my code so far:
public class UpdateActivity extends Activity {
protected EditText mUpdateStatus;
protected Button mUpdateStatusButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
//initialization of variables
mUpdateStatus=(EditText)findViewById(R.id.updateStatusUpdate);
mUpdateStatusButton=(Button)findViewById(R.id.updateButtonUpdate);
//code update button click event
mUpdateStatusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Get current user
ParseUser currentUser=ParseUser.getCurrentUser();//Identifies current user
String currentUserUsername=currentUser.getUsername();//stores username in variable
//Create new variable to store strings
String newStatus=mUpdateStatus.getText().toString();
//Event for an empty status
if (newStatus.isEmpty())
{AlertDialog.Builder builder=new AlertDialog.Builder(UpdateActivity.this);
builder.setMessage("STATUS SHOULD NOT BE EMPTY.");
builder.setTitle("OOPS!");
builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog=builder.create();
dialog.show();}
else{
//Save the status in Parse.com
ParseObject statusObject = new ParseObject("Status");//Create a new parse class
statusObject.put("newStatus",newStatus);//Creates a new attribute and adds value from newStatus
statusObject.put("User",currentUserUsername);//Stores username in new parse class
//Save data and initiate callback method
statusObject.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e==null)
{//Event for a Successful storage
Toast.makeText(UpdateActivity.this,getString(R.string.succssfulUpdate),Toast.LENGTH_LONG).show();
//Take user back to profile
Intent main = new Intent(UpdateActivity.this, ProfileActivity.class);
UpdateActivity.this.startActivity(main);
}
else
{//Event for an Unsuccessful storage
AlertDialog.Builder builder=new AlertDialog.Builder(UpdateActivity.this);
builder.setMessage(e.getMessage());
builder.setTitle("SORRY!");
builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog=builder.create();
dialog.show();
}
}
});}
}
});
}
#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_update, 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
switch(id) {
case R.id.logoutUpdateMenu:
{//logout the user
ParseUser.logOut();
//Take user back to login
Intent intent = new Intent(UpdateActivity.this, LoginActivity.class);
UpdateActivity.this.startActivity(intent);
UpdateActivity.this.finish();
Toast.makeText(getApplicationContext(), getString(R.string.logout_text), Toast.LENGTH_LONG).show();
break;}
}
return super.onOptionsItemSelected(item);
}
}
A complete example image upload for Parse.com with option to take a photo gallery or the camera.
Activity.class
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
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.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.SaveCallback;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends ActionBarActivity {
private static int RESULT_LOAD_CAMERA_IMAGE = 2;
private static int RESULT_LOAD_GALLERY_IMAGE = 1;
private String mCurrentPhotoPath;
private ImageView imgPhoto;
private Button btnUploadImage;
private File cameraImageFile;
private TextView mTextView;
#Override
public void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == RESULT_LOAD_GALLERY_IMAGE && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mCurrentPhotoPath = cursor.getString(columnIndex);
cursor.close();
} else if (requestCode == RESULT_LOAD_CAMERA_IMAGE) {
mCurrentPhotoPath = cameraImageFile.getAbsolutePath();
}
File image = new File(mCurrentPhotoPath);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions);
imgPhoto.setImageBitmap(bitmap);
}
}
private File createImageFile () throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File folder = new File(storageDir.getAbsolutePath() + "/PlayIOFolder");
if (!folder.exists()) {
folder.mkdir();
}
cameraImageFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
folder /* directory */
);
return cameraImageFile;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgPhoto = (ImageView)findViewById(R.id.imgPhoto);
imgPhoto.setOnClickListener(chooseImageListener);
btnUploadImage = (Button)findViewById(R.id.btnUpload);
btnUploadImage.setOnClickListener(uploadListener);
}
View.OnClickListener chooseImageListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogChooseFrom();
}
};
View.OnClickListener uploadListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
byte[] image = null;
try {
image = readInFile(mCurrentPhotoPath);
}
catch(Exception e) {
e.printStackTrace();
}
// Create the ParseFile
ParseFile file = new ParseFile("picturePath", image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a New Class called "ImageUpload" in Parse
ParseObject imgupload = new ParseObject("Image");
// Create a column named "ImageName" and set the string
imgupload.put("Image", "picturePath");
// Create a column named "ImageFile" and insert the image
imgupload.put("ImageFile", file);
// Create the class and the columns
imgupload.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Toast.makeText(getBaseContext(), "Done!", Toast.LENGTH_LONG).show();
}
});
}
};
private void dialogChooseFrom(){
final CharSequence[] items={"From Gallery","From Camera"};
AlertDialog.Builder chooseDialog =new AlertDialog.Builder(this);
chooseDialog.setTitle("Pick your choice").setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(items[which].equals("From Gallery")){
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_GALLERY_IMAGE);
} else {
try {
File photoFile = createImageFile();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, RESULT_LOAD_CAMERA_IMAGE);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
chooseDialog.show();
}
private byte[] readInFile(String path) throws IOException {
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
}
Layout
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<RelativeLayout
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#ccc">
<ImageView
android:id="#+id/imgPhoto"
android:layout_width="200dp"
android:layout_height="200dp"
/>
<TextView
android:text="Choose a image"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:layout_margin="2dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
<Button
android:id="#+id/btnUpload"
android:text="Upload Photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Android Manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I have no experience with parse.com but If you are able to put images(bit map) into ParseObject, you just need to call take photo or pick photo action using intent and startActivityForResult. Example:
public void onClickTakePhoto(View view) {
dispatchTakePictureIntent();
}
public void onClickPickPhoto(View view) {
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, REQUEST_SELECT_IMAGE);
}
//Code from Android documentation
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == REQUEST_IMAGE_CAPTURE || requestCode == REQUEST_SELECT_IMAGE) && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
ParseObject statusObject = new ParseObject("Status");
//I think parse has similar support If not this
statusObject.put("profile_photo",imageBitmap);
statusObject.saveInBackground( new Callback(){...});
}
}
You need to convert your Bitmap or any Object into byte[].
And then use following code.
byte[] image= your byte array
final ParseFile files = new ParseFile(image);
files.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException exception) {
if (exception == null) {
ParseUser.getCurrentUser().put("<parse-column-name>", files);
ParseUser.getCurrentUser().saveInBackground();
}
}
});
Hope this helps.
This is how you can upload a file to a Parse server (Back4App):
ByteArrayOutputStream bos = new ByteArrayOutputStream();
newProfileImageBitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bitmapData = bos.toByteArray();
ParseFile newImageFile = new ParseFile(bitmapData);
currentUser.put("userPicture", newImageFile);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e == null) {
// Image has been uploaded
} else {
// An error has happened when upoading
}
}
});