Speeding up loading a webpage into android using Jsoup - android

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

Related

Piccaso not loading Image on First Attempt android

In my application I have a fragment which loads image from remote server to set background of FrameLayout using AsynTask and in onPostExeccute() method I am trying to render Bitmap images using Picasso. But as my Fragment starts first time no image is loaded in the background of FrameLayout but as I refresh the particular fragment then I can see the Image as background.
Updated Code segment inside AsyncTask
private class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String responseBody = "";
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResult = "";
try {
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
System.out.println("Returned Json object " + jsonResult.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ctx);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
if(result.equals("") || result == null){
Toast.makeText(ctx, "Server connection failed", Toast.LENGTH_LONG).show();
}
int jsonResult = returnParsedJsonObject(result);
if(jsonResult == -1){
Toast.makeText(ctx, "Sorry No Places Found", Toast.LENGTH_LONG).show();
}
if(jsonResult == 1){
//Toast.makeText(ctx, "", Toast.LENGTH_LONG).show();
try {
JSONObject jsonObj = new JSONObject(result);
// Getting JSON Array node
places = jsonObj.getJSONArray("result");
// looping through All Contacts
for (int i = 0; i < places.length(); i++) {
JSONObject place = places.getJSONObject(i);
// String slot = c.getString(TAG_SLOT);
// serverReturn.add(slot);
UserPlaces placeFroServer = new UserPlaces();
placeFroServer.setId(place.getString(TAG_PID));
placeFroServer.setName(place.getString(TAG_PNAME));
placeFroServer.setDescription(place.getString(TAG_DESC));
placeFroServer.setImg(place.getString(TAG_IMG));
placeFroServer.setLat(place.getString(TAG_LAT));
placeFroServer.setLng(place.getString(TAG_LNG));
placesList.add(placeFroServer);
}
UserPlaces myPlace = placesList.get(counter);
pid=myPlace.getId();
lat = myPlace.getLat();
lng = myPlace.getLng();
Picasso.with(ctx).load(myPlace.getImg()).into(new Target() {
#Override
public void onPrepareLoad(Drawable arg0) {
// TODO Auto-generated method stub
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom arg1) {
// TODO Auto-generated method stub
Toast.makeText(ctx,"Loaded",Toast.LENGTH_LONG).show();
pImg.setBackgroundDrawable(new BitmapDrawable(ctx.getResources(), bitmap));
pImg.invalidate();
}
#Override
public void onBitmapFailed(Drawable arg0) {
// TODO Auto-generated method stub
Toast.makeText(ctx, "Failed Loading", Toast.LENGTH_SHORT).show();
}
});
pname.setText(myPlace.getName());
pdes.setText(myPlace.getDescription());
rl.setVisibility(View.VISIBLE);
counter++;
} catch (JSONException e) {
String ex = e.getMessage();
e.printStackTrace();
}
}
if (pDialog.isShowing())
pDialog.dismiss();
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
For particular problem of week reference try creating a global Target object. As demonstrated in the code below.
Code Sample:
Target target;
target = new Target(){
#Override
public void onPrepareLoad(Drawable arg0) {
// TODO Auto-generated method stub
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom arg1) {
//Toast.makeText(ctx,"Loaded",Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
pImg.setBackgroundDrawable(new BitmapDrawable(ctx.getResources(), bitmap));
pImg.invalidate();
}
#Override
public void onBitmapFailed(Drawable arg0) {
// TODO Auto-generated method stub
Toast.makeText(ctx, "Failed Loading", Toast.LENGTH_SHORT).show();
}
};
Picasso.with(ctx).load(myPlace.getImg()).into(target);
You should call invalidate() on pImg after setting the background.
You can use the alternative of it Univerasal Image Loader

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
}
}
}

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

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

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.

populating listview through a fragment

I have a class extending listFragment. I have written code for fetching json response in a method which is called in oncreate of the class. For fetching json in background I have created new inner class which extends asyncTask. I can get the jsonarrays and strings in the json response in the logcat. But when I try to save them in a string array and pass them my custom baseadapter, I get a nullpointer exception.
public class OnlineInfo extends ListFragment {
public static String result;
public String[] Technologies1;
public String[] TechnologyDescription1;
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
downloadjsonresponse();
}
public class Download extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
StringBuilder stringbuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet url = new HttpGet(params[0]);
try
{
Log.d("in background", "in background");
HttpResponse response = client.execute(url);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line ;
while((line = reader.readLine()) != null)
{
stringbuilder.append(line);
}
}
catch(ClientProtocolException e)
{
Log.d("error in clientprotocol", "error");
e.printStackTrace();
}
catch(IOException e)
{
Log.d("error in IO", "error");
e.printStackTrace();
}
return stringbuilder.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
OnlineInfo.result = result;
try {
JSONObject jsonobject = new JSONObject(result);
JSONArray raja = jsonobject.getJSONArray("Technologies");
//String raja = jsonobject.getJSONArray("Technologies").getJSONObject(0).getString("desc");
//Log.d("desc:", raja);
for(int i=0; i<raja.length();i++)
{
Technologies1[i] = raja.getJSONObject(i).getString("name");
TechnologyDescription1[i] = raja.getJSONObject(i).getString("desc");
Log.d("technology :", raja.getJSONObject(i).getString("name"));
Log.d("technologydescription :", raja.getJSONObject(i).getString("desc"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("desc:", "error");
}
getListView().setAdapter(new AdapterForOnlineInfo(getActivity(), OnlineInfo.this.Technologies1, OnlineInfo.this.TechnologyDescription1));
}
}
public void downloadjsonresponse()
{
Download jsonresponse = new Download();
jsonresponse.execute("http://www.avantajsoftwares.com/result.json");
}
}
I could get the results in logcat whenever I comment these two lines in for-loop:
Technologies1[i] = raja.getJSONObject(i).getString("name");
TechnologyDescription1[i] = raja.getJSONObject(i).getString("desc");
Don't know what's going wrong. Please somebody provide me some insight....:-(
I think you need to allocate space in your string arrays to hold the new strings.
Just before your for loop, try putting something like this:
Technologies1 = new String[raja.length()];
TechnologyDescription1 = new String[raja.length()];

Categories

Resources