I want to start timer after clicking on Button and poll for every 3 secs.
I am using following code.
private EditText url;
private Button submit;
private TextView error;
String some_URL;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);
loadviews();
handler=new Handler();
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
some_URL="http://"+url.getText().toString();
getStatus();
}
}
});
private void getStatus() {
// TODO Auto-generated method stub
handler.postDelayed(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
new Class_Poll().execute(some_URL);
error.setText("ID:"+ID+"\n"+
"Name:"+name+"\n" +
"Type:"+type+"\n"+
"Status:"+Status+"\n"+
"Content:"+Content);
}
}, 3000);
}
}
private void loadviews() {
// TODO Auto-generated method stub
url=(EditText)findViewById(R.id.url);
submit=(Button)findViewById(R.id.Submit);
error=(TextView)findViewById(R.id.log);
error.setMovementMethod(new ScrollingMovementMethod());
}
private class Class_Poll extends AsyncTask<String, Void, Void>{
private final HttpClient Client = new DefaultHttpClient();
#Override
protected Void doInBackground(String... arg0) {
// TODO Auto-generated method stub
Content=executeHttpRequest(some_URL);
return null;
}
#Override
protected void onPostExecute(Void unused) {
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(Content);
ID=jsonResponse.optString("ID").toString();
name=jsonResponse.optString("Name").toString();
type=jsonResponse.optString("Type").toString();
Status=jsonResponse.optString("Status").toString();
error.setText("ID:"+ID+"\n"+
"Name:"+name+"\n" +
"Type:"+type+"\n"+
"Status:"+Status+"\n"+
"Content:"+Content);
} catch (JSONException e) {
error.setText(e.toString());
}
//Toast.makeText(getApplicationContext(), "ID:"+ID+" Name:"+name+" Type:"+type+" Status:"+Status, Toast.LENGTH_LONG).show();
}
}
public static String executeHttpRequest(String url)
{
HttpURLConnection urlConnection = null;
try
{
URL httpUrl = new URL(url);
urlConnection = (HttpURLConnection) httpUrl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.addRequestProperty("Accept", "text/html,text/xhtml,application/xhtml+xml,application/xml;");
urlConnection.setConnectTimeout(10000);
InputStream in = null;
try
{
in = urlConnection.getInputStream();
} catch (NullPointerException e)
{
Log.e("Check", "Request Failed, Check the url");
return null;
}
if (in != null)
{
in = new BufferedInputStream(in);
String response = readStream(in);
Log.e("Check", response + "");
if (response != null && !response.isEmpty())
{
// statusTrace.print(TAG, "Operation executed : " +
// isSuccess(response));
return response;
}
else
{
Log.e("Check", "Request Failed");
}
} else
;//statusTrace.print(TAG, "Request Failed");
} catch (IOException e)
{
Log.e("Check", "Error : " + e.toString());
//statusTrace.print("Error", "Network Error. Check connection and Tuxedo IP");
}
return null;
}
public static String readStream(InputStream in)throws IOException {
// TODO Auto-generated method stub
InputStreamReader is = new InputStreamReader(in);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(is);
String read = br.readLine();
while (read != null)
{
sb.append(read);
read = br.readLine();
}
return sb.toString();
}
error is TextView in which I am displaying some Text.
And I am invoking web service in Asyntask. So it is not executing asynchtask for delay of 3 seconds after button click.
I don't know where know what is the problem exactly. It should execute actually, my textview is not getting updated for each 3 seconds.
Timer runs on a different thread you should not invoke AsyncTask from a background thread.
Please read Threading rules #
http://developer.android.com/reference/android/os/AsyncTask.html
public void scheduleAtFixedRate (TimerTask task, long delay, long period)
Added in API level 1
Schedule a task for repeated fixed-rate execution after a specific delay has passed.
Parameters
task the task to schedule.
delay amount of time in milliseconds before first execution.
period amount of time in milliseconds between subsequent executions.
Throws
IllegalArgumentException if delay < 0 or period <= 0.
IllegalStateException if the Timer has been canceled, or if the task has been scheduled or canceled.
Your delay is 0. See this }, 0, 3000);
can you suggest me an alternative to this so that I can execute
AsynchTask at after 3 secs of delay??
I assume you want to invoke asynctask after a 3 sec delay
You can use a Handler
Handler handler = new Handler():
handler.postDelayed(new Runnable(){
#Override
public void run() {
// run something after 3 sec delay
}
}, 3000);
Edit:
public class MainActivity extends Activity
{
private EditText url;
private Button submit;
private TextView error;
String Content;
String some_URL;
Handler handler;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);
loadviews();
handler=new Handler();
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
some_URL="http://"+url.getText().toString();
getStatus();
}
});
}
private void getStatus() {
// TODO Auto-generated method stub
handler.postDelayed(new Runnable(){
#Override
public void run() {
new Class_Poll().execute(some_URL);
}
}, 3000);
}
private void loadviews() {
// TODO Auto-generated method stub
url=(EditText)findViewById(R.id.url);
submit=(Button)findViewById(R.id.Submit);
error=(TextView)findViewById(R.id.log);
error.setMovementMethod(new ScrollingMovementMethod());
}
private class Class_Poll extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... arg0) {
String _response;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(arg0[0]);
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
}catch(Exception e)
{
e.printStackTrace();
}
return _response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(result);
String ID=jsonResponse.optString("ID").toString();
String name=jsonResponse.optString("Name").toString();
String type=jsonResponse.optString("Type").toString();
String Status=jsonResponse.optString("Status").toString();
error.setText("ID:"+ID+"\n"+
"Name:"+name+"\n" +
"Type:"+type+"\n"+
"Status:"+Status+"\n"+
"Content:"+Content);
} catch (JSONException e) {
error.setText(e.toString());
}
}
}
}
Related
I want to create an application using PHP webservices which can download file from server.
This is my Detail class:
public class ImportExportDataDetails extends Activity {
int id;
Button btnback;
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
TextView txtname,tvfile1,tvfile2,tvdetail;
ImageView imgflag;
Button btnfile1,btnfile2;
String url1,url2,filenm1,filenm2;
private DefaultHttpClient httpclient;
private HttpPost httppost;
private ArrayList<NameValuePair> lst;
public static String[] image;
public static String[] name;
public static String[] file1;
public static String[] file2;
public static String[] fnm1;
public static String[] fnm2;
public static String[] detail;
private JSONArray users =null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_import_export_data_details);
Intent i=getIntent();
id=i.getIntExtra("id", 0);
txtname=(TextView)findViewById(R.id.txtname);
tvfile1=(TextView)findViewById(R.id.tvfile1);
tvfile2=(TextView)findViewById(R.id.tvfile2);
tvdetail=(TextView)findViewById(R.id.tvdetail);
imgflag=(ImageView)findViewById(R.id.imgflag);
btnfile1=(Button)findViewById(R.id.btnfile1);
btnfile2=(Button)findViewById(R.id.btnfile2);
btnback=(Button)findViewById(R.id.btnback);
btnback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i=new Intent(getApplicationContext(),ImportExportData.class);
startActivity(i);
}
});
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://kalalunsons.com/webservice/web-import-export-data-details.php?import_export=1");
lst=new ArrayList<NameValuePair>();
lst.add(new BasicNameValuePair("im_ex_data_id", Integer.toString(id)));
try {
httppost.setEntity(new UrlEncodedFormEntity(lst));
new details().execute();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
btnfile1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
startDownload();
}
});
}
private void startDownload() {
String url = url1;
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
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(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 lenghtOfFile = conexion.getContentLength();
// Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/file.xlsx");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
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(DIALOG_DOWNLOAD_PROGRESS);
}
}
class details extends AsyncTask<String, integer, String>{
String jsonstring;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
HttpResponse httpresponse=httpclient.execute(httppost);
jsonstring=EntityUtils.toString(httpresponse.getEntity());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonstring;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONObject JsonObject=null;
try {
JsonObject =new JSONObject(result);
JSONObject jobj=JsonObject.getJSONObject("0");
users=jobj.getJSONArray("import_export");
name=new String[users.length()];
image=new String[users.length()];
detail=new String[users.length()];
file1=new String[users.length()];
file2=new String[users.length()];
fnm1=new String[users.length()];
fnm2=new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo=users.getJSONObject(i);
name[i]=jo.getString("name");
image[i]=jo.getString("image");
detail[i]=jo.getString("details");
file1[i]=jo.getString("file");
file2[i]=jo.getString("file2");
fnm1[i]=jo.getString("file_name");
fnm2[i]=jo.getString("file_name");
txtname.setText(name[i]);
Picasso.with(getApplicationContext()).load(image[i]+"?import_export=1").into(imgflag);
tvdetail.setText(Html.fromHtml(detail[i]));
tvfile1.setText(fnm1[i]);
tvfile2.setText(fnm2[i]);
url1=file1[i];
url2=file2[i];
filenm1=tvfile1.getText().toString();
filenm1=filenm1.toLowerCase()+".xlsx";
}
//Toast.makeText(getApplicationContext(), url1, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
In that case the logcat doesn't display any error.when i run this code it start progress of downloading,when progress finished i check my sdcard folder but it not display any file.the file was downloaded successfully but it displays as binary format,what can i changes in my code.and how can i display it in the sdcard.
you can use some library for network calls:-
retrofit-
http://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/
also background and UI threads are separate threads. In UI thread, you can update your views and UI like toast messages and load an image.
here is a great article to learn about asynctask, read this first --
https://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/
Issue: you are showing Toast in doInBackground() which run in separate thread. Remove Toast message from doInBackground() method
If you wanna show some info,use logs instead of Toast
I'm coding the client side of an Android application which uses sockets. Since I'm new with AsyncTask, I coded something simple to test my understanding. Here is what I have, it seems to be correct:
public class Messaggi extends ActionBarActivity implements OnClickListener {
LinearLayout mLayout;
ScrollView scroll;
EditText writeMessage;
Button send;
Socket connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_messaggi);
mLayout = (LinearLayout) findViewById(R.id.linearVertical);
scroll = (ScrollView) findViewById(R.id.scrollView1);
writeMessage= (EditText)findViewById(R.id.ScriviMessaggio);
send= (Button)findViewById(R.id.invia);
send.setOnClickListener(this);
LavoraDietro asd = new LavoraDietro();
asd.execute();
}
#Override
public void onClick(View v) {
}
private void updateScroll(){
scroll.post(new Runnable() {
#Override
public void run() {
scroll.fullScroll(View.FOCUS_DOWN);
}
});
}
private TextView createNewTextView(String text) {
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText("Client: " + text);
return textView;
}
private class LavoraDietro extends AsyncTask<Void, Void, Boolean> {
String mex;
#Override
protected Boolean doInBackground(Void... params){
try {
InetAddress local = InetAddress.getByName("192.168.1.79");
Socket connection= new Socket(local , 7100);
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
output.writeUTF("Client: Server prova");
output.flush();
DataInputStream input = new DataInputStream(connection.getInputStream());
mex= input.readUTF();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}catch(Exception e){
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(result == true){
mLayout.addView(createNewTextView("Sono connesso al server"));
mLayout.addView(createNewTextView("I canali sono aperi.."));
mLayout.addView(createNewTextView(mex));
updateScroll();
}
else{
mLayout.addView(createNewTextView("ERRORE CONNESSIONE AL SERVER "));
updateScroll();
}
}
}
}
When the connection to the server is established, the client sends a test meesage and the server should send the same message to the client, where it is printed.
But my task is to establish the connection immediatly when the app is opened and send a message only when the button "send" is pressed. Is possible to create multiple AsyncTasks and make them work at the same time without crashing the application? If yes, can you please post an example of how can I do this?
EDITED CODE
This is my new code:
public class Messaggi extends ActionBarActivity implements OnClickListener {
LinearLayout mLayout;
ScrollView scroll;
EditText writeMessage;
Button send;
Socket connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_messaggi);
mLayout = (LinearLayout) findViewById(R.id.linearVertical);
scroll = (ScrollView) findViewById(R.id.scrollView1);
writeMessage= (EditText)findViewById(R.id.ScriviMessaggio);
send= (Button)findViewById(R.id.invia);
send.setOnClickListener(this);
LavoraDietro asd = new LavoraDietro();
asd.execute();
}
#Override
public void onClick(View v) {
CliccaInvia asd123 = new CliccaInvia();
asd123.execute(connection);
}
private void updateScroll(){
scroll.post(new Runnable() {
#Override
public void run() {
scroll.fullScroll(View.FOCUS_DOWN);
}
});
}
private TextView createNewTextView(String text) {
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText("Client: " + text);
return textView;
}
private class LavoraDietro extends AsyncTask<Void, Void, Socket> {
String mex;
#Override
protected Socket doInBackground(Void... params){
try {
InetAddress local = InetAddress.getByName("192.168.1.79");
connection= new Socket(local , 7100);
DataInputStream input = new DataInputStream(connection.getInputStream());
mex = input.readUTF();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return connection;
}
#Override
protected void onPostExecute(Socket result) {
super.onPostExecute(result);
if(result != null){
mLayout.addView(createNewTextView("Sono connesso al server"));
mLayout.addView(createNewTextView("I canali sono aperi.."));
mLayout.addView(createNewTextView(mex));
updateScroll();
}
else{
mLayout.addView(createNewTextView("ERRORE CONNESSIONE AL SERVER "));
updateScroll();
}
}
}
private class CliccaInvia extends AsyncTask<Socket, Void, Boolean>{
#Override
protected Boolean doInBackground(Socket... params) {
try {
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
output.writeUTF("Client: Server prova");
output.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(result == true){
mLayout.addView(createNewTextView("Message Sent"));
aggiornaScroll();
}
else{
mLayout.addView(createNewTextView("Error sending Mex "));
aggiornaScroll();
}
}
}
But this doesn't work.. :(
Well if you need to spawn a lot of tasks and keep track of them all you could do something like this
List<LavoraDietro> tasks = new ArrayList<LavoraDietro>();
LavoraDietro task = new LavoraDietro();
task.execute;
tasks.add(task);
then in your LavoraDietro in the onPostExecute
tasks.remove(this);
But there is a million different ways you could make connections if you want. I recommend Apache's library. http://hc.apache.org/httpclient-3.x/
Here is an example of how you might make a connection, just call this function from inside the background of your task.
public static InputStream getHTTPRequest(String url, ArrayList<NameValuePair> parameters, ArrayList<NameValuePair> headers)
{
final String TAG = "getHTTPRequest";
HttpGet getRequest = new HttpGet(url);
// attach all and any params
if (parameters != null && parameters.size() > 0)
{
HttpParams params = getRequest.getParams();
for (NameValuePair param : parameters)
{
params.setParameter(param.getName(), param.getValue());
}
getRequest.setParams(params);
}
// attach all and any headers
if (headers != null && headers.size() > 0)
{
for (NameValuePair header : headers)
{
getRequest.addHeader(header.getName(), header.getValue());
}
}
getRequest.addHeader("Content-type", "application/json");
getRequest.addHeader("Accept", "application/json");
DefaultHttpClient client = new DefaultHttpClient();
try
{
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
{
Log.d(TAG, "status not ok");
Log.d(TAG, "status = " + Integer.toString(statusCode));
Log.d(TAG, "url = " + getRequest.getURI().toString());
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
Log.d(TAG, "returning valid content");
return getResponseEntity.getContent();
} catch (IOException e)
{
Log.d(TAG, "IOException: getRequest.abort");
getRequest.abort();
}
return null;
}
I am having a trouble dismiss Progress Dialog if any exception occurs at doInBackground in my AsyncTask as it never reaches the onPostExecute and never dismiss the Progress Dialog which makes ANR.
Below is the code for AsyncTask
private class checkAS extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialogue;
#Override
protected void onPostExecute() {
// TODO Auto-generated method stub
super.onPostExecute();
dialogue.dismiss();
}
#Override
protected Void doInBackground(Void... params) {
//Long Network Task
return null;
}
#Override
protected void onPreExecute(Void result) {
// TODO Auto-generated method stub
super.onPreExecute(result);
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
}
My question is if any exception occurs at doInBackground how will I handle it and how onPostExecute will be called to dismiss the dialogue? I can not dismiss it on doInBackground. How to sync this up?
Try this..
Return something like string from doInBackground. If Exception came catch that assign string value error otherwise return success
private class checkAS extends AsyncTask<Void, Void, String>
{
ProgressDialog dialogue;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
#Override
protected String doInBackground(Void... params) {
//Long Network Task
String result;
try{
result = "success"
}
catch(Exception e){
result = "error";
}
return result;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result.equals("error"))
dialogue.dismiss();
else
// do something
}
}
You are creating dialog dialog in onPostExecute method it should be in onPreExecute method.
try this.
private class checkAS extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialogue;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogue = new ProgressDialog(MainActivity.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
#Override
protected Void doInBackground(Void... params) {
//Long Network Task
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialogue.dismiss();
}
}
#Override
protected String doInBackground(String... params)
{
System.out.println("check user profile");
try
{
}
catch (Exception e)
{
e.printStackTrace();
publishProgress((e.getMessage()));
}
return result;
}
#Override
protected void onProgressUpdate(String... values)
{
// TODO Auto-generated method stub
super.onProgressUpdate(values);
Toast.makeText(activity, values[0], Toast.LENGTH_LONG);
if(dialog != null && dialog.isShowing())
dialog.dismiss();
}
#SuppressLint("InlinedApi")
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(dialog != null && dialog.isShowing())
{
dialog.dismiss();
}
}
You may want to dismiss dialog in finally block of try catch construct.
i.e.
try {
...
} catch {
...
finally{
//dismiss dialog here.
}
first check whether the dialog is showing or not using this code you can check
if(dialog.isShowing())
dialog.dismiss();
And use Exception handling to avoid unknown Exceptions
private class checkAS extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
private static final String TAG = "checkAS";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 12000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 12000;
private int taskType = POST_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public checkAS(int taskType, Context mContext, String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
#SuppressWarnings("deprecation")
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
handleResponse(response);
pDlg.dismiss();
}
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost= new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
}
}
catch (Exception e) {
// display("Remote DataBase can not be connected.\nPlease check network connection.");
Log.e(TAG, e.getLocalizedMessage(), e);
return null;
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
public void handleResponse(String response)
{
//display("Response:"+response);
if(!response.equalsIgnoreCase(""))
{
JSONObject jso;
try {
//do your stuff
}
catch (JSONException e1) {
Log.e(TAG, e1.getLocalizedMessage(), e1);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
else
{
display("Could not able to reach Server!");
}
}
Try this:
private class checkAS extends AsyncTask<Void, Void, Boolean> {
ProgressDialog dialogue;
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
dialogue.dismiss();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
Thread.sleep(15000);
} catch (Exception e) {}
return true;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialogue = new ProgressDialog(Main.this);
dialogue.setTitle("Processing");
dialogue.setMessage("Getting Profile Information");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
}
This question already has an answer here:
how to fix getDataTask method error?
(1 answer)
Closed 9 years ago.
this is my code below which work perfectly only problem is not show toast mesage code is blast i want to display toast mesage if Status is 0 in this line if (status.equals("1"))
show toast message but code is blast if i comment Toast then code run perfectly help me what do i do??
public class thirdstep extends Activity {
ListView listCategory;
String status;
String message;
String MenuSelect;
ProgressBar prgLoading;
long Cat_ID;
String Cat_name;
String CategoryAPI;
int IOConnect = 0;
TextView txtAlert;
thirdstepAdapter cla;
static ArrayList<String> Category_ID = new ArrayList<String>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
ImageButton btnback = (ImageButton) findViewById(R.id.btnback);
listCategory = (ListView) findViewById(R.id.listCategory2);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new thirdstepAdapter(thirdstep.this);
new getDataTask().execute();
listCategory.setAdapter(cla);
btnback.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
Intent iGet = getIntent();
Cat_ID = iGet.getLongExtra("category_id", 0);
Cat_name = iGet.getStringExtra("category_name");
Toast.makeText(this, Cat_ID + Cat_name, Toast.LENGTH_SHORT).show();
MenuSelect = Utils.MenuSelect;
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(thirdstep.this,
fourthscreen.class);
iMenuList.putExtra("Cat_ID",Cat_ID);
iMenuList.putExtra("Menuitem", Category_ID.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void>{
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if((Category_ID.size() > 0) || IOConnect == 0){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
public void parseJSONData() {
CategoryAPI = Utils.MenuList + Cat_ID;
clearData();
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json = new JSONObject(str);
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
message = json2.getString("message");
if (status.equals("1")) {
JSONObject data = json.getJSONObject("data");
JSONArray school = data.getJSONArray("menu_groups");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
Category_ID.add(object.getString("id"));
Category_name.add(object.getString("title"));
Category_image.add(object.getString("image"));
}
}
else
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Your toast message is within the parseJsonData method which is called from the doInBackground method of your asynctask.
You can not update the user interface thread from a background thread.
You have two options here
1) You can publish the progress publishProgress(1) of the thread passing in an integer value to be used as a flag which you can pick up on in the onPublishProgress listener and show your toast there
or
2) As your method has finished by this point then make the parseJsonData set an integer variable global to the asynctask and in the onPostExecute method pass something back to the listener to indicate that a toast needs to be shown
Update based on comments
Replace
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
with
{
publishProgress(1);
}
Add the missing onProgressUpdate() method to your asynctask
#Override
protected void onProgressUpdate(Integer... percent) {
//Call your listeners.onProgressUpdate(percent) here and show the
//Or
super.onProgressUpdate(percent);
if (percent[0] == 1){
Toast.makeText(thirdstep.this, message, Toast.LENGTH_SHORT).show();
}
}
I'm not here to write your code for you. Do some research on how to properly write an async task and publish progress
Here is a good starting point
http://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/
You should be aware of orientation changes and how that will effect your asynctask (I avoid the pitfals of this by using a fragment
This is the design pattern I use for async tasks
http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html
But for handling web services, be nice to your users and let the android system work out when to download data etc and don't drain their battery and use a sync adapter with an intentservice instead of an asynctask. There are already too many crappy apps out there that take the asynctask approach for consuming web services. Please don't add yours to the list
Do it this way
http://developer.android.com/training/sync-adapters/creating-sync-adapter.html
It's a lot of extra learning curve but your a programmer right? You should be giving your users the best possible experience.
BTW You are getting down votes because you are demanding code to be written for you. I'm hoping this is just a language barrier and not an attitude problem.
Surround your Toast with this
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), message, Toast.LENGTH_SHORT).show();
}
});
I have a Login page where I want to authenticate the username and password from the database on the network. The problem is while doing the AsyncTask I want to return the username and password values. But this is not happening.
How do I return the values? Here is my login page code.
public class Login extends Activity {
Integer aaa=0;
Button b,b2;
RelativeLayout r;
TextView t, t2;
String str1, str2, username, password;
String A = null, B = null;
EditText et1, et2;
Dialog myDialog;
String FILENAME = "http://animsinc.com/query.php";
protected ProgressDialog dialog;
protected Handler h;
static InputStream in = null;
static JSONObject jObj = null;
static String json = "";
private static final String TAG_ID = "id";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_in);
Display display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight() / 4;
r = (RelativeLayout) findViewById(R.id.RL);
RelativeLayout.LayoutParams r = new RelativeLayout.LayoutParams(width,
height);
t = (TextView) findViewById(R.id.textView1);
t2 = (TextView) findViewById(R.id.textView2);
t.setOnClickListener(link);
t2.setOnClickListener(fgtpass);
et1 = (EditText) findViewById(R.id.editText1);
et2 = (EditText) findViewById(R.id.editText2);
b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(temp);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((et1.getText().length() == 0)
|| (et2.getText().length() == 0))
{
Toast.makeText(getApplicationContext(),
"Please enter correct details",Toast.LENGTH_LONG)
.show();
} else {
dialog = ProgressDialog.show(Login.this, "Loading",
"Please Wait...");
/* h = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
dialog.dismiss();
}
};
new Thread() {
#Override
public void run() {
super.run();
String st=startDownload();
try {
Thread.sleep(3000);
h.sendEmptyMessage(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();*/
Toast.makeText(getApplicationContext(),""+st,Toast.LENGTH_LONG).show();
String st=startDownload();
Toast.makeText(getApplicationContext(),"aaa="+aaa, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),""+st, Toast.LENGTH_LONG).show();
}
if ((et1.getText().toString().equals(username))&& (et2.getText().toString().equals(password)))
{
Intent openStartingPoint = new Intent(Login.this,
UserActivity.class);
startActivity(openStartingPoint);
}
}
});
}
private
String startDownload() {
String C = null;
new AppTask().execute(FILENAME);
aaa++;
return C;
}
private View.OnClickListener temp = new View.OnClickListener() {
public void onClick(View V) {
Intent openStartingPoint = new Intent(Login.this,
UserActivity.class);
startActivity(openStartingPoint);
}
};
private View.OnClickListener link = new View.OnClickListener() {
public void onClick(View V) {
Intent openStartingPoint = new Intent(Login.this,
ContactDetails.class);
startActivity(openStartingPoint);
}
};
private View.OnClickListener fgtpass = new View.OnClickListener() {
public void onClick(View V) {
myDialog = new Dialog(Login.this);
myDialog.setContentView(R.layout.emailpop);
myDialog.setTitle("Forgot Password");
myDialog.setCancelable(true);
// for save
Button ok = (Button) myDialog.findViewById(R.id.button1);
ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
myDialog.dismiss();
}
});
myDialog.show();
}
};
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public class AppTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
String is = null;
str1 = et1.getText().toString();
str2 = et2.getText().toString();
if (str1.length() > 0 && str2.length() > 0) {
A = str1;
B = str2;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://animsinc.com/query.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("username", str1));
nameValuePairs.add(new BasicNameValuePair("password", str2));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = EntityUtils.toString(entity);
JSONArray jArray = new JSONArray(is);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
username = jObject.getString("username");
password = jObject.getString("password");
aaa++;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return username;
}
}
}
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
So return value in doInBackground() , receive it in onPostExecute() and update ui accordingly.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeTest(MainActivity.this,result,1000).show();
//set result to textview
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// result is the value you return from doInBackground
String username = result;
}