How do i make status of asynctask from running to finished? - android

I'm trying to implement AsyncTask outside the activity class. Now the issue is status of this asynctask class is always showing as running, how do i make it finished?
This is my activity class
protected void onCreate(Bundle savedInstanceState) {
employeeAsyncTask.execute(new String[] {url});
System.out.println("Status "+employeeAsyncTask.getStatus());
//employeeAsyncTask.cancel(true);
while(employeeAsyncTask.getStatus() == AsyncTask.Status.RUNNING){
}
while (employeeAsyncTask.getStatus()== AsyncTask.Status.FINISHED) {
System.out.println("hereeeeeeeeeeeeee");
ArrayList<Employee> list = employeeAsyncTask.getEmpList();
System.out.println("Size of list "+list);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capture);
}
This is my asynctask class
public class FetchEmployeeAsyncTask extends AsyncTask<String, Void, ArrayList>{
private ArrayList<Employee> empList = null;
private boolean done = false;
/**
* #return the done
*/
public boolean isDone() {
return done;
}
/**
* #param done the done to set
*/
public void setDone(boolean done) {
this.done = done;
}
#Override
protected ArrayList doInBackground(String... url) {
// TODO Auto-generated method stub
ArrayList<Employee> employees = null;
for(String employeeUrl : url){
employees = fetch(employeeUrl);
}
return employees;
}
private ArrayList<Employee> fetch(String url) {
// TODO Auto-generated method stub
ArrayList<Employee> employees = null;
String response = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
employees = EmployeeXMLParser.XMLfromString(response);
System.out.println("Size in fetch "+employees.size());
//System.out.println("Employee Name :: " + employees.get(0).getFirstName() + " " + employees.get(0).getLastName());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*catch (XmlPullParserException e) {
// TODO Auto-generated catch block
System.out.println("Error parsing the response :: " + response);
e.printStackTrace();
}*/
return employees;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
done = false;
}
#Override
public void onPostExecute(ArrayList employeeList){
setEmpList(employeeList);
System.out.println("in post execxute "+employeeList.size());
done = true;
}
public ArrayList<Employee> getEmpList() {
return empList;
}
public void setEmpList(ArrayList<Employee> empList) {
this.empList = empList;
}
}
I'm unable to figure out what should be included in onPostExecute().

Add a constructor that takes the activity as parameter and stores it in a field:
private MyActivity activity;
public FetchEmployeeAsyncTask(MyActivity activity) {
this.activity = activity;
}
Then in the onPostExecute method you can pass back the employee list:
#Override
public void onPostExecute(ArrayList employeeList) {
activty.onEmpListLoaded(employeeList);
}
And in your activity implement onEmpListLoaded to do whatever needs to be done.

Related

Android currency converter application

