Download a file from internet inside the app without user intervention - android

I need to download a file from internet to update some resources files in the path
"/data/data/" + context.getPackageName() + "/databases/"
the method
public static void updateDB(){
removeOldCopies();
//how to download a file in a specific directory without open browser????
}
should perform this action without user intervention, showing only a progress dialog
How could I do this?

You can use AsyncTask to show a Progress Dialog on the PreExecute() method and hide/dismiss it in the PostExecute() method.
ProgressDialog prog = new ProgressDialog(this); // Create Progress Dialog
private class DownloadFile extends AsyncTask<Void, Integer, Void>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Display progressDialog before download starts
prog.show();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
prog.hide(); //Hide Progress Dialog else use dismiss() to dismiss the dialog
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
InternetManager in = new InternetManager("http://url-to-download");
in.fileRequest();
return null;
}
}
in.fileRequest() will give you the file that you intent to download, Then use FileOutputStream.write(bytes[]) to write it into a file.
And finally call the AsyncTask through,
DownloadFile dd = new DownloadFile();
dd.execute();
InternetManager class which performing internet releted task.
public class InternetManager {
HttpClient httpclient;
HttpGet httpget;
HttpResponse httpresponse;
HttpEntity httpentity;
String url;
String response = null;
byte[] data = null;
public InternetManager(String url) {
this.url = url;
}
public byte[] fileRequest() {
httpclient = new DefaultHttpClient();
httpget = new HttpGet(url);
try {
httpresponse = httpclient.execute(httpget);
httpentity = httpresponse.getEntity();
data = EntityUtils.toByteArray(httpentity);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("", "File downloaded URL: " + url);
return data;
}
}

Related

unfortunately android application has been stopped. At Http Post while attempting to call server

Unfortunately android application has been stopped. At Http Post while attempting to call server at post activity please help
HttpClient cli = new DefaultHttpClient();
//HttpPost post = new HttpPost("http://" + sp.getString("ip", "localhost") + "/attendance/cliLogin.php");
HttpPost post = new HttpPost("localhost/attendance/");
// seting post data
List<NameValuePair> loginData = new ArrayList<NameValuePair>(2);
loginData.add(new BasicNameValuePair("uname", uname));
loginData.add(new BasicNameValuePair("pass", pass));
post.setEntity(new UrlEncodedFormEntity(loginData));
// executing login
HttpResponse res = cli.execute(post);
HttpEntity resent = res.getEntity();
String result = EntityUtils.toString(resent);
// reading response
if(result.equals("NoParams"))
Commons.showToast("Something went wrong", true);
else if(result.equals("Login"))
{
navi = new Intent(this, HomeActivity.class);
startActivity(navi);
}
else
Commons.showToast(result, true);
}
catch (HttpHostConnectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Commons.showToast("Can't reach server, check the Hostname", true);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
Commons.showToast("Username/Password can't be empty", true);
}
}
Could you please share your logcat to see the error? I think that your are calling the php script in your main thread (that is your activity thread) and you may have NetworkOnMainThreadException
If that is the case:
Create a class that extends the AsyncTask.
Override its methods.
In the creator of this class pass the variables and assign them to the fields (variables) of your class.
Make your post in an AsyncTask inside the doInBackground method
And call the AsyncTask execute. Like this:
public class MyTask extends AsyncTask<String,String,String>{
private short errorType = -1;
private String result;
private String uname;
private String pass;
public MyTask(String uname, String pass){
this.uname = uname;
this.pass = pass;
}
#Override
protected String onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (errorType == 1){
Commons.showToast("Can't reach server, check the Hostname", true);
}
if(result.equals("NoParams")) {
Commons.showToast("Something went wrong", true); }
else if(result.equals("Login")) {
Intent navi = new Intent(this, HomeActivity.class); startActivity(navi);
}
else {
Commons.showToast(result, true);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try
{
HttpClient cli = new DefaultHttpClient();
HttpPost post = new HttpPost("localhost/attendance/");
List<NameValuePair> loginData = new ArrayList<NameValuePair>(2);
loginData.add(new BasicNameValuePair("uname", uname));
loginData.add(new BasicNameValuePair("pass", pass));
post.setEntity(new UrlEncodedFormEntity(loginData));
// executing login
HttpResponse res = cli.execute(post);
HttpEntity resent = res.getEntity();
return result = EntityUtils.toString(resent);
}
catch (HttpHostConnectException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
errorType = 1;
return null;
}
catch (ParseException e) {
// TODO Auto-generated catch block e.printStackTrace();
errorType = 2;
return null;
}
catch (IOException e) {
// TODO Auto-generated catch block e.printStackTrace();
errorType = 3;
return null;
}
catch(Exception e){
errorType = 4;
return null;
}
}
}
And inside the activity make your call like this:
MyTask new MyTask(uname, pass).execute();
Again. All this is applicable only if you have
NetworkOnMainThreadException
Please share your logcat for further help.

