id1385
یک شنبه 26 مرداد 1393, 12:21 عصر
با سلام
دوستان من در حال نوشتن یک برنامه هستم نه ایکه بخوام منتشر کنم صرفاً جهت یادگیری هستش، در این برنامه سعی می کنم از اینترنت فایلهایی با فرمت json بگیرم و ذخیره کنم
برای اینکه نخوام هرجا نیاز به AsyncTask شد مجدد اونو بنویسم بخاطر همین اونو توی یک کلاس قرار دادم، بعد اونو فراخونی میکنم تا اینجا مشکلی نیست
در ایکلیپس که برنامه رو فراخونی میکنم یعنی در اسپلش که فراخونی میکنم درست کار میکنه بعضی موقعها هم کار نمکینه و تو گوشی هم اصلاً وارد پراسس نمی شه!
یعضی وقتا هم کار میکنه، آیا این درسته که من در اسپلش اسکرینم اول از توی یک کلاس دیگه یه سری فعالیتها رو انجام بدم و منتظر پاسخ بشم و بعد وارد محیط اصلی بشم یا خیر ؟
اصولاً که باید درست باشه ولی کار نمیکنه
کد نوشته شده رو براتون میذارم امیدوارم که دوستان راهنمایی کنن.
ممنون
DownloadTask.java
//package name here
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map.Entry;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
public class DownloadTask extends AsyncTask < String, Integer, Boolean > {
private HashMap < String, String[] > sUrls;
private boolean running = true;
int sUrlCount = 0;
int sUrlActive = 0;
int sUrlDownloaded = 0;
int downloadedSize = 0;
int totalSize = 0;
int file_lenght = 0;
int file_downloaded = 0;
public DownloadTask(HashMap < String, String[] > urls) {
this.sUrls = urls;
}
@Override
protected Boolean doInBackground(String...arg0) {
sUrlCount = this.sUrls.size();
boolean Response = false;
Log.d("LOG", "Count is :" + sUrlCount);
for (Entry < String, String[] > entry: sUrls.entrySet()) {
if (this.isCancelled()) {
break;
}
String[] value = entry.getValue();
if (download(value)) {
sUrlDownloaded++;
Log.d("LOG", "FIle Downloaded");
} else {
Log.d("LOG", "Download ERROR OoPs");
}
}
if (sUrlCount == sUrlDownloaded) {
Response = true;
}
return Response;
}
// download file
private boolean download(String...sUrl) {
String URL = sUrl[0];
String FILE_PATH = sUrl[1];
Log.d("rt", "DOWNLOAD DETAILS: \n" + String.valueOf(URL));
Log.d("tag", "Url: " + URL);
Log.d("tag", "F path: " + FILE_PATH);
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
boolean is_downloaded_successfuly = false;
try {
sUrlActive++;
URL url = new URL(sUrl[0].replaceAll(" ", "%20"));
Log.d("TAG", "Strting Download: " + sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.d("CONECTION:\n", connection.getResponseCode() + " " + connection.getResponseMessage());
return false;
}
Log.d("D", "Connection is ok 200");
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(FILE_PATH);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1 && running) {
total += count;
if (fileLength > 0) {
file_lenght = fileLength;
file_downloaded = (((int) total) - fileLength);
publishProgress((int)(total * 100 / fileLength));
output.write(data, 0, count);
is_downloaded_successfuly = true;
}
}
} catch (Exception e) {
Log.d("ERROR", e.getMessage());
is_downloaded_successfuly = false;
} finally {
try {
if (output != null) output.close();
if (input != null) input.close();
} catch (IOException ignored) {}
if (connection != null) connection.disconnect();
}
return is_downloaded_successfuly;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
public void onCancel(DialogInterface dialog) {
this.cancel(true);
running = false;
}
@Override
protected void onProgressUpdate(Integer...progress) {
super.onProgressUpdate(progress);
}
@Override
protected void onPostExecute(Boolean result) {
//Toast.makeText(context,"Download Result is: " + result, Toast.LENGTH_LONG).show();
}
protected static String getFileName(String url) {
String fileName;
int slashIndex = url.lastIndexOf("/");
int qIndex = url.lastIndexOf("?");
if (qIndex > slashIndex) {
fileName = url.substring(slashIndex + 1, qIndex);
} else {
fileName = url.substring(slashIndex + 1);
}
if (fileName.contains(".")) {
fileName = fileName.substring(0, fileName.lastIndexOf("."));
}
return fileName;
}
}
usage :
String Create_folders_in = null, JsonFile = null;
HashMap < String, String[] > downloadList = new HashMap < String, String[] > ();
JsonFile = "/mnt/sdcard/"; //Create_folders_in + appFolders[0] ;
downloadList.put("1", new String[] {
"http://netneutralitymap.org/json/countries-BitTorrent.json", JsonFile + "a.json"
});
downloadList.put("2", new String[] {
"http://netneutralitymap.org/json/countries-POP.json", JsonFile + "b.json"
});
downloadList.put("3", new String[] {
"http://netneutralitymap.org/json/country--eMule.json", JsonFile + "c.json"
});
DownloadTask dn = new DownloadTask(downloadList);
isLoaded = dn.execute().get();
return isLoaded;
دوستان من در حال نوشتن یک برنامه هستم نه ایکه بخوام منتشر کنم صرفاً جهت یادگیری هستش، در این برنامه سعی می کنم از اینترنت فایلهایی با فرمت json بگیرم و ذخیره کنم
برای اینکه نخوام هرجا نیاز به AsyncTask شد مجدد اونو بنویسم بخاطر همین اونو توی یک کلاس قرار دادم، بعد اونو فراخونی میکنم تا اینجا مشکلی نیست
در ایکلیپس که برنامه رو فراخونی میکنم یعنی در اسپلش که فراخونی میکنم درست کار میکنه بعضی موقعها هم کار نمکینه و تو گوشی هم اصلاً وارد پراسس نمی شه!
یعضی وقتا هم کار میکنه، آیا این درسته که من در اسپلش اسکرینم اول از توی یک کلاس دیگه یه سری فعالیتها رو انجام بدم و منتظر پاسخ بشم و بعد وارد محیط اصلی بشم یا خیر ؟
اصولاً که باید درست باشه ولی کار نمیکنه
کد نوشته شده رو براتون میذارم امیدوارم که دوستان راهنمایی کنن.
ممنون
DownloadTask.java
//package name here
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map.Entry;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
public class DownloadTask extends AsyncTask < String, Integer, Boolean > {
private HashMap < String, String[] > sUrls;
private boolean running = true;
int sUrlCount = 0;
int sUrlActive = 0;
int sUrlDownloaded = 0;
int downloadedSize = 0;
int totalSize = 0;
int file_lenght = 0;
int file_downloaded = 0;
public DownloadTask(HashMap < String, String[] > urls) {
this.sUrls = urls;
}
@Override
protected Boolean doInBackground(String...arg0) {
sUrlCount = this.sUrls.size();
boolean Response = false;
Log.d("LOG", "Count is :" + sUrlCount);
for (Entry < String, String[] > entry: sUrls.entrySet()) {
if (this.isCancelled()) {
break;
}
String[] value = entry.getValue();
if (download(value)) {
sUrlDownloaded++;
Log.d("LOG", "FIle Downloaded");
} else {
Log.d("LOG", "Download ERROR OoPs");
}
}
if (sUrlCount == sUrlDownloaded) {
Response = true;
}
return Response;
}
// download file
private boolean download(String...sUrl) {
String URL = sUrl[0];
String FILE_PATH = sUrl[1];
Log.d("rt", "DOWNLOAD DETAILS: \n" + String.valueOf(URL));
Log.d("tag", "Url: " + URL);
Log.d("tag", "F path: " + FILE_PATH);
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
boolean is_downloaded_successfuly = false;
try {
sUrlActive++;
URL url = new URL(sUrl[0].replaceAll(" ", "%20"));
Log.d("TAG", "Strting Download: " + sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.d("CONECTION:\n", connection.getResponseCode() + " " + connection.getResponseMessage());
return false;
}
Log.d("D", "Connection is ok 200");
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(FILE_PATH);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1 && running) {
total += count;
if (fileLength > 0) {
file_lenght = fileLength;
file_downloaded = (((int) total) - fileLength);
publishProgress((int)(total * 100 / fileLength));
output.write(data, 0, count);
is_downloaded_successfuly = true;
}
}
} catch (Exception e) {
Log.d("ERROR", e.getMessage());
is_downloaded_successfuly = false;
} finally {
try {
if (output != null) output.close();
if (input != null) input.close();
} catch (IOException ignored) {}
if (connection != null) connection.disconnect();
}
return is_downloaded_successfuly;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
public void onCancel(DialogInterface dialog) {
this.cancel(true);
running = false;
}
@Override
protected void onProgressUpdate(Integer...progress) {
super.onProgressUpdate(progress);
}
@Override
protected void onPostExecute(Boolean result) {
//Toast.makeText(context,"Download Result is: " + result, Toast.LENGTH_LONG).show();
}
protected static String getFileName(String url) {
String fileName;
int slashIndex = url.lastIndexOf("/");
int qIndex = url.lastIndexOf("?");
if (qIndex > slashIndex) {
fileName = url.substring(slashIndex + 1, qIndex);
} else {
fileName = url.substring(slashIndex + 1);
}
if (fileName.contains(".")) {
fileName = fileName.substring(0, fileName.lastIndexOf("."));
}
return fileName;
}
}
usage :
String Create_folders_in = null, JsonFile = null;
HashMap < String, String[] > downloadList = new HashMap < String, String[] > ();
JsonFile = "/mnt/sdcard/"; //Create_folders_in + appFolders[0] ;
downloadList.put("1", new String[] {
"http://netneutralitymap.org/json/countries-BitTorrent.json", JsonFile + "a.json"
});
downloadList.put("2", new String[] {
"http://netneutralitymap.org/json/countries-POP.json", JsonFile + "b.json"
});
downloadList.put("3", new String[] {
"http://netneutralitymap.org/json/country--eMule.json", JsonFile + "c.json"
});
DownloadTask dn = new DownloadTask(downloadList);
isLoaded = dn.execute().get();
return isLoaded;