Can you show me why these methods are out of scope? - java

I am using a tutorial to create a download class and it uses a progress dialog. The show and dissmiss methods are in protected classes inside of the asynchTask class. The IDE is telling me that it can not resolve them
public class DownloadHandler {
private Context mContext;
public String filename;
private String remotePath;
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
public DownloadHandler(String rp, String f, Context c) throws Exception {
mContext = c;
remotePath = rp;
filename = f;
}
private void startDownload() {
String url = "http://example.com/"+remotePath+"/"+filename+".pdf";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//===================showDialog can not be resolved============================
showDialog(DIALOG_DOWNLOAD_PROGRESS);
//========================================================================
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lengthOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
//write it to the internal storage
OutputStream output = new FileOutputStream(filename+".pdf");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lengthOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
//=========dismissDialog can not be resolved ==================
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
//=============================================================
}
}
}
Does it have something to do with the protected class?

showDialog and dismissDialog are in the Activity class. In the tutorial, it shows that the class Download extends activity, which the inner class can then use.
Have Download extend Activity. As for the methods being deprecated, this is because you should be using a DialogFragment. Apparently, the tutorial you are following is outdated, and you should look into how to use a DialogFragment

Related

How to Cast Fragment to Async Constructor?

I want to cast SlideshowDialogFragment to context in my asynctask in DdownloadTask.java but when i write
final DownloadTask downloadTask = new
DownloadTask(myActivity.this);
SlideshowDialogFragment instead of myActivity , android show warning and say
warning android
i don't know what am i do ?? thx for help me
public class SlideshowDialogFragment extends DialogFragment{
ArrayList<Image> images;
ViewPager viewPager;
MyViewPagerAdapter myViewPagerAdapter;
TextView lblCount,lblTitle,lblDate;
Button btn_set;
Button btn_download;
int selectedPostition;
DownloadManager downloadManager;
public static ProgressDialog mProgressDialog;
static SlideshowDialogFragment newInstance(){
SlideshowDialogFragment f=new SlideshowDialogFragment();
return f;
}
#Override
public View onCreateView (LayoutInflater inflater,ViewGroup container,Bundle saveInstanceState)
{
View v=inflater.inflate(R.layout.fragment_image_slider,container,false);
viewPager=(ViewPager)v.findViewById(R.id.view_pager);
lblTitle=(TextView)v.findViewById(R.id.title);
lblDate=(TextView)v.findViewById(R.id.date);
btn_set=(Button)v.findViewById(R.id.btn_set);
btn_download=(Button)v.findViewById(R.id.btn_download);
images=(ArrayList<Image>) getArguments().getSerializable("images");
selectedPostition=getArguments().getInt("position");
myViewPagerAdapter=new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int
positionOffsetPixels) {
displayInfo(position);
//setWallpaper(position);
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
setCurrentItem(selectedPostition);
btn_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
download(selectedPostition);
}
});
return v;
}
void download (int position){
Image image=images.get(position);
String large = image.getlarge();
final DownloadTask downloadTask = new
DownloadTask(**SlideshowDialogFragment**.this);
downloadTask.execute(large);
}
And this is DownloadTask Activity with constructor i write AsyncTask in this class:
public class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager)
context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context,"خطای دانلود "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"دانلود با موفقیت انجام شد",
Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/tabriz.jpg");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
}
what am i do for casting SlideshowDialogFragment to Async ?
You need to pass a Context as you defined your constructor like that. A Fragment does not have a Context, but the Activity has it. Since Fragment is a part of an Activity you can access it with
SlideshowDialogFragment.this.getActivity();
You could also use it directly with DownloadTask(getActivity())

Progress indicator on RecyclerView

