Download Random Images from file server - android

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

Related

PC to Android File Transfer through Sockets

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

How to retrive pdf file from server & show in app & how?

How to convert pdf file into Base64 in android & how to retrive pdf file from server them using json(HTTPURLConection)?
You can convert a PDF to base64 in android using
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
String encodeFileToBase64Binary = encodeFileToBase64Binary(yourFile);
private static String encodeFileToBase64Binary(File fileName) throws IOException {
byte[] bytes = loadFile(fileName);
byte[] encoded = Base64.encodeBase64(bytes);
String encodedString = new String(encoded);
return encodedString;
}
And you may refer this link to work out with your second question Retrieve PDF from server
You can download a PDF fie from server using following Code..
avtivity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aman.pdfserver.MainActivity">
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="download"
android:onClick="download" />
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/button1"
android:layout_marginTop="38dp"
android:text="view"
android:onClick="view" />
</RelativeLayout>
MainActivity.java
package com.example.aman.pdfserver;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.app.ProgressDialog;
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.util.Log;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
// Progress dialog
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
}
public void download(View v)
{
new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf");
}
public void view(View v)
{
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "maven.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);
try{
startActivity(pdfIntent);
}catch(ActivityNotFoundException e){
Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
}
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, "testthreepdf");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
return null;
}
}
}
FileDownloader.java
package com.example.aman.pdfserver;
/**
* Created by Aman on 13-12-2016.
*/
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.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();
}
}
}

Getting Error while downloading file (from local system) in android

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.

Image download code works for all image format, issues with PNG format rendering

I am using the code below to download and show image from server to my ImageView
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 HTTPTest extends Activity {
ImageView imView;
String imageUrl="http://11.0.6.23/";
Random r= new Random();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Button bt3= (Button)findViewById(R.id.get_imagebt);
bt3.setOnClickListener(getImgListener);
imView = (ImageView)findViewById(R.id.imview);
}
View.OnClickListener getImgListener = new View.OnClickListener()
{
#Override
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
//png0.png, png1.png, png2.png so different file is downloaded in button press
int i =r.nextInt(4);
downloadFile(imageUrl+"png"+i+".png");
Log.i("im url",imageUrl+"png"+i+".png");
}
};
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();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
imView.setImageBitmap(bmImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This code works file for all format of images but when it comes to PNG it wont let the image transparent after download and displaying on ImageView.
Any idea?
I dont know it will be a solution for you or not
But you can use a Drawable instead of Bitmap
Here is the code
void downloadFile(String fileUrl) {
try{
InputStream is = (InputStream) new URL(fileUrl).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
imgView.setImageDrawable(d);
} catch (IOException e) {
e.printStackTrace();
}
}
This will show a png correctly

how to upload the image into server

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

Categories

Resources