I'm working on a big program for Android and I'm trying to get the currency converter part of the program to work. For full disclosure: I found it from http://firstamong.com/building-android-currency-converter/, and it's a tutorial on how to build a real-time currency converter. I'll post the code in question followed by the logcat. The error that occurs is when I try to convert from one currency to another, the application says it was forced to stop. However, the "Invalid" portion works (the case where both currency fields are the same.) Any help would truly be appreciated:
Code:
public class currency_converter extends Activity {
public int to;
public int from;
public String [] val;
public String s;
public Handler handler;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_currency_converter);
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
Spinner s2 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.name, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
val = getResources().getStringArray(R.array.value);
s1.setAdapter(adapter);
s2.setAdapter(adapter);
s1.setOnItemSelectedListener(new spinOne(1));
s2.setOnItemSelectedListener(new spinOne(2));
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
TextView t = (TextView) findViewById(R.id.textView4);
if(from == to)
{
Toast.makeText(getApplicationContext(), "Invalid", 4000).show();
}
else
{
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
t.setText(exResult);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
public String getJson(String url)throws ClientProtocolException, IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
private class spinOne implements OnItemSelectedListener
{
int ide;
spinOne(int i)
{
ide =i;
}
public void onItemSelected(AdapterView<?> parent, View view,
int index, long id) {
if(ide == 1)
from = index;
else if(ide == 2)
to = index;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
class GetResponseData extends AsyncTask<String, String, String> {
private ProgressDialog dialog;
private ArrayList<String> titleList;
private TextView textView;
public GetResponseData(TextView textView) {
this.textView = textView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(currency_converter.this, "", "Loading",
false);
}
#Override
protected String doInBackground(String... params) {
try {
String s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22" + val[from] + val[to] + "%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
return exResult;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog != null)
dialog.dismiss();
if (result != null) {
textView.setText(result);
}
}
}
}
}
Logcat:
10-30 00:59:48.164 20591-20591/com.example.travelapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:365)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:587)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:511)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:489)
at com.example.travelapplication.currency_converter.getJson(currency_converter.java:93)
at com.example.travelapplication.currency_converter$1.onClick(currency_converter.java:68)
at android.view.View.performClick(View.java:4222)
at android.view.View$PerformClick.run(View.java:17620)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5391)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Try this,,
Your performing a networking operation on its main thread. That why your getting NetworkOnMainThreadException
b.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
TextView t = (TextView) findViewById(R.id.textView4);
if(from == to)
{
Toast.makeText(getApplicationContext(), "Invalid", 4000).show();
}
else
{
GetResponseData abcd = GetResponseData(t);
abcd.execute();
}
}
});
You are getting:
NetworkOnMainThreadException
Issue is that you are calling your function getJson() in your Activity.
Use AsyncTask:
public class ProcessTask extends AsyncTask<Void, Integer, String>{
public ProcessTask() {
// TODO Auto-generated constructor stub
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
//your code of parsing
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url); //your yahooapi url goes here
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
It looks like you have strict mode on in your android manifest. Strict mode will complain when you are doing network calls on you main thread. You can just disable strict mode or a better approach is to put your network call into an async task. The network call in question is
HttpResponse response = client.execute(httpGet);
inside public String getJson(String url)
The async task you need is already there you just need to use it
Change this else statement
else
{
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
t.setText(exResult);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
To this
else {
new GetResponseData().execute("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
}
It will help use this :
public class CurrencyConverter extends Fragment {
public CurrencyConverter() {
}
TextView t;
public int to;
public int from;
public String[] val;
public String s;
String exResult;
public Handler handler;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.currency_converter, container, false);
t= (TextView) rootView.findViewById(R.id.textView4);
Spinner s1 = (Spinner) rootView.findViewById(R.id.spinner1);
Spinner s2 = (Spinner) rootView.findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this.getActivity(), R.array.name, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
val = getResources().getStringArray(R.array.value);
s1.setAdapter(adapter);
s2.setAdapter(adapter);
s1.setOnItemSelectedListener(new spinOne(1));
s2.setOnItemSelectedListener(new spinOne(2));
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View View) {
if (from == to) {
Toast.makeText(getActivity().getApplicationContext(), "Invalid", 4000).show();
} else {
new calculate().execute();
}
}
});
return rootView;
}
public class calculate extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return exResult;
}
#Override
protected void onPostExecute(String exResult) {
t.setText(exResult);
}
}
public String getJson(String url)throws IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
public class spinOne implements AdapterView.OnItemSelectedListener
{
int ide;
spinOne(int i)
{
ide =i;
}
public void onItemSelected(AdapterView<?> parent, View view,
int index, long id) {
if(ide == 1)
from = index;
else if(ide == 2)
to = index;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
}

Dismiss Progress Dialog and handle exception in AsyncTask

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();
}
}

Speeding up loading a webpage into android using Jsoup