I work with a RecyclerView that looks like this.
I use an AsyncTask for managing the downloads. I use this button so that each item in the list of cards can have the progress of the respective download. I am not sure how to report the status of the download to the RecyclerView. How do I get this to post updates to the cards?
The async downloader code is this
public class DownloadFileFromURL extends AsyncTask<String, String, String> {
private final String resourceType;
public DownloadFileFromURL(String resourceType) {
super();
this.resourceType = resourceType;
// do stuff
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//showDialog(progress_bar_type);
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
// pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
String fileName = url.toString().substring(url.toString().lastIndexOf('/') + 1);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lengthOfFile = connection.getContentLength();
Log.d("lengthofFile", String.valueOf(lengthOfFile));
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
String destinationDirectory ="";
if(resourceType.equals(SyncUtil.IMAGE_ZIP)) {
destinationDirectory= SyncUtil.TMP;
}
if(resourceType.equals(SyncUtil.VIDEOFILE)) {
destinationDirectory = SyncUtil.VIDEO;
}
File mFolder = new File(AppController.root.toString() + File.separator+destinationDirectory);
if (!mFolder.exists()) {
mFolder.mkdir();
}
OutputStream output = new FileOutputStream(AppController.root.toString()+File.separator+destinationDirectory+File.separator
+ fileName);
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) / lengthOfFile));
output.write(data, 0, count);
}
output.flush();
// closing streams
output.close();
input.close();
if(resourceType.equals(SyncUtil.IMAGE_ZIP)) {
BusProvider.getInstance().post(new ZipDownloadComplete(fileName,resourceType));
}
if(resourceType.equals(SyncUtil.VIDEOFILE)) {
// BusProvider.getInstance().post(new VideoDownloadComplete(fileName));
}
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
}
}
The RecyclerView adapter is here
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final Video video = videosList.get(position);
holder.title.setText(video.getTitle());
holder.description.setText(video.getDescription());
holder.downloadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url ="http://"+ AppController.serverAddr +":"+AppController.port +"/video/"+video.getUrl()+video.getExtension();
DownloadFileFromURL downloadFileFromURL = new DownloadFileFromURL(SyncUtil.VIDEOFILE);
downloadFileFromURL.execute(url,video.getTitle(),video.getDescription());
}
});
holder.bind(video,listener);
}
Though its not a very good solution but in my case I got that working. I'm just sharing my thoughts with some sample code snippet.
I assume you're showing the download progress with a ProgressBar. So take an instance of the ProgressBar in your adapter and pass the reference to your AsyncTask.
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final Video video = videosList.get(position);
holder.title.setText(video.getTitle());
holder.description.setText(video.getDescription());
holder.downloadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url ="http://"+ AppController.serverAddr +":"+AppController.port +"/video/"+video.getUrl()+video.getExtension();
// Pass the progressBar here. You might have to set it as a final variable.
DownloadFileFromURL downloadFileFromURL = new DownloadFileFromURL(SyncUtil.VIDEOFILE, holder.progressBar);
downloadFileFromURL.execute(url,video.getTitle(),video.getDescription());
}
});
holder.bind(video,listener);
}
Now modify your constructor of the AsyncTask like this.
public DownloadFileFromURL(... , ProgressBar mProgressbar) {
this.mProgressbar = mProgressbar;
this.mProgressbar.setProgress(0);
this.mProgressbar.setMax(100);
}
Add onProgressUpdate in your AsyncTask
protected void onProgressUpdate(Integer... values) {
mProgressbar.setProgress(values[0]);
}
Now in your doInBackground calculate the file size and publish the progress after a certain amount of file is downloaded.
protected void doInBackground() throws IOException {
try {
// Establish connection
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
final String contentLengthStr = connection.getHeaderField("content-length");
InputStream input = connection.getInputStream();
String data1 = f.getPath();
FileOutputStream stream = new FileOutputStream(data1);
byte data[] = new byte[4096];
int count;
int progressCount = 0;
while ((count = input.read(data)) != -1) {
stream.write(data, 0, count);
progressCount = progressCount + count;
int progress = (int) (((progressCount * 1.0f) / Integer.parseInt(contentLengthStr)) * 10000);
// Publish your progress here
publishProgress(progress);
}
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Note:
Passing the original reference of your views is not a very good solution. I would rather set a BroadcastReceiver in my activity and would publish a broadcast with the specific item position in the publishProgress function. So that when the broadcast is received in the main activity, I could call notifyDatasetChanged to take progress effect in the list.

Download PDF not working

In my application, I have an expandablelistview and I want to open a PDF downloaded from the internet when I click on a specific child. The problem is that the pdf file (Read.pdf) is always empty, meaning that the download is not working.
Downloader Class:
public class Downloader {
public static void DownloadFile(String fileURL, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Part of the Activity:
private void registerClick() {
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
if ((groupPosition == 0) && (childPosition == 0)){
File file = new File(Environment.getExternalStorageDirectory()+File.separator+"IAVE", "Read.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile("https://www.cp.pt/StaticFiles/Passageiros/1_horarios/horarios/PDF/lx/linha_cascais.pdf", file);
AbrirPDF.showPdf();
} else {
}
return false;
}
});
}
I think the OpenPDF (AbrirPDF) doesn't have any problem, but I will post it...
public class AbrirPDF {
public static void showPdf()
{
File file = new File(Environment.getExternalStorageDirectory()+File.separator+"IAVE/Read.pdf");
PackageManager packageManager = ContextGetter.getAppContext().getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ContextGetter.getAppContext().startActivity(intent);
}
}
Thank you.
Ideally, your download should happen in a separate thread to avoid locking your app.
Here is an example that also includes a progress bar.
public class MainActivity extends Activity {
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
private static String file_url = "https://www.cp.pt/StaticFiles/Passageiros/1_horarios/horarios/PDF/lx/linha_cascais.pdf";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadFileFromURL().execute(file_url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
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;
}
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/2011.kml");
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;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
}
}
}

