Can't send image attachment by email intent - android

I have tried to send image by attachment in email intent.
I select gmail app, it seems file is attached, but when i click on send on gmail app it says:
Unfortunately, Gmail has stopped.
Please help me what is the problem and how can i fix it?
AndroidManifest.xml:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
MyActivity.java:
public class MyActivity extends Activity {
private static final int SELECT_PICTURE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 2;
private String selectedImagePath;
TextView uritv=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
uritv = (TextView) findViewById(R.id.uritxt);
Button send = (Button) findViewById(R.id.sendBtn);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (uritv.getText().toString().equals("URI")) {
Toast.makeText(getApplicationContext(),"Please choose an image first!",Toast.LENGTH_SHORT).show();
} else {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("image/*");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"myemail#myemail.com"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Test Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "From My App");
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(uritv.getText().toString()));
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
}
}
});
Button galbtn = (Button) findViewById(R.id.galBtn);
galbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
Button cambtn = (Button) findViewById(R.id.camBtn);
cambtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE || requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
uritv.setText(selectedImagePath.toString());
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}

It requires Internet permissions, add this permission in manifest file
<uses-permission android:name="android.permission.INTERNET"/>

yes the problem is with the URI you build to get the file path. you are taking the raw file path which is not the case with the URI. it should be like below
content://media/external/images/media
Please check your path and test that again