I have created a app to fetch a table from a website into android using jsoup after logging into that site. Though it works fine it is very slow and takes a lot of time for the activity to start up. Can any one help me with this issue. I have attached the code below and thanks in advance
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
tv=(TextView)findViewById(R.id.tv);
Bundle extra=getIntent().getExtras();
if(extra!=null){
Log.v("got", extra.getString("user")+extra.getString("pass"));
user=extra.getString("user");
pass=extra.getString("pass");
}
HomeList homelist=new HomeList(this);
try {
ArrayList<String> result=homelist.execute(user+pass).get();
if(result.contains("rejected")){
Toast.makeText(this, result.toString(), Toast.LENGTH_LONG).show();
finish();
}
else{
tv.setText(user.toUpperCase(Locale.US));
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, result);
lv=(ListView)findViewById(R.id.list);
lv.setAdapter(adapter);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
}
public class HomeList extends AsyncTask<String,String,ArrayList<String>> {
private List<String> cookies;
private HttpURLConnection conn;
private final String USER_AGENT="Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36";
private Home home;
List<String> cook;
private int BUFF=50;
String username;
public HomeList(Home home) {
// TODO Auto-generated constructor stub
this.home=home;
}
public HomeList() {
// TODO Auto-generated constructor stub
}
#Override
protected ArrayList<String> doInBackground(String... arg0) {
// TODO Auto-generated method stub
publishProgress("Loading");
String user=arg0[0].substring(0,10);
Log.v("user", user);
String pass=arg0[0].substring(10,arg0[0].length());
Log.v("pass", pass);
//int code=Integer.parseInt(arg0[0].substring(arg0[0].length()-1));
ArrayList<String> no=new ArrayList<String>();
no.add("rejected");
String url = "http://borealis.astra.edu.in";
//action url in form
String astra="http://borealis.astra.edu.in/index.php";
String attendance="http://borealis.astra.edu.in/index.php?option=com_base_attendancereport&Itemid=98";
HomeList coll=new HomeList();
//for cookies
CookieHandler.setDefault(new CookieManager());
//get form data to be sent
String page=coll.GetPageContent(url);
//collecting form data
String postParams = coll.getFormParams(page,user,pass);
System.out.println(postParams);
cook=cookies;
System.out.print(cook);
ArrayList<String> result=coll.sendPost(url,postParams);
if(result.contains("error"))
return no;
else
return result;
}
private ArrayList<String> sendPost(String url, String postParams) {
// TODO Auto-generated method stub
URL obj;
try {
obj = new URL(url);
conn=(HttpURLConnection)obj.openConnection();
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host", "borealis.astra.edu.in");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn.setRequestProperty("Accept-Language","en-US,en;q=0.8");
for(String cookie:this.cookies){
conn.setRequestProperty("cookie", cookie.split(";",1)[0]);
System.out.println(cookie);
}
conn.setRequestProperty("Connection","keep-alive");
conn.setDoOutput(true);
conn.setDoInput(true);
DataOutputStream wr=new DataOutputStream(conn.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode=conn.getResponseCode();
System.out.println(conn.getURL());
System.out.println("posting data to "+url);
System.out.println("parametrs are "+postParams);
System.out.println("response Code "+responseCode);
URL secondURL = new URL(conn.getHeaderField("Location"));
conn=(HttpURLConnection) secondURL.openConnection();
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()),BUFF);
Log.d("length", "got"+conn.getContentLength());
System.out.println("redirected url" + conn.getURL());
String inputLine;
StringBuffer response=new StringBuffer();
while((inputLine=in.readLine())!=null){
response.append(inputLine);
}
Document doc=Jsoup.parse(response.toString());
Elements table=doc.getElementsByClass("tiles_box");
in.close();
ArrayList<String> ele=new ArrayList<String>();
if(table.first()!=null){
Iterator<Element> ite=table.select("tr").select("td").iterator();
ele.add(ite.next().text());
Log.d("td", ele.toString());
while(ite.hasNext()){
String td=ite.next().text();
if(!ele.contains(td)){
ele.add(td);
Log.d("td", ele.toString());
}
}
return ele;
}
else
{
ArrayList<String> error=new ArrayList<String>();
error.add("error");
return error;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private String getFormParams(String html, String user, String pass){
// TODO Auto-generated method stub
try{
System.out.println("extracting form data");
Document doc=Jsoup.parse(html);
Element form=doc.getElementById("form-login");
Elements inputElements=form.getElementsByTag("input");
List<String> paramsList=new ArrayList<String>();
for(Element inputElement:inputElements){
String key=inputElement.attr("name");
String value=inputElement.attr("value");
if(key.equals("username"))
value=user;
if(key.equals("passwd"))
value=pass;
paramsList.add(key+"="+URLEncoder.encode(value,"UTF-8"));
}
StringBuilder result=new StringBuilder();
for(String param:paramsList){
if(result.length()==0){
result.append(param);
}else{
result.append("&"+param);
}
}
return result.toString();
}catch(Exception e){
Log.d("error", e.toString());
}
return null;
}
private String GetPageContent(String url){
// TODO Auto-generated method stub
try{
URL obj=new URL(url);
conn=(HttpURLConnection)obj.openConnection();
conn.setChunkedStreamingMode(20);
conn.setRequestMethod("GET");
conn.setUseCaches(true);
conn.setRequestProperty("Host", "borealis.astra.edu.in");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn.setRequestProperty("Accept-Language","en-US,en;q=0.8");
if(cookies!=null)
{
for(String cookie:this.cookies){
conn.addRequestProperty("cookie", cookie.split(";",1)[0]);
}
}
int responseCode=conn.getResponseCode();
System.out.println("sending get request "+url);
System.out.println("response code is "+responseCode);
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()),BUFF);
String inputLine;
StringBuffer response=new StringBuffer();
while((inputLine=in.readLine())!=null){
response.append(inputLine);
}
in.close();
setCookies(conn.getHeaderFields().get("Set-Cookie"));
return response.toString();
}catch(Exception e){
Log.d("error", e.toString());
}
return null;
}
private void setCookies(List<String> cookies) {
// TODO Auto-generated method stub
this.cookies=cookies;
cook=cookies;
System.out.print(cook);
}
public List<String> getCookies(){
return cookies;
}
#Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
Toast.makeText(getApplicationContext(), values[0], Toast.LENGTH_LONG).show();
}
#Override
protected void onPostExecute(ArrayList<String> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
With this line ArrayList<String> result=homelist.execute(user+pass).get(); you lose all the advantages of multithreading. The problem is the get() method, which
Waits if necessary for the computation to complete, and then retrieves its result.
In my opinion you should use a sort of callback, like this:
public class MyAsyncTask extends AsyncTask<String, Void, String> {
public interface OnWorkDone {
public void doSomething(String s);
}
private OnWorkDone listener;
public void setListener(OnWorkDone listener) {
this.listener = listener;
}
#Override
protected String doInBackground(String... params) {
String result = null;
//do something
return result;
}
#Override
protected void onPostExecute(String result) {
if (listener != null) {
listener.doSomething(result);
}
}
}
And, on the main class:
MyAsyncTask task = new MyAsyncTask();
task.setListener(new OnWorkDone() {
#Override
public void doSomething(String s) {
//Use results
}
});
task.execute(params);

when process dialog is being displayed, doInBackground() is not being executed

I'm trying to display process dialog, it is being showed as expected, but when it is being showed, doInBackground() is not being executed, when I press on screen of emulator, then doInBackground() starts executing again.
This is my AsyncTask class:
public class FetchEmployeeAsyncTask extends AsyncTask<String, Void, ArrayList<Employee> > {
private CaptureActivity activity;
//private ProgressDialog progressDialog;
public FetchEmployeeAsyncTask(CaptureActivity nextActivity) {
this.activity = nextActivity;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*progressDialog= new ProgressDialog(activity);
progressDialog.setCancelable(true);
progressDialog.setTitle("Fetching Employees!!");
progressDialog.setMessage("Please wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(0);
progressDialog.show();*/
}
#Override
protected ArrayList<Employee> doInBackground(String... url) {
// TODO Auto-generated methoVoidd stub
ArrayList<Employee> employees = null;
for(String employeeUrl : url){
employees = fetch(employeeUrl);
}
return employees;
}
private ArrayList<Employee> fetch(String url) {
// TODO Auto-generated method stub
ArrayList<Employee> employees = null;
String response = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
employees = EmployeeXMLParser.employeeParser(response);
System.out.println("Size in fetch "+employees.size());
//System.out.println("Employee Name :: " + employees.get(0).getFirstName() + " " + employees.get(0).getLastName());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*catch (XmlPullParserException e) {
// TODO Auto-generated catch block
System.out.println("Error parsing the response :: " + response);
e.printStackTrace();
}*/
return employees;
}
#Override
public void onPostExecute(ArrayList<Employee> employees){
super.onPostExecute(employees);
System.out.println("in post execxute "+employees.size());
//progressDialog.dismiss();
activity.showEmployees(employees);
}
}
I'm calling AsyncTask in this activity class:
public class CaptureActivity extends Activity {
private String url = "http://192.168.2.223:8680/capture/clientRequest.do?r=employeeList&cid=0";
FetchEmployeeAsyncTask employeeAsyncTask;
private ArrayList<Employee> employees = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("");
employeeAsyncTask = new FetchEmployeeAsyncTask(this);
employeeAsyncTask.execute(new String[] {url});
System.out.println("Status "+employeeAsyncTask.getStatus());
setContentView(R.layout.activity_capture);
}
What are you trying to do here? are you trying to get some values from the database if so check the assignment of the url if you are passing the value correctly.
Also please try explaining your problem in detail and paste some more code.
Try this:
protected void onPreExecute() {
progressDialog = ProgressDialog.show(currentActivity.this, "",
"Message Here", true);
}
protected void onPostExecute(String str) {
dialog.dismiss();
}

Android: AsyncTask and reading internet data

I have written a code to download some data from internet. Than i wanted to put it into asyncTask. And after that downloading stopped working. It looks like it cant finish try{} part so skips to exeption.
From main activity "Nekaj" i call loadData() class, which extends AsyncData. From there i call "oto" class inside try command. "oto" class is used to read stuff from internet and returns array of strings. This worked when i called oto class directly from "Nekaj"class. What did I do wrong with using AsyncTask?
Here is the code:
public class Nekaj extends Activity {
TextView Tkolo, Tbroj1;
String[] brojevi_varijabla;
String privremena_varijabla = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.bez_provjere_739);
Tkolo = (TextView) findViewById(R.id.Xkolo);
Tbroj1 = (TextView) findViewById(R.id.Xbroj1);
/*
* try { privremena_varijabla = test.kolo_739();
* Tkolo.setText(privremena_varijabla); } catch (Exception e) { // TODO
* Auto-generated catch block e.printStackTrace(); }
*/
new loadData().execute();
}
public class loadData extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
Oto test = new Oto();
try {
brojevi_varijabla = test.brojevi_739();
if (Integer.valueOf(brojevi_varijabla[0]) > 10) {
Tbroj1.setText("" + brojevi_varijabla[0]);
} else {
Tbroj1.setText(" " + brojevi_varijabla[0]);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public class Oto {
public String[] brojevi_739() throws Exception {
int i = 0;
int uvjet = 0;
int varijabla = 0;
char[] znak = { '>', '<' };
BufferedReader in = null;
String data[] = null;
String provjera = "date-info";
int[] polje = new int[2];
try {
HttpClient klijent = new DefaultHttpClient();
URI webstranica = new URI(
"https://www.aaa.bb");
HttpGet zahtjev = new HttpGet();
zahtjev.setURI(webstranica);
HttpResponse odgovor = klijent.execute(zahtjev);
in = new BufferedReader(new InputStreamReader(odgovor
.getEntity().getContent()));
StringBuffer brojevi = new StringBuffer("");
String brojevi_string = null;
String neki_string = null;
String red = "";
in.skip(21000);
while ((red = in.readLine()) != null) {
varijabla = red.indexOf(provjera);
if (varijabla != -1) {
// 1. KOLO
if (uvjet == 0) { // onda sadrži taj
// substring
// !!!!
red = in.readLine(); // sada string red sadrži ono
// što
// želim, još moram samo to
// izrezati!!
do {
if (i == 0) {
varijabla = red.indexOf(znak[i]);
}
else {
varijabla = red.indexOf(znak[i], polje[0]);
}
if (varijabla != -1) // ako taj znak postoji u
// stringu
{
if (i == 0) {
polje[i] = varijabla + 1;
}
else {
polje[i] = varijabla;
}
i++;
}
} while (i <= 1);
neki_string = red.substring(polje[0], polje[1]);
Tkolo.setText(neki_string);
provjera = "Dobitna kombinacija";
uvjet++;
continue;
}
}
}
in.close();
brojevi_string = brojevi.toString();
data = brojevi_string.split("\n");
return data;
} finally {
if (in != null) {
try {
in.close();
return data;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}}
What you are doing wrong is Tbroj1.setText() inside the doInBackground() method. What you have to do is to use the onPostExecute method to post your data on the UI:
public class loadData extends AsyncTask<String, Integer, Boolean> {
protected Long doInBackground(String... arg0) {
Oto test = new Oto();
Boolean result = false;
try {
brojevi_varijabla = test.brojevi_739();
result = true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
protected void onPostExecute(Boolean result) {
if(result){
if (Integer.valueOf(brojevi_varijabla[0]) > 10) {
Tbroj1.setText("" + brojevi_varijabla[0]);
} else {
Tbroj1.setText(" " + brojevi_varijabla[0]);
}
}
}
}
Actually, You are trying to update UI in doInBackGround() of your AsyncTask, so its not allowed (doInBack.. runs in non UI Thread..), So put the UI updation code in onPostExecute() of AsyncTask..
Try this and let me know what happen..
public class loadData extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
Oto test = new Oto();
try {
brojevi_varijabla = test.brojevi_739();
if(brojevi_varijabla != null)
return brojevi_varijabla[0];
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result)
{
if(result != null)
{
if (Integer.valueOf(result) > 10) {
Tbroj1.setText("" + result;
} else {
Tbroj1.setText(" " + result);
}
}
}
}
use onPostExecute(Void result1) {}
to catch the result and perform the action required over there
You can't manipulate UI elements directly on a non-UI (background) thread, which is where doInBackground() always runs. The usual way of using AsyncTask is to get the data in doInBackground(), return it as a value, and then process the UI changes in onPostExecute(). For example:
public class loadData extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
Oto test = new Oto();
try {
brojevi_varijabla = test.brojevi_739();
if (Integer.valueOf(brojevi_varijabla[0]) > 10) {
return "" + brojevi_varijabla[0];
} else {
return " " + brojevi_varijabla[0];
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) Tbroj1.setText(result);
}
}

Categories

Resources