Android: can not show dialog from AsyncTask class

I've builded Updates class for my Android app. It works fine except Download inner AsyncTask-class.
I wanted to display progress dialog in LoadingActivity while file is downloading.
Firstly, I invoke the Updates class in onCreate method. As a parameter I send activity context. Then in Updates class constructor I invoke Check inner class (AsyncTask), which parse JSON response from URL (works properly) and invoke Download (next Updates inner class) and here it's problem.
When I'm trying to create ProgressDialog object, the compiler throws:
04-01 02:53:56.864 24393-24425/pl.com.mpkostrowiec.schedule E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:197)
at android.os.Handler.<init>(Handler.java:111)
at android.app.Dialog.<init>(Dialog.java:107)
at android.app.AlertDialog.<init>(AlertDialog.java:114)
at android.app.AlertDialog.<init>(AlertDialog.java:98)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at pl.com.mpkostrowiec.schedule.DownloadAsync.<init>(DownloadAsync.java:30)
at pl.com.mpkostrowiec.schedule.Updates$Check.doInBackground(Updates.java:128)
at pl.com.mpkostrowiec.schedule.Updates$Check.doInBackground(Updates.java:74)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:838)
I thought that ProgressDialog constructor can't access context variable from Updates class, so I tried to send it as parameter, but it doesn't resolve the problem.
LoadingActivity class:
package pl.com.mpkostrowiec.schedule;
import ...
public class LoadingActivity extends Activity {
private final Preferences preferences = new Preferences(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading);
preferences.savePreference("Preferences", "firstRun", "1");
// Check if first run
if (preferences.readPreference("Preferences", "firstRun").equals("0")) {
System.out.println("****************** Not first run");
} else {
// Create directory
File dir = this.getDir("Versions", MODE_PRIVATE);
new Updates(this);
}
}
}
Update class:
package pl.com.mpkostrowiec.schedule;
import ...
interface AfterExecuteListener {
public void afterDownload(String[] versionData, int type);
}
public class Updates implements AfterExecuteListener{
private static VersionsTable versionsTable;
private Context context;
public static Boolean status_current = false;
public static Boolean status_new = false;
private final int TYPE_CURRENT = 0;
private final int TYPE_NEW = 1;
private static final String URL = "http://www.mpkostrowiec.com.pl/preview/";
private static final String GET_VERSIONS = "includes/android/versions.php";
private static final String RESOURCES = "resources/android/versions/";
private static final String EXTENSION = ".db";
public Updates(Context context) {
this.context = context;
versionsTable = new VersionsTable(this.context);
new Check(TYPE_CURRENT).execute();
}
public final void afterDownload(String[] versionData, int type) {
// Add version data to DB
versionsTable.open();
versionsTable.add(versionData);
versionsTable.close();
// Set status
if (type == TYPE_CURRENT) {
System.out.println("****************** Downloaded: " + type);
status_current = true;
} else if (type == TYPE_NEW) {
System.out.println("****************** Downloaded: " + type);
status_new = true;
}
Schedule();
}
private void Schedule() {
if (status_current) {
if (status_new) {
System.out.println("****************** SUCCESS");
} else {
new Check(TYPE_NEW).execute();
}
}
}
private class Check extends AsyncTask<String, Integer, String> {
public AfterExecuteListener mListener;
private int type;
public Check(int type) {
this.type = type;
}
#Override
protected String doInBackground(String... Url) {
String[] typeStr = {"current", "new"};
// Get versions form URL
JSONObject json = null;
String versions = null;
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost(URL + GET_VERSIONS);
try {
response = myClient.execute(myConnection);
versions = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONObject jObject = new JSONObject(versions);
json = jObject.getJSONObject(typeStr[type]);
if (json.length() > 1) {
String[] versionData = {json.getString("id"),
json.getString("name"),
json.getString("expDate")};
versionsTable.open();
Boolean idExist = versionsTable.check(versionData[0]);
versionsTable.close();
// Check version
if (!idExist) {
// Start downloading
Download download = new Download(versionData, type);
download.setListener(Updates.this);
download.execute(URL + RESOURCES + versionData[0] + EXTENSION);
}
} else {
// If array contains only false field then do not update
if (type == TYPE_CURRENT) {
Updates.status_current = true;
} else if (type == TYPE_NEW) {
Updates.status_new = true;
}
Schedule();
}
} catch ( JSONException e) {
e.printStackTrace();
}
return null;
}
}
private class Download extends AsyncTask<String, Integer, String> {
public ProgressDialog mProgressDialog;
public AfterExecuteListener mListener;
private String[] versionData;
private int type;
public Download(String[] versionData, int type) {
this.versionData = versionData;
this.type = type;
// Create progress dialog
mProgressDialog = new ProgressDialog(context);
// Set your progress dialog Title
mProgressDialog.setTitle("Updating...");
// Set your progress dialog Message
mProgressDialog.setMessage("Update in progress. Please wait.");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Show progress dialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... Url) {
try {
java.net.URL url = new URL(Url[0]);
URLConnection connection = url.openConnection();
connection.connect();
// Detect the file lenghth
int fileLength = connection.getContentLength();
// Locate storage location
String filepath = context.getApplicationInfo().dataDir + "/Versions";
// Download the file
InputStream input = new BufferedInputStream(url.openStream());
// Save the downloaded file
OutputStream output = new FileOutputStream(filepath + "/" + versionData[0] + ".db");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// Publish the progress
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
// Close connection
output.flush();
output.close();
input.close();
} catch (Exception e) {
// Error Log
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// Update the progress dialog
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
// Dismiss the progress dialog
mProgressDialog.dismiss();
mListener.afterDownload(versionData, type);
}
private void setListener(AfterExecuteListener listener) {
mListener = listener;
}
}
}

How to add AsyncTask in an HttpURLConnection?

I'm establishing a server connection, my problem is that I need to put an AsyncTask on my code, because its not working in sdk version 10 up. I don't want to use the StrictMode.ThreadPolicy.
public class TestConnection extends Activity {
#Override
public void onCreate(Bundle cbundle) {
super.onCreate(cbundle);
ConnectivityManager aConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo aNetworkInfo = aConnectivityManager.getActiveNetworkInfo();
if (aNetworkInfo != null && aNetworkInfo.isConnected()){
Toast.makeText(this, "Internet Connected", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "Internet Connection Timeout", Toast.LENGTH_LONG).show();
}
URL aURL;
/* Will be filled and displayed later. */
String aString = null;
/* We will show the data we read in a TextView. */
TextView aTextView = new TextView(this);
try {
/* Define the URL we want to load data from. */
aURL = new URL(
"http://url");
/* Open a connection to that URL. */
final HttpURLConnection aHttpURLConnection = (HttpURLConnection) aURL.openConnection();
/* Define InputStreams to read from the URLConnection. */
InputStream aInputStream = aHttpURLConnection.getInputStream();
BufferedInputStream aBufferedInputStream = new BufferedInputStream(
aInputStream);
/* Read bytes to the Buffer until there is nothing more to read(-1) */
ByteArrayBuffer aByteArrayBuffer = new ByteArrayBuffer(50);
int current = 0;
while ((current = aBufferedInputStream.read()) != -1) {
aByteArrayBuffer.append((byte) current);
}
/* Convert the Bytes read to a String. */
aString = new String(aByteArrayBuffer.toByteArray());
} catch (Exception aException) {
/* On any Error we want to display it. */
aString = aException.getMessage();
}
/* Show the String on the GUI. */
aTextView.setText(aString);
this.setContentView(aTextView);
}
}
private class ConnectionTask extends AsyncTask<String, Void, String>{
#Override
protected byte[] doInBackground(String... urls) {
try {
aURL = new URL(
urls[0]);
/* Open a connection to that URL. */
final HttpURLConnection aHttpURLConnection = (HttpURLConnection) aURL.openConnection();
/* Define InputStreams to read from the URLConnection. */
InputStream aInputStream = aHttpURLConnection.getInputStream();
BufferedInputStream aBufferedInputStream = new BufferedInputStream(
aInputStream);
/* Read bytes to the Buffer until there is nothing more to read(-1) */
ByteArrayBuffer aByteArrayBuffer = new ByteArrayBuffer(50);
int current = 0;
while ((current = aBufferedInputStream.read()) != -1) {
aByteArrayBuffer.append((byte) current);
}
/* Convert the Bytes read to a String. */
aString = new String(aByteArrayBuffer.toByteArray()); } catch (IOException e) {
Log.d(TAG, e.toString());
}
return aString;
}
#Override
protected void onPostExecute(String result) {
// result is what you got from your connection
aTextView.setText(result);
}
}
How to call it:
ConnectionTask task = new ConnectionTask();
String[] params = new String[2];
params[0] = url;
params[1] = somethingelseifneeded;
task.execute(params);
In oncreate() u can use like this::
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
new MyAsynTask().execute(null, null, null);
}
Then in AsynTask do as well::
class MyAsynTask extends AsyncTask<Long, Integer, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected <Type> doInBackground(Long... params) {
URL ur_url = newURL(http://....)
// do the works on url.....
return <tuped>result;
}
#Override
protected void onPostExecute(Integer result) {
// set the results in Ui
}
}
Refer below code
new FetchRSSFeeds().execute();
private class FetchRSSFeeds extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(HomeActivity.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
protected void onPreExecute() {
this.dialog.setMessage(getResources().getString(
R.string.Loading_String));
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
/**
* Write your URL connection code and fetch data here
*/
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
/* Show the String on the GUI. */
aTextView.setText(aString);
this.setContentView(aTextView);
}
}

Categories

Resources