Download.java
package com.example.download_file;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Download extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
final Button downloadbutton=(Button)findViewById(R.id.download_button);
final EditText text=(EditText)findViewById(R.id.download_filename);
downloadbutton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
download();
text.setText("success");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_download, menu);
download();
return true;
}
public void download()
{
final EditText text=(EditText)findViewById(R.id.download_filename);
final EditText localname=(EditText)findViewById(R.id.localname);
try {
String name=text.getText().toString();
String sdcardname=localname.getText().toString();
URL url = new URL(name);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,sdcardname);
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
.
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
1)
input: url= "\192.168.0.103\shared\file.txt"
error: java.net.MalformedURLException:Protocol not found :\192.168.0.103\shared\file.txt
2)
input :url= "file://192.168.0.103/shared/file.txt"
error : java.lang.ClassCastEXception : org.apache.harmony.luni.internal.net.www.protocol.ftp.FtpURLConnection
Use AsyncTask Take a look here: link AsyncTask may be this can help you solve your problem.
Related
I have read txt file from URL but cannot use read text from URL to string in main thread. I have the following code.
How can i get string read from AsyncTask in main thread?
package np.info.mukesh.utdlive;
/**
* Created by Mukesh on 4/30/2017.
*/
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.thin.downloadmanager.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
public class LoadActivity extends AppCompatActivity {
private Tracker mTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load);
new GetMethodDemo().execute("http://m.live.mukesh.info.np/link.txt");
//Toast data read from url
Toast.makeText(this,server_response(), Toast.LENGTH_LONG).show();
}
public class GetMethodDemo extends AsyncTask<String , Void ,String> {
String server_response;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView tv = (TextView) findViewById(R.id.updateNotice);
tv.setText(server_response);
}
}
// Converting InputStream to String
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
}
I have been searching solution for some days but no luck. I am learning android from stackoverflow and google and some blog post. So, I am not much experienced. Thank you!
How to transfer a file(unknown extension ie maybe a pdf/word/jpeg) from PC to Android Phone using Socket Programming. The Android Phone should be able to detect the type of file transfer and should be able to open it thereafter. Also the file should go into a specific folder named after app name in External storage.
I have tried following solution. However in this case, when I select the file to be transferred, the file transferred at Android side is of arbitrary size and not of the same size as of file selected, it is of some random size. Also the file transferred cannot be opened as it does not have a fixed extension.
Any help would be appreciated.
Android code(To receive file)
package minor.subham.com.pccontrol;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.net.*;
import java.io.*;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class getFile extends ActionBarActivity {
ImageView getFile;
public final static int SOCKET_PORT = Constants.SERVER_PORT; // you may change this
public final static String SERVER = Constants.SERVER_IP; // localhost
public final static int FILE_SIZE = 6022386; // file size temporary hard coded
// should bigger than the file to be downloaded
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_file);
getFile = (ImageView) findViewById(R.id.getFile);
getFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread thread = new Thread() {
#Override
public void run() {
while(true) {
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
final File file;
file = new File(Environment.getExternalStorageDirectory(), "PcControl");
try {
sock = new Socket(SERVER, SOCKET_PORT);
System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [FILE_SIZE];
InputStream is = sock.getInputStream();
// fos = new FileOutputStream(FILE_TO_RECEIVED);
try {
fos = new FileOutputStream(file);
} catch (IOException e) {
e.printStackTrace();
}
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
fos.write(mybytearray);
fos.close();
System.out.println("File "
+ " downloaded (" + current + " bytes read)");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (bos != null) try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (sock != null) try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
};
thread.start();
}
});
}
}
And Her is the Java Code to send file. Suppose I want to send file temp.jpg
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class send {
public final static int SOCKET_PORT = 8991; // you may change this
public final static String FILE_TO_SEND = "temp.jpg"; // you may change this
public static void main (String [] args ) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
servsock = new ServerSocket(SOCKET_PORT);
// while (true) {
System.out.println("Waiting...");
try {
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// send file
File myFile = new File (FILE_TO_SEND);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = sock.getOutputStream();
System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done.");
}
finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
// }
}
finally {
if (servsock != null) servsock.close();
}
}
}
when I click button download, pdf opens but gives me this message document is empty 0ko plz if you any suggessions,I use my phone, and I send the acrobat reader adobe file in my phone and i have adobe acrobat in my phone..
this Mainactivity.java
package com.example.down1;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void download(View v)
{
new DownloadFile().execute("http://172.16.2.138/upload/guide.pdf", "guide.pdf");
}
public void view(View v)
{
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/uploade/" + "guide.pdf"); // -> filename = maven.pdf
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Intent intent = Intent.createChooser(pdfIntent, "Open File");
startActivity(pdfIntent);
}
private class DownloadFile extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0]; // -> http://maven.apache.org/maven-1.x/maven.pdf
String fileName = strings[1]; // -> maven.pdf
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "uploade");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
return null;
}
}
}
this is my class filedownloader
package com.example.down1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FileDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is my attempt. My files are hosted on my own servers mostly JPGs files. I'm trying to download them into my app. I failed to generate those images into my app. I follow the guide from this blog http://getablogger.blogspot.gr/2008/01/android-download-image-from-server-and.html
My xml
<?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="Hello World, HTTPImage load test"
/>
<Button android:id="#+id/get_imagebt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get an image"
android:layout_gravity="center"
/>
<ImageView android:id="#+id/imview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</LinearLayout>
Coding
package com.example.downloadimages;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
public class MainActivity extends Activity {
ImageView imView;
String imageUrl="http://myfilehosting.com/";
Random r;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
r= new Random();
Button bt3= (Button)findViewById(R.id.get_imagebt);
bt3.setOnClickListener(getImgListener);
imView = (ImageView)findViewById(R.id.imview);
}
View.OnClickListener getImgListener = new View.OnClickListener()
{
public void onClick(View view) {
// TODO Auto-generated method stub
//i tried to randomize the file download, in my server i put 4 files with name like
//jpg0.jpg, jpg1.jpg, jpg2.jpg so different file is downloaded in button press
int i =r.nextInt()%4;
downloadFile(imageUrl+i+".jpg");
}
Bitmap bmImg;
void downloadFile(String fileUrl){
URL myFileUrl =null;
try {
myFileUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
int[] bitmapData =new int[length];
byte[] bitmapData2 =new byte[length];
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
imView.setImageBitmap(bmImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
};
}
there are several problems with your code:
you are trying to perform network operation (download file from remote server) from the UI thread. network operation must be executed from another thread. otherwise - exception been thrown.
one of the ways to launch the code from another thread is:
new Thread(new Runnable() {
#Override
public void run() {
downloadFile(imageUrl+i+".jpg");
}
}).start();
better approach would be using AsyncTask or IntentService (which also performing the code on separate thread)
second thing - you can't just create int array with the size of the input stream: if the image is too big, it can fail. try break the download to segments with fixed size (say 2058 bytes each segment) for example:
private HttpURLConnection conn;
private InputStream stream;
private FileOutputStream out;
private double fileSize;
private double downloaded;
public void downloadFile(String fileURL, String fileName) {
try {
conn = (HttpURLConnection) new URL(fileURL).openConnection();
fileSize = conn.getContentLength();
File file = new File(fileName);
out = new FileOutputStream(file);
conn.connect();
stream = conn.getInputStream();
while (status == DOWNLOADING) {
byte buffer[];
if (fileSize - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[(int) (fileSize - downloaded)];
}
int read = stream.read(buffer);
if (read == -1) {
out.close();
if (conn != null) {
conn.disconnect();
}
break;
}
out.write(buffer, 0, read);
downloaded += read;
}
} catch (Exception e) {
Log.e("downloadFile():", e.getMessage());
if (conn != null) {
conn.disconnect();
}
}
}
i tried to upload the image to the server for two days but i could not post the image .the coding is compiled and run sucessfully but the imag is not write into the server.
this is my coding:
import java.io.BufferedInputStream;
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.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.Toast;
public class sde extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadtoUrl("http://
");
}
private void loadtoUrl(String string) {
// TODO Auto-generated method stub
try {
String pathToOurFile = "/sdcard/tamil.PNG";
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
BufferedInputStream bis = new BufferedInputStream(fileInputStream,3000);
byte[] bt=new byte[bis.available()];
HttpURLConnection connection = (HttpURLConnection)new URL(string).openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.connect();
FileOutputStream input = (FileOutputStream) connection.getOutputStream();
input.write(bt);
} catch (MalformedURLException e) {
Context context = null;
int duration = 0;
Toast.makeText(context, "erro in writing", duration);
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
here is a nice article, http://blog.sptechnolab.com/2011/03/09/android/android-upload-image-to-server/. It contains an example that will upload an image and write it at server side. It works.
public boolean fileUpload(Map<String , String> params, ByteArrayOutputStream file, String link) throws Throwable{
Account user = Util.getAccount(getApplicationContext());
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(link);
MultipartEntity multipartContent = new MultipartEntity();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String , String> entry : params.entrySet()) {
multipartContent.addPart(entry.getKey(),new StringBody(entry.getValue(),Charset.forName(HTTP.UTF_8)));
}
}
byte[] data = file.toByteArray();
ByteArrayBody img = new ByteArrayBody(data, "capture.jpg");
multipartContent.addPart("image",img);
postRequest.setEntity(multipartContent);
HttpResponse res = httpClient.execute(postRequest);
res.getEntity().getContent().close();
return true;
}catch(Throwable e){
throw e;
}
}