Sending image from Android to PHP - android

I have tried 3 diffrent methods for sending a image from my Android to PHP.
All three gives the message "Missing inp_image name". I am thinking that I maybe am not sending the image as an image, but rather as some text ?
I am using this http request class in Android: https://github.com/kevinsawicki/http-request
Method 1 with encoding it to base64:
//String selectedFilePath = FilePath.getPath(context, imageUri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bm = BitmapFactory.decodeFile(destImage,options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,40,baos);
byte[] byteImage_photo = baos.toByteArray(); // bitmap object
//generate base64 string of image
String encodedImage = Base64.encodeToString(byteImage_photo,Base64.DEFAULT);
// Send image
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", encodedImage);
stringResponse = request.body();
Method 2 - sending a input stream of image
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", in); // sending input stream
stringResponse = request.body();
Method 3 - sending file:
String sourceFilename= FilePath.getPath(context, imageUri);
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", new File(sourceFilename)); // sending input stream
stringResponse = request.body();
Android Mainifest:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
MainActivity:
package com.nettport.imageupload.imageupload;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
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.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Check permission */
checkPermissionRead();
checkPermissionWrite();
/* Button listener */
buttonListener();
} // onCreate
private void checkPermissionRead(){
int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;
if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
} // checkPermissionRead
private void checkPermissionWrite(){
int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
} // checkPermissionRead
public void buttonListener() {
// Image button listener
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadImage);
buttonLoadImage.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
// Load gallery
// User can select images and upload them
// Result will be in onActivityResult
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);//one can be replaced with any action code
}
});
// Camera
Button buttonLoadCamera = (Button) findViewById(R.id.buttonLoadCamera);
buttonLoadCamera.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
// Load camera
// Result will be in onActivityResult
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);//zero can be replaced with any action code
}
});
} // buttonListener
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
// Set image
ImageView imageViewImage = (ImageView)findViewById(R.id.imageViewImage);
imageViewImage.setImageURI(selectedImageUri);
// Save image
String destinationFilename = savefile(selectedImageUri);
try {
InputStream in = getContentResolver().openInputStream(selectedImageUri);
TextView textViewDynamicText = (TextView) findViewById(R.id.textViewDynamicText); // Dynamic text
String apiURL = "https://xxxxxx.com/xxxxxx/image_upload.php";
UploadImage task = new UploadImage(this, apiURL, in, selectedImageUri, destinationFilename, textViewDynamicText, new UploadImage.TaskListener() {
#Override
public void onFinished(String result) {
// Do Something after the task has finished
imageUploadResult();
}
});
task.execute();
//in.close();
}
catch (java.io.FileNotFoundException e) {
Toast.makeText(this, "MainAcrivity java.io.FileNotFoundException: " + e.toString(), Toast.LENGTH_LONG).show();
}
catch (java.io.IOException e) {
Toast.makeText(this, "MainAcrivity java.io.IOException: " + e.toString(), Toast.LENGTH_LONG).show();
}
} // RESULT_OK
} // onActivityResult
public void imageUploadResult(){
// Dynamic text
TextView textViewDynamicText = (TextView)findViewById(R.id.textViewDynamicText);
Toast.makeText(this, textViewDynamicText.getText().toString(), Toast.LENGTH_SHORT).show();
} // imageUploadResult
public String savefile(Uri sourceuri) {
String sourceFilename= FilePath.getPath(this, sourceuri);
String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Upload";
String destinationFilename = destinationPath+"/upload_me.png";
// Make dir
File folder = new File(destinationPath);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
} else {
Toast.makeText(this, "Dir failed", Toast.LENGTH_LONG).show();
}
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(sourceFilename));
bos = new BufferedOutputStream(new FileOutputStream(destinationFilename, false));
byte[] buf = new byte[1024];
bis.read(buf);
do {
bos.write(buf);
} while(bis.read(buf) != -1);
// Toast.makeText(this, "Saved to " + destinationFilename, Toast.LENGTH_LONG).show();
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "savefile#1: " + e.toString() + "\nFrom: " + sourceFilename, Toast.LENGTH_LONG).show();
}
finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "savefile#2: " + e.toString(), Toast.LENGTH_LONG).show();
}
}
return destinationFilename;
}
}
UploadImage class:
package com.nettport.imageupload.imageupload;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Base64;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by bruker on 08.08.2017.
* Updated
*/
public class UploadImage extends AsyncTask<String, Void, String> {
/* Class variables */
private Context context; // Holder (this)
private String apiUrl; // URL for image upload form, example http://website.com/image_upload.php
private TextView dynamicText;
private InputStream in;
private Uri imageUri;
private String destImage;
private final UploadImage.TaskListener taskListener; // This is the reference to the associated listener
public interface TaskListener {
public void onFinished(String result);
}
/*- Constructor GET, SEND --------------------------------------------------------------- */
public UploadImage(Context ctx, String applicationPIUrl, InputStream input, Uri selectedImageUri, String destinationFilename, TextView textViewDynamicText, UploadImage.TaskListener listener) {
context = ctx;
apiUrl = applicationPIUrl;
in = input;
imageUri = selectedImageUri;
destImage = destinationFilename;
dynamicText = textViewDynamicText;
this.taskListener = listener; // The listener reference is passed in through the constructor
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dynamicText.setText(dynamicText.getText().toString() + "\n" + "Loading...");
}
#Override
protected String doInBackground(String... params) {
// Run methods
String stringResponse ="";
try {
try{
// Method 1 - Base 64
/*
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bm = BitmapFactory.decodeFile(destImage,options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,40,baos);
byte[] byteImage_photo = baos.toByteArray(); // bitmap object
//generate base64 string of image
String encodedImage = Base64.encodeToString(byteImage_photo,Base64.DEFAULT);
// Send image
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", encodedImage);
stringResponse = request.body();
*/
// Method 2 - Input stream
/*
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", in); // sending input stream
stringResponse = request.body();
*/
// Method 3 - File
String sourceFilename= FilePath.getPath(context, imageUri);
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", new File(sourceFilename)); // sending input stream
stringResponse = request.body();
}
catch (Exception e){
return e.toString();
}
}
catch(Exception e){
return e.toString();
}
return stringResponse;
}
#Override
protected void onPostExecute(String result) {
// Set text view with result string
if(dynamicText == null){
Toast.makeText(context, "NULL", Toast.LENGTH_SHORT).show();
}
else {
dynamicText.setText(dynamicText.getText().toString() + "\n" + result);
}
// In onPostExecute we check if the listener is valid
if(this.taskListener != null) {
// And if it is we call the callback function on it.
this.taskListener.onFinished(result);
}
}
#Override
protected void onProgressUpdate(Void... values) {}
}
PHP Script:
<?php
/**
*
* File: image_upload.php
* Date 13:05 04.08.2017
* Version 1
* Copyright (c) 2017 S. A. Ditlefsen
* License: http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/
/*- Get extention ---------------------------------------------------------------------- */
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
/*- Path -------------------------------------------------------------------------------- */
if(!(is_dir("_images"))){
mkdir("_images");
}
/*- Script start ------------------------------------------------------------------------ */
$name = stripslashes($_FILES['inp_image']['name']);
if($name){
$extension = getExtension($name);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
echo"unknown_file_extension";
}
else{
$date_time = date("Y-m-d_h-i-s");
$new_name = $date_time . ".png";
$new_path = "_images/";
$uploaded_file = $new_path . $new_name;
// Upload file
if (move_uploaded_file($_FILES['inp_image']['tmp_name'], $uploaded_file)) {
// Get image size
$file_size = filesize($uploaded_file);
// Check with and height
list($width,$height) = getimagesize($uploaded_file);
if($width == "" OR $height == ""){
echo"getimagesize_failed";
}
else{
// Resize to $settings_image_width
$newwidth=1000;
$newheight=($height/$width)*$newwidth; // 667
$tmp=imagecreatetruecolor($newwidth,$newheight);
if($extension=="jpg" || $extension=="jpeg" ){
$src = imagecreatefromjpeg($uploaded_file);
}
else if($extension=="png"){
$src = imagecreatefrompng($uploaded_file);
}
else{
$src = imagecreatefromgif($uploaded_file);
}
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight, $width,$height);
imagepng($tmp,$uploaded_file);
imagedestroy($tmp);
echo"$new_name";
} // width height
} // move_uploaded_file
else{
switch ($_FILES['inp_food_image_b']['error']) {
case UPLOAD_ERR_OK:
echo"image_to_big";
break;
case UPLOAD_ERR_NO_FILE:
echo"no_file_uploaded";
break;
case UPLOAD_ERR_INI_SIZE:
echo"to_big_size_in_configuration";
break;
case UPLOAD_ERR_FORM_SIZE:
echo"to_big_size_in_form";
break;
default:
echo"unknown_error";
break;
}
}
} // extention
} // name
else{
echo"Missing inp_image name";
}
?>