Android NetworkOnMainThreadException inside Asyntask class

This code shows the exception when it reach the get sentence (line commented on the code).
The code is the next, consist on get a comments list from Http get Request:
public class ObtencionComentariosPerfil extends AsyncTask<String, Integer, List<Comment>>{
#Override
protected List<Comment> doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
URI url;
List<Comment> listaComentarios = new ArrayList<Comment>();
try {
url = new URI(params[1]);
HttpGet del = new HttpGet(url);
del.setHeader("content-type", "application/json");
del.setHeader("X-Auth-Token", params[0]);
System.out.println("El token params es: "+params[0]);
HttpResponse resp = httpClient.execute(del);// THE EXCEPTION shows here
StatusLine estatus = resp.getStatusLine();
if (estatus.getStatusCode() == 200) {
InputStream is = resp.getEntity().getContent();
CommentsParser parser= new CommentsParser();
listaComentarios = parser.parseoComentarios(is.toString());
} else {
System.out.println("Error");
listaComentarios = null;
}
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listaComentarios;
}
#Override
protected void onPostExecute(List<Comment> lista){
}
}
Here is called from main code:
public List<Comment> obtieneComentariosPerfil(long idUsuario, String aut){
List<Comment> listaComentarios = new ArrayList<Comment>();
String url= "http://"+ip+":8080/api/users/"+idUsuario+"/comments";
String[] params= new String[2];
params[0]=aut;
params[1]=url;
ObtencionComentariosPerfil du = new ObtencionComentariosPerfil();
listaComentarios = du.doInBackground(params);
return listaComentarios;
}
I think it have to be a stupid failure but i cant find the error. Thanks.
Because you call du.doInBackground(params);
you should call du.excute(params) instead
listaComentarios = du.doInBackground(params);
You submit async tasks for execution in a background thread by calling execute(), not by directly calling the doInBackground() callback in the current thread.
Communicate the result back to UI thread in onPostExecute().

Why do the Progress Bar doesn't quit?

I have used an asyncTask to make an http request and hence i have used progress bar to indicate the progress of ongoings in that thread. Everything works fine till the onPostexecute() method is called, i have displayed the response string in the Logcat but my progress bar doesn't quit.
There was similar questions asked but i didn't get the required solution for the problem.
Please help.
Here is my code:
class RequestTask extends AsyncTask<String, Integer, String> {
#SuppressWarnings("static-access")
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
prgDialog=new ProgressDialog(getActivity());
prgDialog.setCancelable(true);
prgDialog.show(getActivity(), null, "Loading...");
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
// TODO Handle problems..
} catch (IOException e) {
// TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("result", result);
prgDialog.dismiss();
// Do anything with response..
}
}
You're not calling dismiss() on the ProgressDialog instance you think(or want)you do. You create a ProgressDialog and assign it to the prgDialog reference only to call:
prgDialog.show(getActivity(), null, "Loading...");
which will create a new instance of ProgressDialog which you don't dismiss because prgDialog points to another not showing ProgressDialog. Try:
protected void onPreExecute() {
super.onPreExecute();
prgDialog = ProgressDialog.show(getActivity(), null, "Loading...");
}
This is why you should call static methods on the class and not some instance of that class.

show upload progress for JSON