I done some alteration and i can send the Mail successfully.. Since you are using Gmail use a GmailSender Class. Like this
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import android.net.Uri;
public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
String ContentType = "";
static {
Security.addProvider(new JSSEProvider());
}
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body,
String sender, String recipients, List<Uri> uriList)
throws Exception {
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
recipients));
message.setSubject(subject);
// 3) create MimeBodyPart object and set your message content
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(body);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
for (int i = 0; i < uriList.size(); i++) {
// 4) create new MimeBodyPart object and set DataHandler object
// to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = uriList
.get(i)
.getPath()
.substring(
uriList.get(i).getPath().lastIndexOf("/") + 1,
uriList.get(i).getPath().length());// change
// accordingly
System.out.println("filename " + filename);
DataSource source = new FileDataSource(uriList.get(i).getPath());
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
// 5) create Multipart object and add MimeBodyPart objects to
// this object
multipart.addBodyPart(messageBodyPart2);
}
// 6) set the multiplart object to the message object
message.setContent(multipart);
// 7) send message
Transport.send(message);
System.out.println("message sent....");
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
}
And it is always best to keep your mail sending in a Async Task or Thread. And call this in your send Button.
class SaveAsyncTask extends AsyncTask<Void, Integer, Boolean> {
private ProgressDialog progressDialogue;
private Boolean status = false;
#Override
protected Boolean doInBackground(Void... arg0) {
try {
ArrayList<Uri> uList = new ArrayList<Uri>();
u.add(Uri.parse(uritv.getText().toString()));
try {
GMailSender sender = new GMailSender("<Sender Mail>",
"<Sender Password>");
Log.d("TAG: ", "Mail SENT");
sender.sendMail("Subject Text", "Body Text", "<Sender Mail>", "<Recipient Mail>", uList);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return status;
} catch (Exception e) {
e.printStackTrace();
return Boolean.FALSE;
}
}
protected void onPreExecute() {
progressDialogue = ProgressDialog.show(MainActivity.this,
"Sending Mail...",
"Please Wait..", true,
false);
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Boolean result) {
// result is the value returned from doInBackground
progressDialogue.dismiss();
}
}

Related

How to add a picture from local storage to update Firebase user's photo profile using .setPhotoUri in Android?

I have an error while updating user's photo profile in Firebase. I want to upload user's local photo to Firebase user's profile. This is my activity.
package naufal.com.tugasakhir;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.bumptech.glide.util.Util;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import java.text.ParseException;
public class EditProfile extends AppCompatActivity {
private EditText mUsername;
private Button mUpdateProfileBtn;
private ImageButton mImageBtn;
FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
private static final int GALLERY_REQUEST = 1;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
private Uri imageUri2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
mUsername = (EditText) findViewById(R.id.userName);
mUpdateProfileBtn = (Button) findViewById(R.id.updateProfileBtn);
mImageBtn = (ImageButton) findViewById(R.id.imageField);
String username = user.getDisplayName();
mUsername.setText(username);
mUpdateProfileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//updating user's profile data
String nameUser = mUsername.getText().toString();
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setPhotoUri(Uri.parse(imageUri2))
.setDisplayName(nameUser)
.build();
if(TextUtils.isEmpty(nameUser)){
mUsername.setError("Enter a username");
}
if(imageUri2 == null){
Toast.makeText(EditProfile.this, "Error updating image",
Toast.LENGTH_SHORT).show();
}
//if the field is not null, process continue to update profile
else {
mUser.updateProfile(profileUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) { //success on updating user profile
Toast.makeText(EditProfile.this, "Update Profile Succedeed",
Toast.LENGTH_SHORT).show();
startActivity(new Intent(EditProfile.this, HomePage.class));
} else { //failed on updating user profile
Toast.makeText(EditProfile.this, "Update Profile Failed",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
//setting image for user
mImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
Uri imageUri = data.getData();
mImageBtn.setImageURI(imageUri);
imageUri2 = imageUri;
} else {
Toast.makeText(EditProfile.this, "Failed showing image",
Toast.LENGTH_SHORT).show();
}
}
}
This is how I get the user's profile from Firebase:
String email = user.getEmail();
String username = user.getDisplayName();
Uri uriImage = user.getPhotoUrl();
mUserName.setText(username);
mUserStat.setText(email);
mUriImageProfile.setImageURI(uriImage);
Thanks for the response.
You need to get this image from your device, put the file in firebase and then use it as a link
You can check my github to see it working https://github.com/chrystianmelo/appmodule
The code
**PROFILE_SERVICES**
public void putFile(Bitmap bitmap){
FirebaseStorage storage = FirebaseStorage.getInstance();
final StorageReference storageRef = storage.getReference();
final StorageReference mountainsRef = storageRef.child("images/"+getUID()+".jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mountainsRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.i("chrys", "Img not set");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mountainsRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onSuccess(Uri uri) {
setProfilePic(uri);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.i("chrys", "Img set but whereeee");
// Handle any errors
}
});
}
});
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void setProfilePic(Uri uri){
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setPhotoUri(uri)
.build();
user.updateProfile(profileUpdates);
}
**PROFILE_ACTIVITY**
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_IMAGE) {
Bitmap bitmap;
try {
ProfileServices services = new ProfileServices();
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(Objects.requireNonNull(data.getData())));
services.putFile(bitmap);
Log.i("chrys", "GET FROM LOCAL.: OK");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("chrys", "GET FROM LOCAL.: RUIM");
}
}
}
}
#SuppressLint("IntentReset")
public void getImg(){
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
#SuppressLint("IntentReset") Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
startActivityForResult(chooserIntent, PICK_IMAGE);
}
private static class DownLoadImageTask extends AsyncTask<String,Void,Bitmap> {
#SuppressLint("StaticFieldLeak")
ImageView imageView;
DownLoadImageTask(ImageView imageView){
this.imageView = imageView;
}
/*
doInBackground(Params... params)
Override this method to perform a computation on a background thread.
*/
protected Bitmap doInBackground(String...urls){
String urlOfImage = urls[0];
Bitmap logo = null;
try{
InputStream is = new URL(urlOfImage).openStream();
/*
decodeStream(InputStream is)
Decode an input stream into a bitmap.
*/
logo = BitmapFactory.decodeStream(is);
}catch(Exception e){ // Catch the download exception
e.printStackTrace();
}
return logo;
}
/*
onPostExecute(Result result)
Runs on the UI thread after doInBackground(Params...).
*/
protected void onPostExecute(Bitmap result){
imageView.setImageBitmap(result);
}
}
}
<!-- begin snippet: js hide: false console: true babel: false -->

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().

Parse.com & Android: How do I save Images to my parse database so that i can use them as a profile picture

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

Automatically close application when i call intent.createChooser to send mail?

