You can see that I'm appending tvStatus (TextView) in onPostExecute and after remove my progressDialog box. When I debug my code I can see that the value is set in tvStatus but it doesn't show on the screen.
Also my progressDialog stops rotating after the onPostExecute function is called.
Does any one know why and how to solve?
This is set in the onCreate method:
tvStatus = (TextView) this.findViewById(R.id.tvStatus);
Code:
public class TcpTask extends AsyncTask<Void, Void, Integer> {
#Override
protected Integer doInBackground(Void... params) {
try {
//set up a Connection
Socket s = new Socket("88.26.249.133", TCP_SERVER_PORT);
InputStream inputstream = (s.getInputStream());
DataInputStream in = new DataInputStream(inputstream);
DataOutputStream out = new DataOutputStream(s.getOutputStream());
s.setSoTimeout(20*1000);
//prepare output message
outBuffer[0] = 48;
outBuffer[1] = 51;
outBuffer[2] = 49;
outBuffer[3] = 49;
outBuffer[4] = 0;
outBuffer[5] = 0;
//send output message
out.write(outBuffer);
out.flush();
//To check in logCat
Log.i("TcpTask", "sent: " + outBuffer);
//check # available data
//and use it as byte length
avail = in.available();
byte[] inBuffer = new byte[avail];
//accept server response
while ((nob = in.read(inBuffer)) != -1) {
}
//close stream
in.close();
for (int i = 7; i < avail-7; i += 2) {
lowByte = inBuffer[i];
highByte = inBuffer[i+1];
if (lowByte < 0) {
result = lowByte + 256 + (highByte * 256);
} else {
result = lowByte + (highByte * 256);
}
}
//close connection
s.close();
//To Check in logCat
Log.i("TcpTask", "received: " + inBuffer);
// if the host name could not be resolved into an IP address.
} catch (UnknownHostException e) {
e.printStackTrace();
Log.i("myStatus", "TcpClient: Host name could not be resolved");
// if an error occurs while creating the socket.
} catch (IOException e) {
e.printStackTrace();
Log.i("myStatus", "TcpClient: ERROR");
} finally {
Log.i("TcpTask", "TCPClient: Finished");
}
return result;
}
#Override
protected void onPostExecute(Integer result) {
tvStatus.append(Integer.toString(result) + System.getProperty("line.separator"));
if (myStatus.this.progDialog != null) {
myStatus.this.progDialog.dismiss();
}
}
}
tvStatus.setText(tvStatus.getText().toString+(Integer.toString(result) + System.getProperty("line.separator")));
This is how you set the Text value to the textView
use
tsStatus.setText(result+" "+ System.getProperty("line.separator");
Related
public class PreviewDownload extends AsyncTask<String, Void, String> {
public static final String TAG = "PreviewDownload";
public String inputPath = null;
public String outputFolder = null;
public IRIssue issue = null;
#Override
protected String doInBackground(String... parms) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
issue = Broker.model.issueDataStore.getIRIssue(parms[0]);
outputFolder = IRConstant.issueFolder(issue.year, issue.month, issue.day, issue.pubKey);
try {
inputPath = IRConstant.downloadFile(issue.year, issue.month, issue.day, issue.pubKey, "preview", "0");
URL url = new URL(inputPath);
Log.d (TAG,"input: " + inputPath);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
return null;
// return "Server returned HTTP " + connection.getResponseCode()
// + " " + connection.getResponseMessage();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(outputFolder + "/preview.zip");
Log.d (TAG,"output: " + output);
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
} catch (Exception e) {
// return e.toString();
return null;
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return outputFolder;
}
#Override
protected void onPostExecute(String outputFolder) {
// TODO Auto-generated method stub
super.onPostExecute(outputFolder);
if (outputFolder != null) {
File zipFile = new File (outputFolder + "/preview.zip");
if (Utils.unzip(outputFolder,outputFolder + "/preview.zip" )) {
zipFile.delete();
issue.isThumbDownloaded = 1;
} else {
issue.isThumbDownloaded = 0;
}
} else {
Toast.makeText(Broker.launcherActivity.getBaseContext(), R.string.wordCantDownload, Toast.LENGTH_LONG).show();
issue.isThumbDownloaded = 0;
}
issue.updateProgress(issue.progress);
}
}
Here is the downloader I implemented , the problem is , when the network lost, the output become null and show error message, however, if I would like to retry two times before showing error message, are there any way to do this? If I perfer not to pass in an object instead of string ,is it not recommended? thanks
What prevents you from re-instanciating and re-executing a "Downloader" from your catch blocks in case of errors ?
You could use a single common shared object between dowloader instances to count the attempts, or better, pass a parameter to each of them. In the catch block, you would then retry if you didn't reach the limit, and increase the value passed to a new downloader... Something recursive.
int expectedLength = connection.getContentLength();
can you compare with the expectedLength & downloaded length and retry?
I am using the following code to request a response from a webserver. The server sends a malformed response without headers which causes a ClientProtocolException. I have tried to use inspectors but they are not called before the exception is fired. I cannot change the server (it is within an embedded device, ALFA router R36).
Any suggestions to deal with this problem (btw: the code works perfect if the server response is well-formed)
Thanks in advance, Ton
class httpRequestTask extends AsyncTask <Integer, Integer, Integer> {
StringBuffer respTxt = new StringBuffer("");
int reqCode = 0;
protected Integer doInBackground(Integer... requestCode) {
Integer reqStatus = 0;
String url = "http://192.168.2.1/";
String authString = ("admin:admin");
switch( reqCode = requestCode[0].intValue()){
case Constants.HTTP_GET_STATUS_INFO: url += "/adm/status_info.asp"; break;
case Constants.HTTP_SCAN: url += "/goform/getUsbStaBSSIDListForm"; break;
}
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
HttpResponse response;
request.setURI( new URI( url));
request.addHeader("Authorization", "Basic " + Base64.encodeToString(authString.getBytes(),Base64.NO_WRAP));
response = client.execute(request);
reqStatus = response.getStatusLine().getStatusCode();
String line;
BufferedReader in = new BufferedReader( new InputStreamReader(response.getEntity().getContent()));
while((line = in.readLine()) != null) respTxt.append(line);
} catch ( ClientProtocolException e){
Log.e("ALFA", "HTTPReq:ClientProtocolException " + e.toString());
} catch ( IOException e){
Log.e("ALFA", "HTTPReq:IOException " + e.toString());
} catch ( Exception e){
Log.e("ALFA", "HTTPReq:Exception " + e.toString());
}
return reqStatus;
}
protected void onPostExecute(Integer reqStatus) {
Intent intent = new Intent(Constants.HTTP_RESPONSE);
intent.putExtra( "reqCode", reqCode);
intent.putExtra( "reqStatus", reqStatus);
intent.putExtra( "rspTxt", respTxt.toString());
getBaseContext().sendBroadcast(intent);
}
}
Looking further to find a solution to the problem I found a suggestion to use a socket to request the server. I used Fiddler in combination with a browser on my PC to examine the data send to and received from the buggy server and read an article on Wikipedia, explaining the HTTP protocol. With that info and by using a Socket, I wrote a very basic httpRequestHandler than deals with the miss formed response from the buggy web server.
class httpSocketRequest extends AsyncTask<Integer, Integer, Integer> {
StringBuffer respTxt = new StringBuffer("");
int reqCode = 0;
int reqStatus = 0;
protected Integer doInBackground(Integer... requestCode) {
String ip = "192.168.2.1";
String path = "";
String authString = ("admin:admin");
Socket socket = null;
switch( reqCode = requestCode[0].intValue()){
case Constants.HTTP_GET_STATUS_INFO: path = "adm/status_info.asp"; break;
case Constants.HTTP_SCAN: path = "goform/getUsbStaBSSIDListForm"; break;
}
try {
socket = new Socket( ip, 80);
PrintWriter out = new PrintWriter( socket.getOutputStream());
out.println( "GET http://" + ip + "/" + path + " HTTP/1.0");
out.println( "Authorization: Basic " + Base64.encodeToString(authString.getBytes(),Base64.NO_WRAP));
out.println( "");
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
int lineCnt = 0;
while((line = in.readLine()) != null){
if( lineCnt >= 0){
lineCnt++;
if(lineCnt == 1){ // first line should start with "HTTP/1.x " followed by a 3 digit status
if( line.length() > 12 && line.substring(0, 6).equals("HTTP/1")){
int p = line.indexOf(" ");
reqStatus = Integer.parseInt(line.substring(p+1, p+4));
continue;
} else { // not a well formed response
lineCnt = -1; // just put everything into respTxt
reqStatus = 200; // and assume everything went OK
}
} else if( lineCnt > 1){ // process rest of headers
if( line.length() == 0){
lineCnt = -1; // done with headers
} else {
// TODO insert code to process other headers
}
continue;
}
}
respTxt.append(line + "\n");
}
} catch (Exception e) {
Log.e("ALFA", "HTTPReq:Exception " + e.toString());
} finally {
try {
if( socket != null) socket.close();
} catch (IOException e) {
Log.e("ALFA", "HTTPReq:Exception closing socket" + e.toString());
}
}
return reqStatus;
}
protected void onPostExecute(Integer reqStatus) {
Intent intent = new Intent(Constants.HTTP_RESPONSE);
intent.putExtra( "reqCode", reqCode);
intent.putExtra( "reqStatus", reqStatus);
intent.putExtra( "rspTxt", respTxt.toString());
getBaseContext().sendBroadcast(intent);
}
}
I have a text file on a server (right now on a local server by WAMP in c:/wamp/www/android/sample.txt ) and an android application with 3 activity that read data through the WiFi.
The first one get the address (on local host use 10.0.2.2/android/sample.txt) and go to activity2. In activity2 I have a button that goes to activity3.
code is third activity:
private InputStream OpenHttpConnection(String urlString) throws Exception {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection)) {
throw new IOException("NOT an HTTP Connection!");
}
try {
HttpURLConnection httpCon = (HttpURLConnection) conn;
httpCon.setAllowUserInteraction(false);
httpCon.setInstanceFollowRedirects(true);
httpCon.setRequestMethod("GET");
httpCon.connect();
response = httpCon.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpCon.getInputStream();
Log.d("myerr", response + "");
}
} catch (Exception e) {
Log.d("myerr2", e.getLocalizedMessage());
throw new IOException("Error Connection!");
}
return in;
}
private String DownloadText(String URL) {
int BUFFER_SIZE = 2000;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
} catch (Exception e) {
Log.d("myerr", e.getLocalizedMessage());
return "";
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer)) > 0) {
String readString = String
.copyValueOf(inputBuffer, 0, charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
} catch (Exception e) {
Log.d("myerr", e.getLocalizedMessage());
return "";
}
return str;
}
private class DownloadTextTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return DownloadText(urls[0]);
}
protected void onPostExecute(String result) {
Global.readedDataFromFile=result;
//Toast.makeText(DrawRhActivity.this,"Result: "+Global.readedDataFromFile, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_draw_rh);
String user_address = Global.ip_address;
new DownloadTextTask().execute(user_address);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("Value: " + Global.readedDataFromFile);
}
I also define some global variable in Global.java .
AND HERE IS MY PROBLEM:
The 3rd activity doesn't show data on textview at the first time. but when I back to 2nd activity and hit the button my data loaded.
Why AsyncTask doesn't show result first time and how to fix this?
Thanks for your attention.
tv.setText("Value: " + Global.readedDataFromFile);
write this line in onPostExecute
protected void onPostExecute(String result) {
Global.readedDataFromFile=result;
//Toast.makeText(DrawRhActivity.this,"Result: "+Global.readedDataFromFile, Toast.LENGTH_LONG).show();
tv.setText("Value: " + Global.readedDataFromFile);
}
Solution:
put tv.setText("Value: " + Global.readedDataFromFile); in your onPostExecute method.
Explaination:
AsyncTask runs on separate thread instead of your UI thread.
so when it is being executed Global.readedDataFromFile may be empty.and when execution completes it goes in onPostExecute method and now Global.readedDataFromFile have some value stored in it.
Issue:
you are setting the text instantly after calling new DownloadTextTask().execute(user_address);
so it may happen that the AsyncTask is not completed yet and Global.readedDataFromFile is empty.
Reference:
AsyncTask
I hope it will be helpful !!
the problem lies within your onCreate function:
String user_address = Global.ip_address;
new DownloadTextTask().execute(user_address);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("Value: " + Global.readedDataFromFile);
First you start a task, then you want to set your views, but your task is not finished.
You have to set the views with the result of your task in to onPostExecute of the task.
Keep your DownloadTextTask &
Trying this code in your Activity
DownloadTextTask textTask = new DownloadTextTask();
textTask.execute(user_address);
String strDownloaded = "";
try {
strDownloaded = textTask.get();
} catch (Exception e) {
Log.e("DownloadTextTask", "Error: " + e.getMessage());
}
Since Google analytics can raise many privacy concerns, I implemented an events logger.
My first idea is to track user's generated events into a logfile and then send them back to the server that will perform the analysis of data for the System Administrator and Application Engineers.
For the moment the idea is to instantiate the Logger into an Application or a Service class and use those elements onCreate and onDestroy to safely handle the LogFile.
The solution is quite simple:
Open file
Append to it every time an event is generated
Once the a MAX_NUM_LINES is reached, send the log to the server (possibly I'll zip the text file I am generating)
I wonder if there's anything already baked there in the wild I am unaware of that you might know (something like ACRA).
Every contribution will be appreciated.
Here my implementation.
However any better version is much appreciated.
The TSG objet is just a static class that I use as time manager.
Use the code and improve it as long as you repost / edit the modifications.
public class Logger {
private BufferedWriter logFile;
private String nameFile;
public int fileLines;
private File fTemp;
private timeStampGenerator TSG;
private int LOG_LINES_LIMIT = 100;
private Object mutex;
public enum EventType {
BUTTON_PRESSED,
PAGE_VIEWED,
LOADED_ACTIVITY,
GENERIC_EVENT
}
public Logger (String fileName) throws IOException {
nameFile = fileName;
createLogFile();
fileLines = countLines();
TSG = new timeStampGenerator();
// This is our mutex to access to the file
mutex = new Object();
}
public void createLogFile() throws IOException{
fTemp = new File (nameFile);
if (!fTemp.exists()) {
fTemp.createNewFile();
}
logFile = new BufferedWriter(new FileWriter(nameFile, true));
}
public void LogEvent(EventType event, String comment, String value) {
String line = "";
line += TSG.getTimestampMillis();
line += ",";
line += event.name();
line += ",";
if (comment != "") {
line += comment.replaceAll(",", ";");
} else {
line += " ";
}
line += ",";
if (value != "") {
line += value.replaceAll(",", ";");
} else {
line += " ";
}
line += "\n";
synchronized (mutex) {
try {
logFile.append(line);
} catch (IOException e) {
// Do wathever you want here
}
fileLines++;
}
}
public int countLines() //throws IOException
{
InputStream is;
try {
is = new BufferedInputStream(new FileInputStream(nameFile));
} catch (FileNotFoundException e1) {
//let's consider it an empty file
return 0;
}
int count = 0;
boolean empty = true;
try {
int readChars = 0;
byte[] c = new byte[1024];
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n')
++count;
}
}
} catch(IOException e) {
// Do wathever you want here
}
try {
is.close();
} catch (IOException e) {
// Do wathever you want here
}
return (count == 0 && !empty) ? 1 : count;
}
public boolean isLimitReached() {
return (fileLines >= LOG_LINES_LIMIT);
}
public void close () {
flush();
try {
logFile.close();
} catch (IOException e) {
// Do wathever you want here
}
}
/**
* clear the content of the file
*/
public void clearFile() {
synchronized (mutex) {
if ( fTemp.delete() ) {
try {
createLogFile();
} catch (IOException e1) {
// Do wathever you want here
}
}
}
}
/**
* Get the full content of the file
* #return the content
*/
public String getContent() {
StringBuffer fileData = new StringBuffer();
synchronized (mutex) {
try {
BufferedReader reader = new BufferedReader(new FileReader( nameFile ));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
} catch (IOException e) {
// Do wathever you want here
}
}
return fileData.toString();
}
public void flush() {
try {
logFile.flush();
} catch (IOException e) {
// Do wathever you want here
}
}
}
I'm downloading a file from a server and for some reason i can't determine, the downloaded file size doesn't match the original file size. Here's my code.
private class dl extends AsyncTask<String,Integer,Void>
{
int size;
#Override
protected Void doInBackground(String... arg0) {
// TODO Auto-generated method stub
try{
URL myFileUrl = new URL("http://10.0.2.2:8080/testdlapps/chrome-beta.zip");
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setConnectTimeout(5000);
conn.connect();
InputStream is = conn.getInputStream();
size = conn.getContentLength();
Log.v("INFO---------------------", "size is " +size);
FileOutputStream fout1 = new FileOutputStream(Environment.getExternalStorageDirectory()+"/"+"xyz.zip");
BufferedOutputStream bos = new BufferedOutputStream(fout1);
byte[] b = new byte[1024]; int i=0, count=0;
while((count = is.read(b)) != -1)
{
bos.write(b,0,count);
i+=count;
publishProgress(i);
Log.v("INFO----------------------------",""+count);
}
fout1.close();
}catch(Exception e){
Log.v("INFO--------------------------","Error!!");
Log.v("INFO--------------------------",e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
tv.setText("downloaded " + progress[0] + "/" + size ); //tv is a TextView
}
}
When i run the app, after the download completes, count and size are the same but the actual file size i.e /mnt/sdcard/xyz.zip is always less than size. Any ideas what going wrong?
override onPostExecute and check if actually it finishes, perhaps here a code to download with resume support,
pay attention because if you press back the download may still run:
if (isCancelled())
return false;
in the loop is needed because the close() on the socket will hang on exit without you noticeing it
here is the code:
class DownloaderTask extends AsyncTask<String, Integer, Boolean>
{
private ProgressDialog mProgress;
private Context mContext;
private Long mFileSize;
private Long mDownloaded;
private String mDestFile;
public DownloaderTask(Context context, String path)
{
mContext = context;
mFileSize = 1L;
mDownloaded = 0L;
mDestFile = path;
}
#Override
protected void onPreExecute()
{
mProgress = new ProgressDialog(mContext);
mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgress.setMessage("Downloading...");
mProgress.setCancelable(true);
mProgress.setCanceledOnTouchOutside(false);
mProgress.setOnCancelListener(new DialogInterface.OnCancelListener()
{
#Override
public void onCancel(DialogInterface dialog)
{
DownloaderTask.this.cancel(true);
}
});
mProgress.show();
}
#Override
protected void onProgressUpdate(Integer... percent)
{
mProgress.setProgress(percent[0]);
}
#Override
protected Boolean doInBackground(String... urls)
{
FileOutputStream fos = null;
BufferedInputStream in = null;
BufferedOutputStream out = null;
AndroidHttpClient mClient = AndroidHttpClient.newInstance("AndroidDownloader");
try
{
HttpResponse response = null;
HttpHead head = new HttpHead(urls[0]);
response = mClient.execute(head);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
return false;
Boolean resumable = response.getLastHeader("Accept-Ranges").getValue().equals("bytes");
File file = new File(mDestFile);
mFileSize = (long) Integer.parseInt(response.getLastHeader("Content-Length").getValue());
mDownloaded = file.length();
if (!resumable || (mDownloaded >= mFileSize))
{
Log.e(TAG, "Invalid size / Non resumable - removing file");
file.delete();
mDownloaded = 0L;
}
HttpGet get = new HttpGet(urls[0]);
if (mDownloaded > 0)
{
Log.i(TAG, "Resume download from " + mDownloaded);
get.setHeader("Range", "bytes=" + mDownloaded + "-");
}
response = mClient.execute(get);
if ((response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) && (response.getStatusLine().getStatusCode() != HttpStatus.SC_PARTIAL_CONTENT))
return false;
if (mDownloaded > 0)
publishProgress((int) ((mDownloaded / mFileSize) * 100));
in = new BufferedInputStream(response.getEntity().getContent());
fos = new FileOutputStream(file, true);
out = new BufferedOutputStream(fos);
byte[] buffer = new byte[8192];
int n = 0;
while ((n = in.read(buffer, 0, buffer.length)) != -1)
{
if (isCancelled())
return false;
out.write(buffer, 0, n);
mDownloaded += n;
publishProgress((int) ((mDownloaded / (float) mFileSize) * 100));
}
} catch (Exception e)
{
e.printStackTrace();
return false;
} finally
{
try
{
mClient.close();
if (in != null)
in.close();
if (out != null)
out.close();
if (fos != null)
fos.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
return true;
}
#Override
protected void onCancelled()
{
finish();
}
#Override
protected void onPostExecute(Boolean result)
{
if (mProgress.isShowing())
mProgress.dismiss();
if (result)
// done
else
// error
}
}
If it is a chunked response, the content-length in the header will be a guess at best.