I have the following piece of code and I would want to add a feature in here such that I know when the JSON content is uploaded. I am uploading a JSON content.
#Override
protected String doInBackground(JSONObject... params) {
// TODO Auto-generated method stub
String state = "";
HttpPost httpPost = new HttpPost(commentURL);
StringEntity se = null;
HttpResponse response = null;
HttpEntity entity = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
InputStream is = null;
try {
se = new StringEntity(params[0].toString());
Log.i("SE", params[0].toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
httpPost.setEntity(se);
try {
response = httpClient.execute(httpPost);
Log.i("HTTP POST", httpPost.toString());
Log.i("RESPONSE", response.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
entity = response.getEntity();
try {
is = entity.getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
state = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return state;
}
I tried researching myself, which is where I stumbled upon the MultipartEntity, but since I am to upload a simple JSON content through POST I didn't find this necessary to use. So how do I show how much progress is made in the upload process and also what is the total size of the JSON content ?? I sort of figured that I would have had to use the StringEntity ? Am I right ?
Initiate your progress bar as
private ProgressDialog pDialog;
On onPreExecute()
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(getParent());
pDialog.setMessage("Please wait ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
On onPostExecute()
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pDialog.dismiss();
}
For showing progress bar with percentage try ..
public class AndroidDownloadFileByProgressBarActivity extends Activity {
// button to show progress dialog
Button btnShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;
// File url to download
private static String file_url = "your_url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (ImageView) findViewById(R.id.my_image);
/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
}
});
}
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}

Android Strict Mode

I have written a simple code on JSON Parsing using AsyncTask. I'm just displaying the response in TextView. I don't know whether it is right or wrong. Its working on GingerBread and showing NetworkOnMainThreadException on JellyBean. If I use StrictMode, its working on JellyBean and getting force close on GingerBread. How to write the code which support above Android 3.0 and below Android 3.0.
public class MainActivity extends Activity {
TextView tv;
Button b;
InputStream is = null;
DefaultHttpClient client;
HttpGet get;
HttpResponse response;
HttpEntity entity;
StringBuffer buffer;
#SuppressLint("NewApi")
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
// StrictMode.setThreadPolicy(policy);
tv = (TextView) findViewById(R.id.texty);
b = (Button) findViewById(R.id.buttonGET);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyOperation mytask = new MyOperation();
mytask.execute();
}
});
}
private class MyOperation extends AsyncTask<String, Void, String> {
ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
client = new DefaultHttpClient();
get = new HttpGet("http://www.google.com");
try {
response = client.execute(get);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
entity = response.getEntity();
try {
is = entity.getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = null;
do {
try {
line = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buffer.append(line);
} while (line != null);
tv.setText(buffer);
}
}
}
public class MainActivity extends Activity {
TextView tv;
Button b;
InputStream is = null;
DefaultHttpClient client;
HttpGet get;
HttpResponse response;
HttpEntity entity;
StringBuffer buffer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//StrictMode.ThreadPolicy policy = new
// StrictMode.setThreadPolicy(policy);
tv = (TextView) findViewById(R.id.texty);
b = (Button) findViewById(R.id.buttonGET);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyOperation mytask = new MyOperation();
mytask.execute();
}
});
}
private class MyOperation extends AsyncTask<String, Void, String> {
ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
StringBuffer buffer = new StringBuffer();
// TODO Auto-generated method stub
client = new DefaultHttpClient();
get = new HttpGet("http://www.google.com");
try {
response = client.execute(get);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
entity = response.getEntity();
try {
is = entity.getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String line = null;
do {
try {
line = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buffer.append(line);
} while (line != null);
return buffer.tostring();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
tv.setText(result);
}}
}
otherwise you are running the read line operation in main thread
Make the InputStream is and Entity entity local field variables in the doInBackground() as return as result the string that you wanna set on the TextView...and on the onPostExecute() you just get the result (the string) and set it in the TextView straight on.
You should read inputStream data in doInBackground function, not in the onPostExecute. So construct StringBuffer in doInBackground append all lines to it and return StringBuffer.toString as result. In onPostExecute you will get what string as parameter.

Categories

Resources