In my android application having one button to send mail, When I click that send button using startActivity(Intent.createChooser(emailIntent, "Send Mail...")); this line Gmail will open and then I click send mail. Mail will sent successfully at the same time my application get closed why ? I need to stay in that same page ?
try
{
String extpath=Environment.getExternalStorageDirectory() +"/NewFolder/DBName";
File pathp=new File(extpath);
Log.d("New Path", pathp.toString());
long fileSize = pathp.length();
if(fileSize > 0)
{
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
String address = "mailid#yourmail.com";
String subject = "Database";
String emailtext = "Please check the attached database and save it";
emailIntent.setType("application/octet-stream");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { address });
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + pathp));
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailtext);
startActivity(Intent.createChooser(emailIntent, "Send Mail..."));
}
else
{
Log.d("Error", "Attachment didn't attach ");
}
}
catch (Throwable t)
{
Log.d("Error on sending mail", t.toString());
}
When i run this code mail sent and then application will get close. I don't want to close application. Help me thanks in advance.
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
Button button;
Session session;
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SendMailBySite bySite=new SendMailBySite();
bySite.execute();
}
class SendMailBySite extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog=new ProgressDialog(MainActivity.this);
dialog.setMessage("Sending mail.....");
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
final String user="XXXXXXXX#gmail.com";//change accordingly
final String password="XXXXXXX";//change accordingly
String to="toXXXXXXXX#gmail.com";//change accordingly
//Get the session object
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password);
}
});
//Compose the message
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Mobiappsdevelper");
message.setText("This is simple program of sending email using JavaMail API");
//send the message
Transport.send(message);
} catch (MessagingException e) {e.printStackTrace();}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
Toast.makeText(getApplicationContext(), "message sent successfully...", 3000).show();
}
}
}
You Can Use This Code:
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"recipient#example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT , "body of email");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MyActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}

how to upload file at google drive in android when i implement throght it gallery

i am working on google drive and try to intrgate in my app.lots of thing i have done.
first i craete SH1 key and then enable the drive api and then genrate the APP key.now i
have implement this link but when i pick the image from gallery it redirect back on this activity and i print the path of image it gives correct path and doesn't uploading.
what i do now??please anybody help me i m struck here what i do now cannot understand.
https://developers.google.com/drive/quickstart-android#step_4_set_up_the_sample
import java.io.IOException;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
public class MainActivity extends Activity{
private static final int REQUEST_ACCOUNT_PICKER = 1;
private static final int SELECT_PICTURE = 3;
private static final int REQUEST_AUTHORIZATION = 2;
private static Drive service;
private GoogleAccountCredential credential;
private static Uri selectedImageUri;
private String selectedImagePath;
private ImageView img;
private TextView tv;
Intent pictureintent;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// img = (ImageView)findViewById(R.id.ImageView01);
((Button) findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
pictureintent = new Intent();
pictureintent.setType("image/jpeg");
pictureintent.setAction(Intent.ACTION_GET_CONTENT);
pictureintent.putExtra(MediaStore.EXTRA_OUTPUT, selectedImageUri);
startActivityForResult(pictureintent, SELECT_PICTURE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode){
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null && data.getExtras() != null) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
credential.setSelectedAccountName(accountName);
service = getDriveService(credential);
saveFileToDrive();
}
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
saveFileToDrive();
} else {
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
case SELECT_PICTURE:
if (resultCode == Activity.RESULT_OK) {
selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
// tv = (TextView) findViewById(R.id.text1);
//tv.setText("File Path: " + selectedImagePath);
showToast("File Path: " + selectedImagePath);
System.out.println("Image Path : " + selectedImagePath);
//img.setImageURI(selectedImageUri);
startpictureIntent();
}
}
}
private Drive getDriveService(GoogleAccountCredential credential) {
return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential)
.build();
}
public void startpictureIntent(){
credential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE);
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
private void saveFileToDrive() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
// File's binary content
java.io.File fileContent = new java.io.File(selectedImageUri.getPath());
FileContent mediaContent = new FileContent("image/jpeg", fileContent);
// File's metadata.
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType("image/jpeg");
File file = service.files().insert(body, mediaContent).execute();
if(file != null) {
showToast("Photo uploaded: " + file.getTitle());
}
}catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_LONG).show();
}
});
}
}
I too use almost the same code for uploading a pdf file, but it is working for me,
try
{
FileContent mediaContent = new FileContent("application/pdf",pdfFile);
com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
body.setTitle(filename);
body.setMimeType("application/pdf");
com.google.api.services.drive.model.File file = servicer.files().insert(body,mediaContent).execute();
if (file != null)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast toast = Toast.makeText(getApplicationContext(), "File exported successfully", 2000);
toast.setGravity(Gravity.TOP|Gravity.CENTER, 0, 30);
toast.show();
}
}
);
}
}
catch (UserRecoverableAuthIOException e)
{
startActivityForResult(e.getIntent(),REQUEST_AUTHORIZATION);
}
catch (IOException e)
{
e.printStackTrace();
}

Categories

Resources