try this and it is working for me ,
String imgstring = getStringImage(bitmap)
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;
}
volley
public void addimage() {
String link = CommonVariables.SERVER_IP + "/uploadimage.php";
StringRequest request = new StringRequest(Request.Method.POST, link, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError != null && volleyError.getMessage() != null) {
Toast.makeText(getContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getContext(), "Something went wrong", Toast.LENGTH_LONG).show();
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("imagename", "yourimagename");
params.put("imagecode", imageString);
return params;
}
};
RetryPolicy mRetryPolicy = new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(mRetryPolicy);
queue.add(request);
}
php
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$imgcode = $_POST['imagecode'];
$imagename = $_POST['imagename'];
require_once('dbconnect.php');
// this is ths path where your image is stored in the file in server
$path = "images/$imagename.jpg";
$sql = "INSERT INTO productlist(proimagename)
VALUES ('$imagename')";
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($imgcode));
echo "1";
}
mysqli_close($con);
}else{
echo "0";
}

Related

Error when trying to retrieve the user location using Android Studio

I want to create an application to get the user location info in coordinates using Locaion manager. The problem is my application always has stopped when it runs and always get java.lang.NullPointerException
this is my Main ACtivity
package com.ionlab.project.volley;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.ionlab.project.volley.app.AppController;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements LocationListener {
//location
private TextView textView;
private LocationManager locationManager;
//waktu
TextView textviewDate;
Button buttonChoose;
FloatingActionButton buttonUpload;
Toolbar toolbar;
ImageView imageView;
EditText txt_name;
EditText txt_item;
Bitmap bitmap, decoded;
int success;
int PICK_IMAGE_REQUEST = 1;
int bitmap_size = 60; // range 1 - 100
private static final String TAG = MainActivity.class.getSimpleName();
/* 10.0.2.2 adalah IP Address localhost Emulator Android Studio. Ganti IP Address tersebut dengan
IP Address Laptop jika di RUN di HP/Genymotion. HP/Genymotion dan Laptop harus 1 jaringan! */
private String UPLOAD_URL = "http://192.168.1.4/android/upload_image/upload.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
private String KEY_ITEM = "item";
private String KEY_LOKASI = "lokasi";
private String KEY_WAKTU = "waktu";
String tag_json_obj = "json_obj_req";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (FloatingActionButton) findViewById(R.id.buttonUpload);
txt_name = (EditText) findViewById(R.id.editText);
txt_item = (EditText) findViewById(R.id.editItem);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
buttonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadImage();
}
});
//Calendar
Calendar calendar = Calendar.getInstance();
String currenDate = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.getTime());
textviewDate = findViewById(R.id.text_view_date);
textviewDate.setText(currenDate);
//textloc
textView = (TextView) findViewById(R.id.id_textview);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
onLocationChanged(location);
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, bitmap_size, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage() {
//menampilkan 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 response) {
Log.e(TAG, "Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt(TAG_SUCCESS);
if (success == 1) {
Log.e("v Add", jObj.toString());
Toast.makeText(MainActivity.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
kosong();
} else {
Toast.makeText(MainActivity.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
//menghilangkan progress dialog
loading.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//menghilangkan progress dialog
loading.dismiss();
//menampilkan toast
Toast.makeText(MainActivity.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
Log.e(TAG, error.getMessage().toString());
}
}) {
#Override
protected Map<String, String> getParams() {
//membuat parameters
Map<String, String> params = new HashMap<String, String>();
//menambah parameter yang di kirim ke web servis
params.put(KEY_IMAGE, getStringImage(decoded));
params.put(KEY_NAME, txt_name.getText().toString().trim());
params.put(KEY_ITEM, txt_item.getText().toString().trim());
params.put(KEY_WAKTU, textviewDate.getText().toString().trim());
params.put(KEY_LOKASI, textView.getText().toString().trim());
//kembali ke parameters
Log.e(TAG, "" + params);
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest, tag_json_obj);
}
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 {
//mengambil fambar dari Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
// 512 adalah resolusi tertinggi setelah image di resize, bisa di ganti.
setToImageView(getResizedBitmap(bitmap, 512));
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void kosong() {
imageView.setImageResource(0);
txt_name.setText(null);
txt_item.setText(null);
}
private void setToImageView(Bitmap bmp) {
//compress image
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, bitmap_size, bytes);
decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(bytes.toByteArray()));
//menampilkan gambar yang dipilih dari camera/gallery ke ImageView
imageView.setImageBitmap(decoded);
}
// fungsi resize image
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
#Override
public void onLocationChanged(Location location) {
double longitude = location.getLongitude();
double latitude = location.getLatitude();
textView.setText("Longitude:" + longitude + "\n" + "Latitude:" + latitude);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
i also make sure that my android manifest is correct
I have Spent Day and Night trying to solve this problem, Browsed through numerous pages on the topic, Tried different codes of my own.
And it still happens. I am a beginner in Android. And please, please do help me. Is there no possible way to solve my problem?
this is my logcat
LogCat
Firstly, you should include your logcat in text form as a part of your question!
However, from what I can read from your screenshot the issue is in the onLocationChanged() method. Perform a check on "location" to see if it is null before trying to read it.
#Override
public void onLocationChanged(Location location) {
if(location != null){
double longitude = location.getLongitude();
double latitude = location.getLatitude();
textView.setText("Longitude:" + longitude + "\n" + "Latitude:" + latitude);
}
else{
Log.e(TAG, "onLocationChanged -- location is null!");
}
}
Note:
Just in case you didn't know the "TAG" is generally added to the beginning of most Android class like this:
public class MainActivity extends AppCompatActivity implements LocationListener {
private static final String TAG = MainActivity.class.getSimpleName();
Why MainActivity.class.getSimpleName() instead of just "MainActivity"? Because if you ever refactor your code, then the name will automatically be changed.
EDIT:
Have you added the necessary permissions in your manifest file?
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:name="android.hardware.location.gps"/>

how to multiple image upload using intent service with update UI from service

I am android developer .I have face issue ANR when multiple image send in background using intent service.I have call service on Resume() method.I have update UI when step by step image upload finish .My all code in service .But i don't understand why my UI hang.I have created ResultReceiver class for Update UI. Please tell me what is wrong i am doing.
public class UploadImageService extends IntentService {
public static final int STATUS_RUNNING = 0;
public static final int STATUS_FINISHED = 1;
public static final int STATUS_ERROR = 2;
private static final String TAG = "UploadImageService";
public static String SHOW_MSG = "showMsg";
public static String SET_IN_ADAPTER = "setData";
public static String UPLOAD_IMAGE = "uploadImage";
public static String RESULT = "result";
private String threadType, toUser, chatThreadId, gcmRegistrationId, openCloseChatWindowType, recipientName, threadTopicName, attachmentID, attachmentType, currentChunks, originalBase64Img, dateTime, classType, loginUserId;
// Declare Web services variable
private MultipartEntity multipartEntityBuilder;
Database database;
Bundle bundle;
ResultReceiver receiver;
public UploadImageService() {
super(UploadImageService.class.getName());
}
#Override
protected void onHandleIntent(Intent intent) {
//initialize database
database = new Database(UploadImageService.this, Database.DATABASE_NAME, null, Database.DATABASE_VERSION);
Log.d(TAG, "Service Started!");
receiver = intent.getParcelableExtra("receiver");
try {
bundle = new Bundle();
/* Update UI: upload Service is Running */
//receiver.send(STATUS_RUNNING, Bundle.EMPTY);
try {
new UploadThumbImageAsync().execute();
} catch (Exception e) {
e.printStackTrace();
bundle.putString(Intent.EXTRA_TEXT, e.toString());
receiver.send(STATUS_ERROR, bundle);
}
/* new Thread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
while(true)
{
try {
new UploadThumbImageAsync().execute();
} catch (Exception e) {
e.printStackTrace();
bundle.putString(Intent.EXTRA_TEXT, e.toString());
receiver.send(STATUS_ERROR, bundle);
}
}
}
}).start();*/
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG, "Service Stopping!");
//this.stopSelf();
}
private class UploadThumbImageAsync extends AsyncTask<String, Void, String> {
/*this method is use for initializing dialog(ProgressDialog,CustomDialog) and showing*/
String toUser, comTypeId, threadType, chatThreadId, threadTopicName, chatAttachmentType, chatMessage, thumbBase64AttachmentPath /*original_image*/, loginUserName, recipientName, originalBase64Image, originalFilePath;
#Override
protected void onPreExecute() {
super.onPreExecute();
//showProgressDialog();
}
/*starts the loading of the data in background in doInBackground() method */
#Override
protected String doInBackground(String... params) {
try {
toUser = params[0];
comTypeId = params[1];
threadType = params[2];
chatThreadId = params[3];
threadTopicName = params[4];
chatAttachmentType = params[5];
chatMessage = params[6];
thumbBase64AttachmentPath = params[7];
loginUserName = params[8];
recipientName = params[9];
originalBase64Image = params[10];
originalFilePath = params[11];
String url;
if (!TextUtils.isEmpty(threadType) && threadType.equals(RecentChatList.SIMPLE_TYPE)) {
url = WS.URL.concat(WS.SAVE_CHAT);
} else {
url = WS.URL.concat(WS.GROUP_SAVE_CHAT);
}
Log.e(TAG, "url_" + chatMessage + " = " + url);
String response = HttpClientExecuteMethod.executeMultipartPostMethod(url, multipartEntityBuilder);
//Log.e(TAG, "save_chat_history_response_" + threadType + "_" + chatMessage + " =" + response);
return response;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/*This method is called after the background computation finishes.
The result of background process in passed in this method as parameters
and now you can dismiss progress dialog
and get the result and display on onPostExecute() method
*/
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
// Log.e(TAG, "chatAttachmentType = " + chatAttachmentType);
updateCounter();
if (result != null) {
JSONObject jo = new JSONObject(result);
String success = null;
final int storeLimit = SharedPreference.getLimit(UploadImageService.this);
if (jo.has(WS.SUCCESS)) {
success = jo.getString(WS.SUCCESS);
if (!TextUtils.isEmpty(success) && success.equals("0")) {
return;
}
if (!TextUtils.isEmpty(success) && success.equals("100")) {
callWsSaveChat(chatAttachmentType, chatMessage, thumbBase64AttachmentPath, originalBase64Image, originalFilePath);
updateRecentChatAndThreadList();
return;
}
if (!TextUtils.isEmpty(success) && success.equals("99")) {
updateRecentChatAndThreadList();
return;
}
}
try {
ArrayList<Chat> saveChatArrayList = null;
if (!TextUtils.isEmpty(success) && success.equals("1")) {
saveChatArrayList = new Chat().getChatHistory(UploadImageService.this, result, TAG, "");
// Log.e(TAG, "onPostExecute_saveChatArrayList.size = " + saveChatArrayList);
ArrayList<Chat> chatHistoryWithoutMsgId = database.getWithoutMsgIdChatHistory(chatThreadId, "#");
//Log.e(TAG, "onPostExecute_chatHistoryWithoutMsgId.size = " + chatHistoryWithoutMsgId.size());
if (saveChatArrayList != null && !saveChatArrayList.isEmpty() && saveChatArrayList.size() > 0) {
for (int i = 0; i < saveChatArrayList.size(); i++) {
final Chat apiChat = saveChatArrayList.get(i);
String apiMsg = apiChat.getMessage();
String apiThumb = null;
if (!TextUtils.isEmpty(apiChat.getAttachment_thumb())) {
apiThumb = apiChat.getAttachment_thumb().concat("$");
}
if (chatHistoryWithoutMsgId != null && !chatHistoryWithoutMsgId.isEmpty() && chatHistoryWithoutMsgId.size() > 0) {
for (int j = 0; j < chatHistoryWithoutMsgId.size(); j++) {
Chat dbChat = chatHistoryWithoutMsgId.get(j);
final String db_message = dbChat.getMessage();
final String db_thumb = dbChat.getAttachment_thumb();
if (apiThumb.equals(db_thumb)) {
database.updateChatList(apiChat, result, "#", db_message, db_thumb, loginUserId, toUser, chatThreadId, threadType);
bundle.putString(RESULT, UPLOAD_IMAGE);
receiver.send(STATUS_FINISHED, bundle);
if (!TextUtils.isEmpty(chatAttachmentType) && chatAttachmentType.equals(getResources().getString(R.string.Image))) {
originalBase64Image = getBase64Image(originalFilePath);
}
int subLength = 1024 * 256;
//Log.e(TAG, "upload_subLength = " + subLength);
int index = 0;
int totalChunks = 0;
if (!TextUtils.isEmpty(originalBase64Image)) {
for (int k = 0; index < originalBase64Image.length(); k++) {
index = index + subLength;
totalChunks++;
}
database.insertOriginalUploadImageList(apiChat.getAttachment_id(), totalChunks, 0, originalFilePath, chatThreadId, apiChat.getDt_sender_created(), chatAttachmentType);
// database.deleteAttachmentImageList(originalBase64Image);
database.deleteAttachmentImageList(originalFilePath);
UploadOriginalImageList(apiChat.getAttachment_id());
}
break;
} else {
// Log.e(TAG, "onPostExecute_not_equal_image");
}
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
// Util.showAlertDialog(mContext, mContext.getResources().getString(R.string.No_internet_connection_available));
}
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "error = " + e.getMessage());
}
}
There are many methods to upload more images to the server.. one could be including two libraries: apache-mime4j-0.6.jar and httpmime-4.0.1.jar.. After that create your java main code:
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FileUploadTest extends Activity {
private static final int SELECT_FILE1 = 1;
private static final int SELECT_FILE2 = 2;
String selectedPath1 = "NONE";
String selectedPath2 = "NONE";
TextView tv, res;
ProgressDialog progressDialog;
Button b1,b2,b3;
HttpEntity resEntity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
res = (TextView)findViewById(R.id.res);
tv.setText(tv.getText() + selectedPath1 + "," + selectedPath2);
b1 = (Button)findViewById(R.id.Button01);
b2 = (Button)findViewById(R.id.Button02);
b3 = (Button)findViewById(R.id.upload);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE1);
}
});
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE2);
}
});
b3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!(selectedPath1.trim().equalsIgnoreCase("NONE")) && !(selectedPath2.trim().equalsIgnoreCase("NONE"))){
progressDialog = ProgressDialog.show(FileUploadTest.this, "", "Uploading files to server.....", false);
Thread thread=new Thread(new Runnable(){
public void run(){
doFileUpload();
runOnUiThread(new Runnable(){
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});
}
public void openGallery(int req_code){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (requestCode == SELECT_FILE1)
{
selectedPath1 = getPath(selectedImageUri);
System.out.println("selectedPath1 : " + selectedPath1);
}
if (requestCode == SELECT_FILE2)
{
selectedPath2 = getPath(selectedImageUri);
System.out.println("selectedPath2 : " + selectedPath2);
}
tv.setText("Selected File paths : " + selectedPath1 + "," + selectedPath2);
}
}
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);
}
private void doFileUpload(){
File file1 = new File(selectedPath1);
File file2 = new File(selectedPath2);
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FileUploadTest extends Activity {
private static final int SELECT_FILE1 = 1;
private static final int SELECT_FILE2 = 2;
String selectedPath1 = "NONE";
String selectedPath2 = "NONE";
TextView tv, res;
ProgressDialog progressDialog;
Button b1,b2,b3;
HttpEntity resEntity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
res = (TextView)findViewById(R.id.res);
tv.setText(tv.getText() + selectedPath1 + "," + selectedPath2);
b1 = (Button)findViewById(R.id.Button01);
b2 = (Button)findViewById(R.id.Button02);
b3 = (Button)findViewById(R.id.upload);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE1);
}
});
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openGallery(SELECT_FILE2);
}
});
b3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!(selectedPath1.trim().equalsIgnoreCase("NONE")) && !(selectedPath2.trim().equalsIgnoreCase("NONE"))){
progressDialog = ProgressDialog.show(FileUploadTest.this, "", "Uploading files to server.....", false);
Thread thread=new Thread(new Runnable(){
public void run(){
doFileUpload();
runOnUiThread(new Runnable(){
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});
}
public void openGallery(int req_code){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (requestCode == SELECT_FILE1)
{
selectedPath1 = getPath(selectedImageUri);
System.out.println("selectedPath1 : " + selectedPath1);
}
if (requestCode == SELECT_FILE2)
{
selectedPath2 = getPath(selectedImageUri);
System.out.println("selectedPath2 : " + selectedPath2);
}
tv.setText("Selected File paths : " + selectedPath1 + "," + selectedPath2);
}
}
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);
}
private void doFileUpload(){
File file1 = new File(selectedPath1);
File file2 = new File(selectedPath2);
String urlString = "http://10.0.2.2/upload_test/upload_media_test.php";
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
FileBody bin2 = new FileBody(file2);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile1", bin1);
reqEntity.addPart("uploadedfile2", bin2);
reqEntity.addPart("user", new StringBody("User"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
runOnUiThread(new Runnable(){
public void run() {
try {
res.setTextColor(Color.GREEN);
res.setText("n Response from server : n " + response_str);
Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
}
}
Now your layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Multiple File Upload from CoderzHeaven"
/>
<Button
android:id="#+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get First File">
</Button>
<Button
android:id="#+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Second File">
</Button>
<Button
android:id="#+id/upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Upload">
</Button>
<TextView
android:id="#+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Selected File path : "
/>
<TextView
android:id="#+id/res"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
/>
</LinearLayout>
of course, include the internet permission in your manifest:
<uses-permission android:name="android.permission.INTERNET" />
And voilĂ . Anyway i followed this example in my case: http://www.coderzheaven.com/2011/08/16/how-to-upload-multiple-files-in-one-request-along-with-other-string-parameters-in-android/ try to see there.. There are 4 methods to upload multiple files. See which you like

Show progress bar with percentage while downloading file using Volley in android

I am using volley to download file using an asynchronous task.I want to show the progress with percentage while the file is being downloaded. But the problem is that the async task is started when the response has come. I can't find any way to track the progress before final response has completely come.
I didn't find any method in JsonRequest that can be used for this.
Below is the onResponse method of request class that extends JsonRequest that i am using.
protected Response<T> parseNetworkResponse(NetworkResponse response) {
if (response.statusCode >= 200 && response.statusCode <= 299) {
// If the status is correct, we return a success but with a null object, because the server didn't return anything
return Response.success(null, HttpHeaderParser.parseCacheHeaders(response));
}
else {
try {
if (downloadFlag) {
DownloadFileAsyncTask downloadFileAsyncTask = new DownloadFileAsyncTask(mContext, fileNameAndExtn,mNotifyManager,mBuilder,mDownloadNotificationUniqueId);
downloadFileAsyncTask.execute(response.data);
} else if (isResponseByteArr) {
return (Response<T>) Response.success(response.data, HttpHeaderParser.parseCacheHeaders(response));
} else {
String json = null;
if (isGzipped(response)) {
json = gzipDecompress(response.data);
} else {
json = new String(response.data,HttpHeaderParser.parseCharset(response.headers));
}
T parsedObject = gson.fromJson(json, clazz);
return Response.success(parsedObject, HttpHeaderParser.parseCacheHeaders(response));
}
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
DownFileAsyncTask is as follows:
package com.android.webframework.webservice;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.NotificationCompat;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
import com.android.applogger.AppLogger;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class DownloadFileAsyncTask extends AsyncTask<byte[], Integer, String> {
private String fileNameAndExtn;
private Context mContext;
private NotificationManager mNotifyManager;
private NotificationCompat.Builder mBuilder;
private int mUniqueId;
public DownloadFileAsyncTask(Context context, String fileNameAndExtn, NotificationManager notifyManager, NotificationCompat.Builder builder, int uniqueId) {
this.fileNameAndExtn = fileNameAndExtn;
this.mContext = context;
this.mNotifyManager = notifyManager;
this.mBuilder = builder;
this.mUniqueId = uniqueId;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
String MEDIA_MOUNTED = "mounted";
#Override
protected String doInBackground(byte[]... bytes) {
File file = null;
int copyCount = 0;
String filePath = "";
String diskState = Environment.getExternalStorageState();
if (diskState.equalsIgnoreCase(MEDIA_MOUNTED)) {
File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
file = new File(sd, fileNameAndExtn);
String fileName = "";
String fileExtn;
String fileNameToSave = fileNameAndExtn;
while (file.exists()) {
copyCount++;
String[] parts = fileNameAndExtn.split("[.]");
if (parts[0] != null)
fileName = parts[0];
fileName += "-" + copyCount;
fileNameToSave = fileName + "." + parts[1];
file = new File(sd, fileNameToSave);
}
fileNameAndExtn = fileNameToSave;
/*if (file.exists()) {
file.delete();
}*/
try {
FileOutputStream fos = new FileOutputStream(file.getPath());
fos.write(bytes[0]);
fos.close();
} catch (IOException e) {
AppLogger.e("file", "Exception in photoCallback", e);
}
AppLogger.e("file Download completed", "***************");
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
mContext.sendBroadcast(intent);
filePath = file.getAbsolutePath();
} else {
Toast.makeText(mContext, "The external disk is not mounted.", Toast.LENGTH_SHORT).show();
}
return (filePath);
}
#Override
protected void onPostExecute(String filePath) {
super.onPostExecute(filePath);
if (fileNameAndExtn != null && !fileNameAndExtn.equalsIgnoreCase("")) {
// Toast.makeText(mContext, "File downloaded in Downloads/" + fileNameAndExtn, Toast.LENGTH_LONG).show();
Toast.makeText(mContext, fileNameAndExtn + " downloaded successfully", Toast.LENGTH_LONG).show();
mBuilder.setProgress(100, 100, false);
Intent intent = getPendingIntent(mContext, filePath);
mBuilder.setContentTitle(fileNameAndExtn)
.setAutoCancel(true)
.setContentText("Download complete");
PendingIntent pendingIntent = null;
if (intent != null) {
pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
}
if (pendingIntent != null) {
mBuilder.setContentIntent(pendingIntent).setProgress(0, 0, false);
}
mNotifyManager.notify(mUniqueId, mBuilder.build());
}
}
#Override
protected void onProgressUpdate(Integer... values) {
mBuilder.setProgress(100, values[0], false);
mNotifyManager.notify(mUniqueId, mBuilder.build());
super.onProgressUpdate(values);
}
public Intent getPendingIntent(Context context, String filePath) {
Intent intent = new Intent(Intent.ACTION_VIEW);
// File file = new File("YOUR_SONG_URI"); // set your audio path
File file = new File(filePath);
intent.setDataAndType(Uri.fromFile(file), getMimeType(filePath));
if (intent.resolveActivityInfo(context.getApplicationContext().
getPackageManager(), 0) != null) {
// context.getApplicationContext().startActivity(intent);
return intent;
} else {
Toast.makeText(context, "File not present or Explorer app not present.",
Toast.LENGTH_LONG).show();
return null;
// if you reach this place, it means there is no any file
// explorer app installed on your device
}
}
public static String getMimeType(String url) {
String filePathWithoutWhiteSpace = url.replaceAll("\\s", "%20");
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(filePathWithoutWhiteSpace);
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
}
return type;
}
}
not sure you can do this with volley but easy solution for you as you are already using AsyncTask. Here is a link http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/ he did the same thing which you are looking.
I solved this problem by creating the notification as soon as the user clicks on download and then the async task notifies after the download is completed but i was not able to show the exact progress while downloading.

a way to copy from google drive? [duplicate]

I am developing an app to uploading ,displaying and downloading files from G Drive. Unfortunately When downloading I am getting
com.google.api.client.http.HttpResponseException: 401 Unauthorized.
Please help me to solve this problem.
Here I am assigning
credential = GoogleAccountCredential.usingOAuth2(this,DriveScopes.DRIVE);
service=new Drive.Builder(AndroidHttp.newCompatibleTransport(),new GsonFactory(),credential).build();
My Code Is:
package com.example.googledrive;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
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.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Children;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.Drive.Files.Get;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.ChildList;
import com.google.api.services.drive.model.ChildReference;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
static final int REQUEST_ACCOUNT_PICKER = 1;
static final int REQUEST_AUTHORIZATION = 2;
static final int CAPTURE_IMAGE = 3;
private static Uri fileUri;
private static Drive service;
private ProgressDialog progressDialog;
private GoogleAccountCredential credential;
String fileId;
String fileName;
String downloadUrl;
ListView listView;
Activity activity;
String sdCardPadth;
List<File> allFileList;
ArrayList<String> fileType;
ArrayList<String> mainTitleList;
ArrayList<String> fileIdList;
ArrayList<String> alternateUrlList;
ArrayList<Integer> fileSizeList;
FileTitlesAdapter myAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.uploadedFilesList);
allFileList = new ArrayList<File>();
mainTitleList = new ArrayList<String>();
alternateUrlList = new ArrayList<String>();
fileSizeList = new ArrayList<Integer>();
fileType = new ArrayList<String>();
fileIdList=new ArrayList<String>();
progressDialog=new ProgressDialog(getApplicationContext());
progressDialog.setTitle("Please Wait....");
progressDialog.setCancelable(false);
activity = this;
credential = GoogleAccountCredential.usingOAuth2(this,DriveScopes.DRIVE);
startActivityForResult(credential.newChooseAccountIntent(),REQUEST_ACCOUNT_PICKER);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, final int arg2,long arg3) {
// String str=itemArray.get(arg2).toString().trim();
System.out.println("mainTitleList size==="+mainTitleList.size());
System.out.println("arg2==="+arg2);
fileName = (String)mainTitleList.get(arg2);
mainTitleList.clear();
//fileSizeList.clear();
final String fileTypeStr=fileType.get(arg2);
fileType.clear();
if(fileTypeStr.contains("application/vnd.google-apps.folder"))
{
Thread t = new Thread(new Runnable() {
#Override
public void run() {
boolean b=true;
try {
String dirUrl=alternateUrlList.get(arg2);
alternateUrlList.clear();
System.out.println("Folder Name Is:"+fileName);
System.out.println("Folder Type Is:"+fileTypeStr);
System.out.println("Folder URL Is:"+dirUrl);
String fileId=fileIdList.get(arg2);
System.out.println("Folder Id Is:"+fileId);
//retrieveAllFilesFromDir(service, fileId, b);
//retrieveAllFiles1(service, b, fileId);
//Files.List request = service.children().get(fileId, null);
Files.List request = service.files().list().setQ("'" + fileId + "' in parents ");
retrieveAllFiles(service,request,b);
//retrieveAllFiles(service, b);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Exception In retrieveAllFiles Dir Is:"+e);
e.printStackTrace();
}
}
});t.start();
}
else
{
try {
System.out.println("fileSizeList size===="+fileSizeList.size());
System.out.println("arg2===="+arg2);
Integer fileSize = (int) fileSizeList.get(arg2);
downloadUrl = alternateUrlList.get(arg2);
byte[] size = new byte[fileSize];
int byteRead = 0, byteWritten = 0;
sdCardPadth = Environment.getExternalStorageDirectory().getPath();
System.out.println("Download Url==="+downloadUrl);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
InputStream inStream=downloadFile(service, downloadUrl);
java.io.File inFile=new java.io.File(sdCardPadth+"/"+fileName+"1");
System.out.println("File Succesfully Stored");
}
}).start();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Exception In get Integer Is:" + e);
e.printStackTrace();
}
}
}
});
}
#Override
protected void onActivityResult(final int requestCode,
final int resultCode, final 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);
final boolean b=false;
Thread t=new Thread(new Runnable() {
#Override
public void run() {
try
{
Files.List request = service.files().list().setQ("hidden="+b);
retrieveAllFiles(service,request,b);
} catch (Exception e) {
System.out.println("Exception Is:"+e);
e.printStackTrace();
}
}
}) ;t.start();
}
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
System.out.println("REQUEST_AUTHORIZATION case Is:"
+ REQUEST_AUTHORIZATION);
saveFileToDrive();
} else {
startActivityForResult(credential.newChooseAccountIntent(),
REQUEST_ACCOUNT_PICKER);
}
break;
case CAPTURE_IMAGE:
if (resultCode == Activity.RESULT_OK) {
System.out.println("CAPTURE_IMAGE case Is:" + CAPTURE_IMAGE);
saveFileToDrive();
}
}
}
private void saveFileToDrive() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
// File's binary content
System.out.println("run method");
java.io.File fileContent = new java.io.File(fileUri.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=null;
try {
file = service.files().insert(body, mediaContent).execute();
} catch (Exception e) {
System.out.println("Exception In Insert File Is"+e);
e.printStackTrace();
}
if (file != null) {
showToast("Photo uploaded: " + file.getTitle());
System.out.println("photo sucessfullly uploaded:"+ fileId);boolean b=false;
Files.List request = service.files().list().setQ("hidden="+b);
retrieveAllFiles(service,request,b);
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
private Drive getDriveService(GoogleAccountCredential credential) {
return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
new GsonFactory(), credential).build();
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast,Toast.LENGTH_SHORT).show();
}
});
}
private List<File> retrieveAllFiles(Drive service,Files.List request,boolean b) throws IOException {
List<File> result = new ArrayList<File>();
final ArrayList<String> titleList = new ArrayList<String>();
String fileUrl = "";
do {
try {
FileList files = request.execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
for (int i = 0; i < result.size(); i++) {
File tempFile = result.get(i);
String fileTypeStr = tempFile.getMimeType();
String fileName = tempFile.getTitle();
titleList.add(fileName);
fileId = tempFile.getId();
fileIdList.add(fileId);
fileUrl = tempFile.getAlternateLink();
System.out.println("<><>< fileUrl Is:" + fileUrl);
alternateUrlList.add(fileUrl);
fileType.add(fileTypeStr);
mainTitleList.add(fileName);
try {
Integer fileSize =tempFile.getFileSize()==null?100:(int) (long) tempFile.getFileSize();
fileSizeList.add(fileSize);
System.out.println("<><>< fileSize Is:" + fileSize);
} catch (Exception e) {
fileSizeList.add(2000);
e.printStackTrace();
}
}
try {
runOnUiThread(new Runnable() {
public void run() {
myAdapter = new FileTitlesAdapter(activity,
fileType, mainTitleList, alternateUrlList,
fileSizeList);
listView.setAdapter(myAdapter);
}
});
} catch (Exception e) {
System.out.println("Exception Setting ListView Is:" + e);
e.printStackTrace();
}
} catch (IOException e) {
System.out.println("An error occurred in retrieveAllFiles:"+ e);
request.setPageToken(null);
}
} while (request.getPageToken() != null
&& request.getPageToken().length() > 0);
return result;
}
private static InputStream downloadFile(Drive service, String url) {
System.out.println("downloadFile is called service=="+service);
if (url != null && url.length() > 0) {
try {
System.out.println("downloadFile is called try");
HttpResponse resp =service.getRequestFactory().buildGetRequest(new GenericUrl(url)).execute();
System.out.println("resp.getContent()===="+resp.getContent());
return resp.getContent();
} catch (Exception e) {
System.out.println("Exception Is:"+e);
e.printStackTrace();
return null;
}
} else {
System.out.println("No Exception No Output");
return null;
}
}
}
This is code that I use to download File from google Drive
new AsyncTask<Void, Integer, Boolean>() {
#Override
protected Boolean doInBackground(Void... params) {
try {
File file = service.files().get("path in drive").execute();
java.io.File toFile = new java.io.File("where you want to store");
toFile.createNewFile();
HttpDownloadManager downloader = new HttpDownloadManager(file, toFile);
downloader.setListener(new HttpDownloadManager.FileDownloadProgressListener() {
public void downloadProgress(long bytesRead, long totalBytes) {
Log.i("chauster",totalBytes);
Log.i("chauster",bytesRead);
}
#Override
public void downloadFinished() {
// TODO Auto-generated method stub
}
#Override
public void downloadFailedWithError(Exception e) {
// TODO Auto-generated method stub
}
});
return downloader.download(service);
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
};
}.execute();
HttpDownloadManager.java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import com.grandex.ShareInfomation.ShareData;
import com.grandex.ShareInfomation.ShareData.ToolTapState;
public class HttpDownloadManager {
private String donwloadUrl;
private String toFile;
private FileDownloadProgressListener listener;
private long totalBytes;
public void setListener(FileDownloadProgressListener listener) {
this.listener = listener;
}
public HttpDownloadManager(File sourceFile, java.io.File destinationFile) {
super();
this.donwloadUrl = sourceFile.getDownloadUrl();
this.toFile = destinationFile.toString();
this.totalBytes = sourceFile.getFileSize();
}
public static interface FileDownloadProgressListener {
public void downloadProgress(long bytesRead, long totalBytes);
public void downloadFinished();
public void downloadFailedWithError(Exception e);
}
public boolean download(Drive service) {
HttpResponse respEntity = null;
try {
// URL url = new URL(urlString);
respEntity = service.getRequestFactory()
.buildGetRequest(new GenericUrl(donwloadUrl)).execute();
InputStream in = respEntity.getContent();
if(totalBytes == 0) {
totalBytes = respEntity.getContentLoggingLimit();
}
try {
FileOutputStream f = new FileOutputStream(toFile) {
#Override
public void write(byte[] buffer, int byteOffset,
int byteCount) throws IOException {
// TODO Auto-generated method stub
super.write(buffer, byteOffset, byteCount);
}
}
};
byte[] buffer = new byte[1024];
int len1 = 0;
long bytesRead = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
if (listener != null) {
bytesRead += len1;
listener.downloadProgress(bytesRead, totalBytes);
}
}
f.close();
} catch (Exception e) {
if (listener != null) {
listener.downloadFailedWithError(e);
}
return false;
}
if (listener != null) {
listener.downloadFinished();
}
return true;
} catch (IOException ex) {
if (listener != null) {
listener.downloadFailedWithError(ex);
return false;
}
} finally {
if(respEntity != null) {
try {
respEntity.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return false;
}
}
Nowhere in your code are you setting the Authorization header.
You need something like
setRequestProperty("Authorization", "OAuth " + "***ACCESS_TOKEN***");
For any 401/403 errors it's well worth getting your request working on the Oauth. Try this out
Please check below code for download apk file from google drive
implementation 'com.google.android.material:material:1.0.0'
Add uses permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
Create a file provider
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<files-path
name="files"
path="." />
Now declare the file provider inside the manifest
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_provider_paths" />
Add some value inside strings.xml file
<resources>
<string name="app_name">Download APK</string>
<string name="downloading">Downloading...</string>
<string name="title_file_download">APK is downloading</string>
<string name="storage_access_required">Storage access is required to downloading the file.</string>
<string name="storage_permission_denied">Storage permission request was denied.</string>
<string name="ok">OK</string>
Create a download controller
package com.hktpayment.mytmoney.pos.mauritius.util
import android.app.Dialog
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.util.Log
import android.widget.ProgressBar
import android.widget.Toast
import androidx.core.content.FileProvider
import com.hktpayment.mytmoney.pos.mauritius.BuildConfig
import com.hktpayment.mytmoney.pos.mauritius.R
import java.io.File
class DownloadController(
private val context: Context,
private val url: String,
private val progressBar: Dialog
) {
companion object {
private const val FILE_NAME = "SampleDownloadApp.apk"
private const val FILE_BASE_PATH = "file://"
private const val MIME_TYPE = "application/vnd.android.package-archive"
private const val PROVIDER_PATH = ".provider"
private const val APP_INSTALL_PATH = "application/vnd.android.package-
archive"
}
private lateinit var downloadManager: DownloadManager
fun enqueueDownload() {
var destination =
context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString()
+ "/"
destination += FILE_NAME
val uri = Uri.parse("$FILE_BASE_PATH$destination")
val file = File(destination)
if (file.exists()) file.delete()
downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as
DownloadManager
val downloadUri = Uri.parse(url)
val request = DownloadManager.Request(downloadUri)
request.setMimeType(MIME_TYPE)
request.setTitle(context.getString(R.string.title_file_download))
request.setDescription(context.getString(R.string.downloading))
// set destination
request.setDestinationUri(uri)
showInstallOption(destination, uri)
// Enqueue a new download and same the referenceId
downloadManager.enqueue(request)
Toast.makeText(context, context.getString(R.string.downloading),
Toast.LENGTH_LONG)
.show()
}
private fun showInstallOption(
destination: String,
uri: Uri
) {
// set BroadcastReceiver to install app when .apk is downloaded
progressBar.show()
val onComplete = object : BroadcastReceiver() {
override fun onReceive(
context: Context,
intent: Intent
) {
progressBar.dismiss()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val contentUri = FileProvider.getUriForFile(
context,
BuildConfig.APPLICATION_ID + PROVIDER_PATH,
File(destination)
)
val install = Intent(Intent.ACTION_VIEW)
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
install.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
install.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true)
install.data = contentUri
context.startActivity(install)
context.unregisterReceiver(this)
// finish()
} else {
val install = Intent(Intent.ACTION_VIEW)
install.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
install.setDataAndType(
uri,
APP_INSTALL_PATH
)
context.startActivity(install)
context.unregisterReceiver(this)
// finish()
}
}
}
context.registerReceiver(onComplete, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
}
}
In this activity, we are checking storage permission first. If permission is granted than calling download function otherwise requesting for storage permission.
val apkUrl = "https://download .apk"
downloadController = DownloadController(this, apkUrl)
downloadController.enqueueDownload()

Transfer Data between Android devices using wifi direct?

I have recently implement wifi direct into my project,my aim is pass string value between two wifidirect connected devices when some of my app condition satisfies.right now i have listed all peers and also made connection between the selected peer.what my idea is to pass a json file between the devices.so before try to execute that idea i try to pass a image file between two devices.i followed the steps from the android wifidirect tutorial.listing peers and the connection between the peers is success full but i cant pass the data between the devices.the follwing is my code.
FileTransferService.java
package jing.app.directwifi;
import android.app.IntentService;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
/**
* A service that process each file transfer request i.e Intent by opening a
* socket connection with the WiFi Direct Group Owner and writing the file
*/
public class FileTransferService extends IntentService {
private static final int SOCKET_TIMEOUT = 5000;
public static final String ACTION_SEND_FILE = "jing.app.directwifi.SEND_FILE";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";
public FileTransferService(String name) {
super(name);
}
public FileTransferService() {
super("FileTransferService");
}
/*
* (non-Javadoc)
* #see android.app.IntentService#onHandleIntent(android.content.Intent)
*/
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
try {
// Log.d(WiFiDirectActivity.TAG, "Opening client socket - ");
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
Log.d("connected", "Client socket - " + socket.isConnected());
OutputStream stream = socket.getOutputStream();
ContentResolver cr = context.getContentResolver();
InputStream is = null;
try {
is = cr.openInputStream(Uri.parse(fileUri));
} catch (FileNotFoundException e) {
Log.d("exp", e.toString());
}
MainActivity.copyFile(is, stream);
Log.d("exp" ,"Client: Data written");
} catch (IOException e) {
Log.e("exp", e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}
}
Main Activity.java
package jing.app.directwifi;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collection;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener, ConnectionInfoListener {
private WifiP2pManager mManager;
private Channel mChannel;
private BroadcastReceiver mReceiver;
private IntentFilter mIntentFilter;
private Button mDiscover;
private TextView mDevices;
public ArrayAdapter mAdapter;
private ArrayList<WifiP2pDevice> mDeviceList = new ArrayList<WifiP2pDevice>();
protected static final int CHOOSE_FILE_RESULT_CODE = 20;
int flag=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDiscover = (Button) findViewById(R.id.discover);
mDiscover.setOnClickListener(this);
mDevices = (TextView) findViewById(R.id.peers);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectReceiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class WiFiDirectReceiver extends BroadcastReceiver {
private WifiP2pManager mManager;
private Channel mChannel;
private MainActivity mActivity;
public WiFiDirectReceiver(WifiP2pManager manager, Channel channel, MainActivity activity) {
super();
mManager = manager;
mChannel = channel;
mActivity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
String title = "ANDROID_ID[" + getAndroid_ID() + "]";
title += " MAC[" + getMACAddress() + "]";
Toast.makeText(mActivity, "Wi-Fi Direct is enabled."+title, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mActivity, "Wi-Fi Direct is disabled.", Toast.LENGTH_SHORT).show();
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
if (mManager != null) {
mManager.requestPeers(mChannel, new PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
if (peers != null) {
mDeviceList.addAll(peers.getDeviceList());
ArrayList<String> deviceNames = new ArrayList<String>();
for (WifiP2pDevice device : mDeviceList) {
deviceNames.add(device.deviceName);
}
if (deviceNames.size() > 0) {
mAdapter = new ArrayAdapter<String>(mActivity, android.R.layout.simple_list_item_1, deviceNames);
if(flag==0)
{
flag=1;
showDeviceListDialog();
}
} else {
Toast.makeText(mActivity, "Device list is empty.", Toast.LENGTH_SHORT).show();
}
}
}
});
}
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.discover:
onDiscover();
break;
}
}
private void onDiscover() {
mManager.discoverPeers(mChannel, new ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Discover peers successfully.", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reason) {
Toast.makeText(MainActivity.this, "Discover peers failed.", Toast.LENGTH_SHORT).show();
}
});
}
private void showDeviceListDialog() {
DeviceListDialog deviceListDialog = new DeviceListDialog();
deviceListDialog.show(getFragmentManager(), "devices");
}
private class DeviceListDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select a device")
.setSingleChoiceItems(mAdapter, 0, MainActivity.this)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
}
#Override
public void onClick(DialogInterface dialog, int which) {
onDeviceSelected(which);
dialog.dismiss();
}
private void onDeviceSelected(int which) {
WifiP2pDevice device = mDeviceList.get(which);
if (device == null) {
return;
}
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
mManager.connect(mChannel, config, new ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, CHOOSE_FILE_RESULT_CODE);
}
#Override
public void onFailure(int reason) {
Toast.makeText(MainActivity.this, "Failed to connect", Toast.LENGTH_SHORT).show();
}
});
}
/**
* ANDROID_ID
*/
private String getAndroid_ID() {
return Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
}
/**
* Wi-Fi MAC
*/
private String getMACAddress() {
WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = manager.getConnectionInfo();
String mac = wifiInfo.getMacAddress();
// After the group negotiation, we assign the group owner as the file
// server. The file server is single threaded, single connection server
// socket.
new FileServerAsyncTask(getApplicationContext())
.execute();
return mac;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// User has picked an image. Transfer it to group owner i.e peer using
// FileTransferService.
Uri uri = data.getData();
Log.d("intent", "Intent----------- " + uri);
Intent serviceIntent = new Intent(MainActivity.this, FileTransferService.class);
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
getMACAddress());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
startService(serviceIntent);
}
/**
* A simple server socket that accepts connection and writes some data on
* the stream.
*/
public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
private Context context;
/**
* #param context
* #param statusText
*/
public FileServerAsyncTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(Void... params) {
try {
System.out.println("insideeeeeeeeeeeeeeeeeeeeeeee");
ServerSocket serverSocket = new ServerSocket(8988);
Log.d("Server: Socket opened", "Server: Socket opened");
Socket client = serverSocket.accept();
Log.d("Server: connection done", "Server: connection done");
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
Log.d("server: copying files ", "server: copying files " + f.toString());
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
Log.e("exp", e.getMessage());
System.out.println(":iooo:"+e);
return null;
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(String result) {
if (result != null) {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
long startTime=System.currentTimeMillis();
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
long endTime=System.currentTimeMillis()-startTime;
Log.v("","Time taken to transfer all bytes is : "+endTime);
} catch (IOException e) {
Log.d("exp", e.toString());
return false;
}
return true;
}
#Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "connectioninfoo", 3000).show();
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="jing.app.directwifi"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Market filtering -->
<uses-feature
android:name="android.hardware.wifi.direct"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="jing.app.directwifi.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Used for transferring files after a successful connection -->
<service
android:name=".FileTransferService"
android:enabled="true" />
</application>
</manifest>
These are files used in my code .form the tutorial i have found that
new FileServerAsyncTask(getApplicationContext())
.execute();
where the the incomming data is begin accepted so when i need to execute this asyn thread,so anyone help me in which portion i have made the mistake.how can i transfer the file between devices .
The android code from the demo wifi direct project is able to pass file is unidirectional. ie. you can send file from client to server only. You need furthur modifications to make it work in both direction.
EDIT 2:
For that you need to know the IP address of both connected peers. Use the following function which I made following various sources with my modifications wherever appropriate.
public static String getIpAddress() {
try {
List<NetworkInterface> interfaces = Collections
.list(NetworkInterface.getNetworkInterfaces());
/*
* for (NetworkInterface networkInterface : interfaces) { Log.v(TAG,
* "interface name " + networkInterface.getName() + "mac = " +
* getMACAddress(networkInterface.getName())); }
*/
for (NetworkInterface intf : interfaces) {
if (!getMACAddress(intf.getName()).equalsIgnoreCase(
Globals.thisDeviceAddress)) {
// Log.v(TAG, "ignore the interface " + intf.getName());
// continue;
}
if (!intf.getName().contains("p2p"))
continue;
Log.v(TAG,
intf.getName() + " " + getMACAddress(intf.getName()));
List<InetAddress> addrs = Collections.list(intf
.getInetAddresses());
for (InetAddress addr : addrs) {
// Log.v(TAG, "inside");
if (!addr.isLoopbackAddress()) {
// Log.v(TAG, "isnt loopback");
String sAddr = addr.getHostAddress().toUpperCase();
Log.v(TAG, "ip=" + sAddr);
boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
if (isIPv4) {
if (sAddr.contains("192.168.49.")) {
Log.v(TAG, "ip = " + sAddr);
return sAddr;
}
}
}
}
}
} catch (Exception ex) {
Log.v(TAG, "error in parsing");
} // for now eat exceptions
Log.v(TAG, "returning empty ip address");
return "";
}
public static String getMACAddress(String interfaceName) {
try {
List<NetworkInterface> interfaces = Collections
.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
if (interfaceName != null) {
if (!intf.getName().equalsIgnoreCase(interfaceName))
continue;
}
byte[] mac = intf.getHardwareAddress();
if (mac == null)
return "";
StringBuilder buf = new StringBuilder();
for (int idx = 0; idx < mac.length; idx++)
buf.append(String.format("%02X:", mac[idx]));
if (buf.length() > 0)
buf.deleteCharAt(buf.length() - 1);
return buf.toString();
}
} catch (Exception ex) {
} // for now eat exceptions
return "";
/*
* try { // this is so Linux hack return
* loadFileAsString("/sys/class/net/" +interfaceName +
* "/address").toUpperCase().trim(); } catch (IOException ex) { return
* null; }
*/
}
I think the way you initialize client makes the problem.
You need to call this
new FileServerAsyncTask(getApplicationContext()).execute();
after the connection is established and check if it's a client.
Now you are creating a client socket only if it is a server(group owner) and always when you call to get a MAC address.
So on the client side you are not intializing the socket and so not able to receive the file.
Once check the WifiDirect sample demo provided in the SDK, you may get more idea.

Categories

Resources