When i use asynctask method, activity indicator does not work. AsyncTask method is used to download the image from URL and put on phone memory. Below is my code
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AsyncCallWS aws = new AsyncCallWS();
try {
retData = aws.execute().get();
Log.d(TAG, "STATUS is " + retData);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Close the window and go back to login page
Intent intent = new Intent(launchar.this, arcamera.class);
intent.putExtra("url", url_);
intent.putExtra(Strings.USERNAME, mUsername);
intent.putExtra(Strings.PASSWORD, mPassword);
intent.putExtra(Strings.COMP_ID, mCompId);
startActivity(intent);
}
});
My Async Method is below :
private class AsyncCallWS extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// Call the service
HttpConnectionHelper helper = new HttpConnectionHelper(
Constants.SERVICE_GETAR_URL);
final String REQUEST_DATA = String.format(
"<ReqData xmlns=\"http://www.ceolution.com/phone\"> "
+ "<key>%s|%s|%s</key>" + "</ReqData>", mUsername,
mPassword, mCompId);
try {
helper.setRequestMethod(HttpPost.METHOD_NAME);
helper.setPostData(REQUEST_DATA);
helper.setHeader("Content-Type", "application/xml");
int code = helper.getResponseCode();
if (Constants.LOG_ENABLED) {
Log.i(TAG, "Response code = " + code);
}
if (code == HttpURLConnection.HTTP_OK) {
String data = helper.getResponseData();
if (Constants.LOG_ENABLED) {
Log.v(TAG, "Response Data - " + data);
}
ARParser par = new ARParser();
String data_ = par.ParseAR(data);
Log.i(TAG, "RETURN DATA IS " + data_);
// Get Object
BufferedReader br = new BufferedReader(new StringReader(
data_));
InputSource is = new InputSource(br);
// Create XML Parser
ARXMLFormatter parser = new ARXMLFormatter();
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser sp = factory.newSAXParser();
XMLReader reader = sp.getXMLReader();
reader.setContentHandler(parser);
reader.parse(is);
myData = parser.itemList;
if (myData != null) {
String OutputData = "";
Location itemLocation = null;
for (Item item : myData) {
if (item != null) {
itemLocation = new Location("");
itemLocation.setLatitude(Double
.parseDouble(item.getLat()));
itemLocation.setLongitude(Double
.parseDouble(item.getLg()));
if (location != null) {
float distanceInMeters = itemLocation
.distanceTo(location);
Log.d(TAG, "distanceInMeters is "
+ distanceInMeters);
if (distanceInMeters <= Double
.parseDouble(item.getR())) {
// Must have to clean the directory
// before
// writing data
File savefilepath1 = new File(
COURSE_ZIP_FILE_PATH);
cleanDirectory(savefilepath1);
Image realData = null;
String imageName = "";
for (int k = 0; k < 8; k++) {
realData = null;
imageName = "";
switch (k) {
case 0: {
realData = item.getN();
imageName = "n.png";
break;
}
case 1: {
realData = item.getE();
imageName = "e.png";
break;
}
case 2: {
realData = item.getS();
imageName = "s.png";
break;
}
case 3: {
realData = item.getW();
imageName = "w.png";
break;
}
case 4: {
realData = item.getNe();
imageName = "ne.png";
break;
}
case 5: {
realData = item.getNw();
imageName = "nw.png";
break;
}
case 6: {
realData = item.getSe();
imageName = "se.png";
break;
}
case 7: {
realData = item.getSw();
imageName = "sw.png";
break;
}
}
url_[k] = realData.getL();
boolean status = false;
if (realData.getU() != ""
&& realData.getU() != null)
status = DownloadFile(
realData.getU()
.replace(
"http",
"https"),
imageName);
Log.d(TAG, "Download status is "
+ status);
}
Log.d(TAG,
"This is the item to processed");
return "SUCCESS";
}
OutputData = OutputData + item.toString();
} else
return "GPSISSUE";
} else
Log.e("Items", "No details");
}
Log.d(TAG, "OutputData data is " + OutputData);
}
return "NODATA";
}
} catch (Exception ex) {
ex.printStackTrace();
return "ERROR";
}
return "NODATA";
}
The XML file is below
<FrameLayout
android:id="#+id/laucnh_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" >
<ImageView
android:id="#+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="#drawable/launch"
android:onClick="#string/onClick"
android:scaleType="center" />
</FrameLayout>
Even i tried to put the activity indicator in onPreExecute() and onPostExecute() also does not work.
I am not sure what may be reason .
Please help.
You will have to publish updates from your asyncTask to the UI. Here is an example of it. So in the onProgressUpdate Function you can update the UI. I hope this helps.
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Related
In my app I am getting response from server and displayint it in listview, now what I am trying is when user click on listitem it should get position of it and need to send it to next activity, but it is not working.
Following is mt snippet code
btn_go.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getNetworkInfo(
ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED
|| connectivityManager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
// listView1.removeAllViews();
listView1.setAdapter(null);
arraylist_oper = new ArrayList<HashMap<String, String>>();
// listView1.notify();
new getOperationalControlList().execute();
} catch (Exception e) {
e.printStackTrace();
}
}
});
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
//qr = ((String) listView1.getItemAtPosition(position)).toString();
Intent intent=new Intent(OperationalControl.this,DispatchTracking.class);
intent.putExtra("arrow_val", "2");
intent.putExtra("qrcodes", qr);
Toast.makeText(OperationalControl.this, qr, Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
class getOperationalControlList extends AsyncTask<String, String, String> {
private String msg = "";
int register_error = 1;
JSONArray operation;
JSONObject obc;
String error;
String access_token, office_name, office_id;
String user_id;
String name;
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(OperationalControl.this);
progressDialog.setCancelable(true);
progressDialog.setMessage("Loading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(0);
progressDialog.show();
noresponse.setVisibility(View.GONE);
}
#Override
protected String doInBackground(String... params) {
JSONObject jsonObjSend;
String content = null;
arraylist_oper = new ArrayList<HashMap<String, String>>();
try {
consts.pref = getSharedPreferences("pref", MODE_PRIVATE);
consts.editor = consts.pref.edit();
String OperationalControlList_URL = ((consts.pref
.getString(consts.Base_URL,
consts.Base_URL)) + consts.OperationalControlList_URL);
Log.d("OperationalControlList_URL url:",
OperationalControlList_URL);
arraylist = new ArrayList<HashMap<String, String>>();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(OperationalControlList_URL);
System.out.println("URL :-"
+ consts.OperationalControlList_URL.toString());
user_id = consts.pref.getString("user_id", "");
access_token = consts.pref.getString("access_token", "");
office_id = consts.pref.getString("office_id", "");
date = date_dropdown.getText().toString();
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(
5);
nameValuePair.add(new BasicNameValuePair("user_id", user_id));
nameValuePair.add(new BasicNameValuePair("access_token",
access_token));
nameValuePair.add(new BasicNameValuePair("filter", filter));
nameValuePair
.add(new BasicNameValuePair("office_id", office_id));
nameValuePair.add(new BasicNameValuePair("date", date));
// Encoding POST data
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println("USER_ID : " + user_id.toString());
System.out.println("access_token : "
+ access_token.toString());
System.out.println("filter : " + filter.toString());
System.out.println("office_id : " + office_id.toString());
System.out.println("date : " + date.toString());
content = EntityUtils.toString(entity);
Log.d("aaa", content);
jsonObjSend = new JSONObject(content.toString());
if (jsonObjSend.getString("status").equals("2")) {
register_error = 1;
error = jsonObjSend.getString("error");
if (error.equals("3")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("4")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("5")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("6")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("7")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("8")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("9")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("10")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("11")) {
msg = jsonObjSend.getString("message");
} else if (error.equals("12")) {
msg = jsonObjSend.getString("message");
} else {
msg = jsonObjSend.getString("message");
}
// {"status":1,"message":"There is no activity of the selected day and filtering otpions"}
} else if (jsonObjSend.getString("status").equals("1")) {
if (jsonObjSend.has("message"))
msg = jsonObjSend.getString("message");
// msg = jsonObjSend.getString("message");
register_error = 0;
operation = new JSONArray();
if (jsonObjSend.has("list")) {
operation = jsonObjSend.getJSONArray("list");
// arraylist_oper = new ArrayList<HashMap<String,
// String>>();
for (int i = 0; i < operation.length(); i++) {
map = new HashMap<String, String>();
qr = operation.getJSONObject(i)
.getString("qrcode");
type = operation.getJSONObject(i)
.getString("type").toString();
Log.d("Types", type);
String origin = operation.getJSONObject(i)
.getString("origin");
String destiny = operation.getJSONObject(i)
.getString("destiny");
String stop_status = operation.getJSONObject(i)
.getString("stop_status");
String stop_status_name = operation
.getJSONObject(i).getString(
"stop_status_name");
String stop_status_color = operation
.getJSONObject(i).getString(
"stop_status_color");
map.put("qrcode", qr);
map.put("type", type);
map.put("origin", origin);
map.put("destiny", destiny);
map.put("stop_status", stop_status);
map.put("stop_status_name", stop_status_name);
map.put("stop_status_color", stop_status_color);
// map.put("status_name", status_name);
arraylist_oper.add(map);
Log.d("qrcode:", qr + " type: " + type
+ " origine: " + origin);
}
} else {
msg = jsonObjSend.getString("message");
}
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
return content;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
if (error.equals("6")) {
Intent intent=new Intent(OperationalControl.this,LoginActivity.class);
startActivity(intent);
OperationalControl.this.finish();
}
try {
if (arraylist_oper.size() > 0) {
Operational_LazyAdapter adpt = new Operational_LazyAdapter(
getApplicationContext(), arraylist_oper);
listView1.setAdapter(adpt);
// Toast.makeText(getApplicationContext(), msg,
// Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Office não definir corretamente ou" + msg,
Toast.LENGTH_LONG).show();
noresponse.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Response
{"status":1,
"list":[{
"qrcode":"#00000757-00000277-700101-0000000040",
"type":"Tipo de Opera\u00e7\u00e3o: Chegada",
"origin":"Origem: ARMAMAR (757)",
"destiny":"Destino: REGUA (277)",
"stop_status":6,
"stop_status_name":"Finalizado",
"stop_status_color":"#cccccc"
},
{
"qrcode":"#00000278-00000277-700101-0000000041",
"type":"Tipo de Opera\u00e7\u00e3o: Chegada",
"origin":"Origem: LAMEGO (278)",
"destiny":"Destino: REGUA (277)",
"stop_status":6,
"stop_status_name":"Finalizado",
"stop_status_color":"#cccccc"
}]
}
On the Intent you create on the list item click listener you should add all variables you need.
In your case add
intent.putExtra("position", position);
In your DispatchTracking Activity use
int position = getIntent().getExtras().getInt("position");
Just you need to pass your HashMap Arraylist to next Activity. Like,
intent.putExtra("myList",arraylist_oper);
and in your next Activity just retrieve as
Intent intent = getIntent();
ArrayList<HashMap<String,String>> mylist = (ArrayList<HashMap<String, String>>)intent.getSerializableExtra("myList");
EDIT :
You need to pass your qrCode too next Activity
intent.putExtra("qrcodes", arraylist_oper.get(position).get("qrcode")));
Now retrieve in next activity as
String qrCode = intent.getStringExtra("qrcodes");
Now check your retrivable arraylist in your second activity using For loop.
for(int i=0; i < myList.size ; i++) {
if(qrCode.equals(myList.get(i).get("qrcode"))){
// get your data here you can get according to qrCode. Like
String density = myList.get(i).get("destiny"); // same for others
}
I google about few hours on this problem. But I cannot get the solution. Hence, hope anyone can give me some idea.
My problem is the async onPostExecute is not reached. However, whenever I restart my IIS 7.5 on my laptop. The async can work fine. After few times the async method is called repeatly, the async onPostExecute is not reached again, it took long time at the doInBackground, infinitely.
I put the try catch at the doInBackground, but there are no error is catched.
Thanks.
ActivityMain.java
#Override
protected void onCreate(Bundle savedInstanceState)
{
UpdateServingNo_EstimatedTime();
}
public void UpdateServingNo_EstimatedTime()
{
new AsyncTask<Void, Void, String>()
{
#Override
protected void onPreExecute()
{
ActivityMain.this.setProgressBarIndeterminateVisibility(true);
};
#Override
protected String doInBackground(Void... params)
{
String result = "0";
try
{
Service_eGiliran service = new Service_eGiliran();
servingNumCounter1 = service.GetCurrentServingNoByStatus("COUNTER1");
servingNumCounter2 = service.GetCurrentServingNoByStatus("COUNTER2");
servingNumRoom1 = service.GetCurrentServingNoByStatus("ROOM1");
servingNumRoom2 = service.GetCurrentServingNoByStatus("ROOM2");
servingNumRoom3 = service.GetCurrentServingNoByStatus("ROOM3");
servingNumPharmacy1 = service.GetCurrentServingNoByStatus("PHARMACY1");
servingNumPharmacy2 = service.GetCurrentServingNoByStatus("PHARMACY2");
avgScdCounter1 = service.GetAvgSecondsByStatus("COUNTER1")!=0 ? service.GetAvgSecondsByStatus("COUNTER1")/60: 0; // min = seconds/60
avgScdCounter2 = service.GetAvgSecondsByStatus("COUNTER2")!=0 ? service.GetAvgSecondsByStatus("COUNTER2")/60: 0;
avgScdRoom1 = service.GetAvgSecondsByStatus("ROOM1")!=0 ? service.GetAvgSecondsByStatus("ROOM1")/60: 0;
avgScdRoom2 = service.GetAvgSecondsByStatus("ROOM2")!=0 ? service.GetAvgSecondsByStatus("ROOM2")/60: 0;
avgScdRoom3 = service.GetAvgSecondsByStatus("ROOM3")!=0 ? service.GetAvgSecondsByStatus("ROOM3")/60: 0;
avgScdPharmacy1 = service.GetAvgSecondsByStatus("PHARMACY1")!=0 ? service.GetAvgSecondsByStatus("PHARMACY1")/60: 0;
avgScdPharmacy2 = service.GetAvgSecondsByStatus("PHARMACY2")!=0 ? service.GetAvgSecondsByStatus("PHARMACY2")/60: 0;
result = "1";
}
catch (Exception e)
{
result = e.getMessage();
}
return result;
}
#Override
protected void onPostExecute(String result)
{
ActivityMain.this.setProgressBarIndeterminateVisibility(false);
if(result.equals("1"))
{
//Update UI label serving number
lblCounter1Ticket.setText(Integer.toString(servingNumCounter1));
lblCounter2Ticket.setText(Integer.toString(servingNumCounter2));
lblRoom1Ticket.setText(Integer.toString(servingNumRoom1));
lblRoom2Ticket.setText(Integer.toString(servingNumRoom2));
lblRoom3Ticket.setText(Integer.toString(servingNumRoom3));
lblPharmacy1Ticket.setText(Integer.toString(servingNumPharmacy1));
lblPharmacy2Ticket.setText(Integer.toString(servingNumPharmacy2));
lblCounter1Time.setText(avgScdCounter1 + " min");
lblCounter2Time.setText(avgScdCounter2 + " min");
lblRoom1Time.setText(avgScdRoom1 + " min");
lblRoom2Time.setText(avgScdRoom2 + " min");
lblRoom3Time.setText(avgScdRoom3 + " min");
lblPharmacy1Time.setText(avgScdPharmacy1 + " min");
lblPharmacy2Time.setText(avgScdPharmacy2 + " min");
}
else
{
Toast.makeText(ActivityMain.this, "Error: "+result, Toast.LENGTH_SHORT).show();
}
}
}.execute();
}
Service_eGiliran.java is my webservice genereated java stub from www.wsdl2code.com by uploading the .asmx files.
Service_eGiliran.java
public int GetCurrentServingNoByStatus(String status, List<HeaderProperty> headers)
{
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.implicitTypes = true;
soapEnvelope.dotNet = true;
SoapObject soapReq = new SoapObject("http://tempuri.org/", "GetCurrentServingNoByStatus");
soapReq.addProperty("status", status);
soapEnvelope.setOutputSoapObject(soapReq);
HttpTransportSE httpTransport = new HttpTransportSE(url, timeOut);
try
{
if(headers != null)
{
httpTransport.call("http://tempuri.org/GetCurrentServingNoByStatus", soapEnvelope, headers);
}
else
{
httpTransport.call("http://tempuri.org/GetCurrentServingNoByStatus", soapEnvelope);
}
Object retObj = soapEnvelope.bodyIn;
if(retObj instanceof SoapFault)
{
SoapFault fault = (SoapFault) retObj;
Exception ex = new Exception(fault.faultstring);
if(eventHandler != null) eventHandler.Wsdl2CodeFinishedWithException(ex);
}
else
{
SoapObject result = (SoapObject) retObj;
if(result.getPropertyCount() > 0)
{
Object obj = result.getProperty(0);
if(obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j = (SoapPrimitive) obj;
int resultVariable = Integer.parseInt(j.toString());
return resultVariable;
}
else if(obj != null && obj instanceof Number)
{
int resultVariable = (Integer) obj;
return resultVariable;
}
}
}
}
catch (Exception e)
{
if(eventHandler != null) eventHandler.Wsdl2CodeFinishedWithException(e);
e.printStackTrace();
}
return -1;
}
LogCat
I have solved this problem by myself.
I modified web service's method into this way.
At the previous version, I do a lot of calls for the similar action. So I modified it and to grab all the data that I want with async to lower burden of server.
Maybe this is not the best solution.
But I hope that this post can help anyone who faced this similar issue.
After Modified Version (Async Task)
#Override
protected String doInBackground(Void... params)
{
String result = "";
try
{
Service_eGiliran service = new Service_eGiliran();
String strResultServingNo = service.GetAllServingNo();
String strResultAvgSeconds = service.GetAllAvgSeconds();
result = "1";
}
catch (Exception e)
{
result = e.getMessage();
}
return result;
}
Before Modified Version (Async Task)
#Override
protected String doInBackground(Void... params)
{
String result = "0";
try
{
Service_eGiliran service = new Service_eGiliran();
servingNumCounter1 = service.GetCurrentServingNoByStatus("COUNTER1");
servingNumCounter2 = service.GetCurrentServingNoByStatus("COUNTER2");
servingNumRoom1 = service.GetCurrentServingNoByStatus("ROOM1");
servingNumRoom2 = service.GetCurrentServingNoByStatus("ROOM2");
servingNumRoom3 = service.GetCurrentServingNoByStatus("ROOM3");
servingNumPharmacy1 = service.GetCurrentServingNoByStatus("PHARMACY1");
servingNumPharmacy2 = service.GetCurrentServingNoByStatus("PHARMACY2");
avgScdCounter1 = service.GetAvgSecondsByStatus("COUNTER1")!=0 ? service.GetAvgSecondsByStatus("COUNTER1")/60: 0; // min = seconds/60
avgScdCounter2 = service.GetAvgSecondsByStatus("COUNTER2")!=0 ? service.GetAvgSecondsByStatus("COUNTER2")/60: 0;
avgScdRoom1 = service.GetAvgSecondsByStatus("ROOM1")!=0 ? service.GetAvgSecondsByStatus("ROOM1")/60: 0;
avgScdRoom2 = service.GetAvgSecondsByStatus("ROOM2")!=0 ? service.GetAvgSecondsByStatus("ROOM2")/60: 0;
avgScdRoom3 = service.GetAvgSecondsByStatus("ROOM3")!=0 ? service.GetAvgSecondsByStatus("ROOM3")/60: 0;
avgScdPharmacy1 = service.GetAvgSecondsByStatus("PHARMACY1")!=0 ? service.GetAvgSecondsByStatus("PHARMACY1")/60: 0;
avgScdPharmacy2 = service.GetAvgSecondsByStatus("PHARMACY2")!=0 ? service.GetAvgSecondsByStatus("PHARMACY2")/60: 0;
result = "1";
}
catch (Exception e)
{
result = e.getMessage();
}
return result;
}
I have created a code to download multiple files showing a progressbar progress. This works perfectly, but now I want to deploy it to an external project (library itself) and I have problems.
My intention is to call "download" and when the download completes or returns 0 or 1. But being asynchronous the method returns the value before finishing., I tried to control it without success with "CountdownLatch" ...
Any idea?
The following code works, the problem is that the method "download" returns the value without waiting for it to finish the rest of code.
Main.java
if(MyLib.download(Main.this, url, nameFiles, "internal", "folderExtra") == 1){
System.out.println("SUCCESS DOWNLOAD!");
}else{
System.out.println("error download");
}
MyLib.java
/** DOWNLOADER WITH PROCESSDIALOG **/
ProgressDialog pDialog;
Context context;
String urlName;
String[] filesToDownload;
int downloadOK = -1;
int currentFile = -1;
int totalFiles = 0;
String typeStorage = "internal";
String folder = "";
CountDownLatch controlLatch;
public int download(Context ctx, String urlName, String[] filesToDownload, String typeStorage, String extraFolder ){
System.out.println("estoy en download");
this.context = ctx;
this.urlName = urlName;
this.filesToDownload = filesToDownload;
this.totalFiles = filesToDownload.length;
this.typeStorage = typeStorage;
/** Almacenamiento de la descarga - Interno o externo **/
if (typeStorage.equalsIgnoreCase("internal")) {
System.out.println("internal");
this.folder = context.getFilesDir().toString() + "/";
} else if (typeStorage.equalsIgnoreCase("external")) {
System.out.println("external");
}
/** COMPLETEMENTO DIRECTORIO/S OPCIONAL **/
if (extraFolder != null && extraFolder != "") {
folder += extraFolder;
}
System.out.println("FOLDER: " + folder);
File directoryFile = new File(folder);
if (!directoryFile.isDirectory()) {
if (!directoryFile.mkdir()) {
Toast.makeText(context, "No se puede crear el directorio o no existe", Toast.LENGTH_LONG).show();
}
}
pDialog = new ProgressDialog(context);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setTitle("Descargando recursos...");
// controlLatch = new CountDownLatch(1);
startDownload();
/*
try {
System.out.println("STOP");
controlLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
*/
return downloadOK;
}
private void startDownload() {
currentFile++;
System.out.println("startDownload!");
if (currentFile < totalFiles) {
pDialog.setMessage("Descargando " + (currentFile + 1) + " de " + totalFiles + "\n\n(..." + filesToDownload[currentFile] + ")");
System.out.println("startDownload currentFile +[" + currentFile + "] totalFiles [" + totalFiles + "]");
System.out.println("file: " + filesToDownload[currentFile].toString());
new DownloaderFile().execute(filesToDownload[currentFile]);
}
}
private class DownloaderFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
try {
File checkFile = new File(folder + params[0]);
if(!checkFile.exists()){
URL urlFinal = new URL(urlName+params[0]);
URLConnection connection = urlFinal.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(urlFinal.openStream());
OutputStream output = new FileOutputStream(folder + params[0]);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} else {
System.out.println("The file " + filesToDownload[currentFile] + " is downloaded" );
}
} catch (Exception e) {
e.printStackTrace();
return "error";
}
return "ok";
}
#Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("-1");
File checkFile = new File(folder + filesToDownload[currentFile]);
if(!checkFile.exists()){
System.out.println("pDialogShow");
pDialog.show();
}
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
pDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String res) {
System.out.println("10");
if (currentFile == (totalFiles - 1)) {
System.out.println("FINISH!!!!!!!!!!!!!!");
currentFile = 0;
pDialog.dismiss();
downloadOK = 1;
//controlLatch.countDown();
} else {
if (res.equals("ok")) {
startDownload();
} else {
System.out.println("error download");
downloadOK = 0;
}
}
}
}
It sounds like you want callback.
Your DownloaderFile class can take a listener interface which is implemented by whatever contains the DownloaderFile object. Call that listener inside onPostExecute().
It might look like this:
public class MyActivity extends Activity implements OnDownloadCompleteListener {
private void startDownload() {
//inside whatever method
Downloader downloader = new Downloader(this); //'this' implements OnDownloadCompleteListener
downloader.go();
}
#Override
public void onDownloadFinished(boolean success) {
//implementation
}
}
Inside Downloader:
//...
#Override
protected void onPostExecute(String res) {
onDownloadCompleteListener.onDownloadComplete(true);
}
The OnDownloadCompleteListener interface:
public interface OnDownloadCompleteListener {
public void onDownloadComplete(boolean success);
}
I have 2 projects: App Project and own library.
My project have this code:
main.java (MyProject)
...
// call method Lib.download()
String nameFiles[] = {"do.mp3","re.mp3","mi.mp3","billiejean.mp3"};
String url = "http://myweb.net/getfiles/";
if( Lib.download(Main.this, url, nameFiles, "internal", "folderExtra" ) == 1){
System.out.println("finish");
} else {
System.out.println("error download");
}
The problem is that Lib.download return the default value without waiting for it to finish the rest of code.
I'm trying controller this with Semaphore / CountDownLatch / whiles but it doesn't work and also i'm trying implement a callback but without success because classes for "download" must be out of my project. Any help?
The downloads are done correctly but the download method returns the value before completing the downloads ...
My intention is to call a method "download" from any activity, this launch the dialog process and the rest of my activity code does not run until this method "download" returns a value.
Lib.java (MyLib)
/** DOWNLOADER WITH PROCESSDIALOG **/
ProgressDialog pDialog;
Context context;
String urlName;
String[] filesToDownload;
int downloadOK = -1;
int currentFile = -1;
int totalFiles = 0;
String typeStorage = "internal";
String folder = "";
CountDownLatch controlLatch;
public int download(Context ctx, String urlName, String[] filesToDownload, String typeStorage, String extraFolder ){
this.context = ctx;
this.urlName = urlName;
this.filesToDownload = filesToDownload;
this.totalFiles = filesToDownload.length;
this.typeStorage = typeStorage;
/** Almacenamiento de la descarga - Interno o externo **/
if (typeStorage.equalsIgnoreCase("internal")) {
System.out.println("internal");
this.folder = context.getFilesDir().toString() + "/";
} else if (typeStorage.equalsIgnoreCase("external")) {
}
/** EXTRA OPTIONALL **/
if (extraFolder != null && extraFolder != "") {
folder += extraFolder;
}
File directoryFile = new File(folder);
if (!directoryFile.isDirectory()) {
if (!directoryFile.mkdir()) {
Toast.makeText(context, "problems create directory", Toast.LENGTH_LONG).show();
}
}
pDialog = new ProgressDialog(context);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setTitle("Descargando recursos...");
// controlLatch = new CountDownLatch(1);
startDownload();
/*
try {
System.out.println("STOP");
controlLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
*/
return downloadOK;
}
private void startDownload() {
currentFile++;
System.out.println("startDownload!");
if (currentFile < totalFiles) {
pDialog.setMessage("Descargando " + (currentFile + 1) + " de " + totalFiles + "\n\n(..." + filesToDownload[currentFile] + ")");
System.out.println("startDownload currentFile +[" + currentFile + "] totalFiles [" + totalFiles + "]");
System.out.println("file: " + filesToDownload[currentFile].toString());
new DownloaderFile().execute(filesToDownload[currentFile]);
}
}
private class DownloaderFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
try {
File checkFile = new File(folder + params[0]);
if(!checkFile.exists()){
URL urlFinal = new URL(urlName+params[0]);
URLConnection connection = urlFinal.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(urlFinal.openStream());
OutputStream output = new FileOutputStream(folder + params[0]);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} else {
System.out.println("The file " + filesToDownload[currentFile] + " is downloaded" );
}
} catch (Exception e) {
e.printStackTrace();
return "error";
}
return "ok";
}
#Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("-1");
File checkFile = new File(folder + filesToDownload[currentFile]);
if(!checkFile.exists()){
System.out.println("pDialogShow");
pDialog.show();
}
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
pDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String res) {
System.out.println("10");
if (currentFile == (totalFiles - 1)) {
System.out.println("FINISH!!!!!!!!!!!!!!");
currentFile = 0;
pDialog.dismiss();
downloadOK = 1;
//controlLatch.countDown();
} else {
if (res.equals("ok")) {
startDownload();
} else {
System.out.println("error download");
downloadOK = 0;
}
}
}
}
AsyncTasks would run at separate thread once your .execute() is called. Your calling line startDownload() will never wait for AsyncTask to return any value, what you can do is:
Implement some callback interface on your main activity, so that your onPostExecute method would be able to notify your main activity once the operation is finished.
As you're the one developing this library, consider moving the AsyncTask to your main activity, and leave very plain download functions (what in your doInBackground method) in the library.
Use LocalBroadcastManager to send a broadcast from your library, listen and react to it on your main.java
When I call asynctask function data is load and display in listview but whenever i go into this activity everytime that function execute and load data again. But I just want that function call only once and display in listview. So what is the solution for that.
This is My full class code:
public class Feed extends Fragment implements
PullToRefreshAttacher.OnRefreshListener {
Button btnSlider;
ListView lv;
String userid, success, message, eventType, feed_title, feed_desc,
timeDate, like, commemt, Feeduserid, photo, posted, hasLike,
latsId, noMore, feed_id, category_id, feedImg, result;
InputStream is;
ProgressDialog pDialog;
InterNetConnectionDetector isNet = new InterNetConnectionDetector(
getActivity());
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
FeedAdapter fdp;
HashMap<String, String> map;
private uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher mPullToRefreshAttacher;
int limit = 5;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
v = inflater.inflate(R.layout.feed, container, false);
if (android.os.Build.VERSION.SDK_INT > 8) {
StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(stp);
}
SharedPreferences pref = getActivity().getSharedPreferences("Login",
Activity.MODE_PRIVATE);
userid = pref.getString("user_id", "user_id");
btnSlider = (Button) v.findViewById(R.id.btnSlide);
lv = (ListView) v.findViewById(R.id.feed_ListView);
btnSlider.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
Sliding.viewActionsContentView.showActions();
} catch (Exception e) {
// TODO: handle exception
}
}
});
try {
if (fdp == null) {
new FeedData().execute();
} else {
lv.setAdapter(fdp);
}
} catch (Exception e) {
// TODO: handle exception
}
mPullToRefreshAttacher = new uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher(
getActivity(), lv);
// Set Listener to know when a refresh should be started
mPullToRefreshAttacher
.setRefreshListener((uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher.OnRefreshListener) this);
((LoadMore) lv)
.setOnLoadMoreListener(new com.example.getconnected.LoadImage.LoadMore.OnLoadMoreListener() {
public void onLoadMore() {
// Do the work to load more items at the end of list
// here
new LoadDataTask().execute();
}
});
return v;
}
/*
* #Override protected void onCreate(Bundle savedInstanceState) { // TODO
* Auto-generated method stub super.onCreate(savedInstanceState);
* setContentView(R.layout.feed);
*
* if (Build.VERSION.SDK_INT >= 8) { getActionBar().hide(); }
*
* if (android.os.Build.VERSION.SDK_INT > 8) {
*
* StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
* .permitAll().build(); StrictMode.setThreadPolicy(stp);
*
* }
*
* try { new FeedData().execute();
*
* } catch (Exception e) { // TODO: handle exception }
*
* SharedPreferences pref = getSharedPreferences("Login",
* Activity.MODE_PRIVATE); userid = pref.getString("user_id", "user_id");
*
* btnSlider = (Button) findViewById(R.id.btnSlide); lv = (ListView)
* findViewById(R.id.feed_ListView); btnSlider.setOnClickListener(new
* OnClickListener() {
*
* #Override public void onClick(View arg0) { // TODO Auto-generated method
* stub
*
* int width = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
* 40, getResources() .getDisplayMetrics());
* SlideoutActivity.prepare(getActivity(), R.id.inner_content, width);
* startActivity(new Intent(getActivity(), MenuActivity.class));
* getoverridePendingTransition(0, 0);
*
* } });
*
* mPullToRefreshAttacher = new PullToRefreshAttacher(getActivity(), lv);
*
* // Set Listener to know when a refresh should be started
* mPullToRefreshAttacher .setRefreshListener((OnRefreshListener)
* getActivity());
*
* ((LoadMore) lv) .setOnLoadMoreListener(new
* com.example.getconnected.LoadImage.LoadMore.OnLoadMoreListener() { public
* void onLoadMore() { // Do the work to load more items at the end of list
* // here new LoadDataTask().execute(); } }); }
*/
public class FeedData extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = ProgressDialog.show(getActivity(), "", "Loading..");
pDialog.setCancelable(true);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// data=jobj.toString();
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://www.sevenstarinfotech.com/projects/demo/GetConnected/api/feed.php?user_id="
+ userid + "&" + "limit=" + limit;
HttpPost httppost = new HttpPost(url);
Log.v("Feed Url:", url);
httppost.addHeader("Content-Type",
"application/x-www-form-urlencoded");
httppost.addHeader("app-key",
"b51bc98b4d6fd0456f7f1b17278415fa49de57d5");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
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();
result = sb.toString();
Log.v("Response is:", result);
} catch (Exception e3) {
Log.e("log_tag", "Error converting result " + e3.toString());
}
// parse json data
try {
JSONObject ja = new JSONObject(result);
JSONObject jdata = ja.getJSONObject("data");
success = jdata.getString("Success");
message = jdata.getString("Message");
latsId = jdata.getString("lastId");
noMore = jdata.getString("nomore");
JSONArray jArray = jdata.getJSONArray("Feeddetails");
for (int i = 0; i < jArray.length(); i++) {
map = new HashMap<String, String>();
JSONObject me = jArray.getJSONObject(i);
map.put("sucess", success);
map.put("message", message);
map.put("latsId", latsId);
map.put("noMore", noMore);
eventType = me.getString("type");
feed_id = me.getString("feed_id");
feed_title = me.getString("feed_title");
category_id = me.getString("category_id");
feed_desc = me.getString("feed_desc");
timeDate = me.getString("timeposted");
posted = me.getString("postedby");
like = me.getString("likes");
photo = me.getString("photo");
commemt = me.getString("comments");
Feeduserid = me.getString("user_id");
hasLike = me.getString("hasliked");
map.put("eventType", eventType);
map.put("feed_id", feed_id);
map.put("feed_title", feed_title);
map.put("category_id", category_id);
map.put("feed_desc", feed_desc);
map.put("timeDate", timeDate);
map.put("posted", posted);
map.put("like", like);
map.put("photo", photo);
map.put("commemt", commemt);
map.put("Feeduserid", Feeduserid);
map.put("hasLike", hasLike);
Log.v("Data:", feed_id + "/" + "/" + "/" + Feeduserid
+ "/" + "/" + "/" + like + "/" + "/" + "/"
+ commemt);
contactList.add(map);
}
Log.v("Length", contactList.size() + "");
} catch (Exception e1) {
Log.e("log_tag",
"Error in http connection " + e1.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
pDialog.dismiss();
fdp = new FeedAdapter(getActivity(), contactList);
lv.setAdapter(fdp);
}
}
#Override
public void onRefreshStarted(View view) {
/**
* Simulate Refresh with 4 seconds sleep
*/
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Notify PullToRefreshAttacher that the refresh has finished
mPullToRefreshAttacher.setRefreshComplete();
}
}.execute();
}
private class LoadDataTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
if (isCancelled()) {
return null;
}
// Simulates a background task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
limit += 5;
DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://www.sevenstarinfotech.com/projects/demo/GetConnected/api/feed.php?user_id="
+ userid + "&" + "limit=" + limit;
HttpPost httppost = new HttpPost(url);
Log.v("Feed Url:", url);
httppost.addHeader("Content-Type",
"application/x-www-form-urlencoded");
httppost.addHeader("app-key",
"b51bc98b4d6fd0456f7f1b17278415fa49de57d5");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
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();
result = sb.toString();
Log.v("Response is:", result);
} catch (Exception e3) {
Log.e("log_tag", "Error converting result " + e3.toString());
}
// parse json data
try {
JSONObject ja = new JSONObject(result);
JSONObject jdata = ja.getJSONObject("data");
success = jdata.getString("Success");
message = jdata.getString("Message");
latsId = jdata.getString("lastId");
noMore = jdata.getString("nomore");
JSONArray jArray = jdata.getJSONArray("Feeddetails");
for (int i = 0; i < jArray.length(); i++) {
map = new HashMap<String, String>();
JSONObject me = jArray.getJSONObject(i);
map.put("sucess", success);
map.put("message", message);
map.put("latsId", latsId);
map.put("noMore", noMore);
eventType = me.getString("type");
feed_id = me.getString("feed_id");
feed_title = me.getString("feed_title");
category_id = me.getString("category_id");
feed_desc = me.getString("feed_desc");
timeDate = me.getString("timeposted");
posted = me.getString("postedby");
like = me.getString("likes");
photo = me.getString("photo");
commemt = me.getString("comments");
Feeduserid = me.getString("user_id");
hasLike = me.getString("hasliked");
map.put("eventType", eventType);
map.put("feed_id", feed_id);
map.put("feed_title", feed_title);
map.put("category_id", category_id);
map.put("feed_desc", feed_desc);
map.put("timeDate", timeDate);
map.put("posted", posted);
map.put("like", like);
map.put("photo", photo);
map.put("commemt", commemt);
map.put("Feeduserid", Feeduserid);
map.put("hasLike", hasLike);
Log.v("Data:", feed_id + "/" + "/" + "/" + Feeduserid
+ "/" + "/" + "/" + like + "/" + "/" + "/"
+ commemt);
contactList.add(map);
}
pDialog.dismiss();
fdp = new FeedAdapter(getActivity(), contactList);
lv.setAdapter(fdp);
} catch (Exception e1) {
Log.e("log_tag",
"Error in http connection " + e1.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
// mListItems.add("Added after load more");
// We need notify the adapter that the data have been changed
fdp.notifyDataSetChanged();
// Call onLoadMoreComplete when the LoadMore task, has finished
((LoadMore) lv).onLoadMoreComplete();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
((LoadMore) lv).onLoadMoreComplete();
}
}
}
Better option is like, just declare your ADAPTER as public static in your ROOT class or in your activity. This will make single copy. And you are done with.
Suppose you have following structure.
ABC (ROOT/SPLASH) Activity -> class Feed extends Fragment
So basically you are calling Feed from ABC. Inside ABC, declare like
public class ABC...{
public static FeedAdapter fdp;
//.. all other stuffs
}
public class Feed...{
//.. to use that object delcared in ABC
ABC.fdp = new FeedAdapter(...);
}