0

I decided that in order to speed up my application and avoid crashing i would run my method PetrolPriceString on a background thread through the AsyncTask method. However even though my application does still run there is no speed up and looking at my code i'm convinced i have made an error in my placement of the method as well as i think maybe some of my code may be wrong despite no errors. My method simply runs the method PetrolPriceString in a background thread and returns the urlString which i'm hoping will contain a URL to an RSS feed specified.

    package org.me.myandroidstuff;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.app.ProgressDialog;
import android.os.AsyncTask;
//import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class PetrolPriceActivity extends Menu 
{
    private TextView response;
    private TextView errorText;
    private String result;
    private String petrolPriceURL;
    private static final String TAG = "PetrolPrice";


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);

        Bundle extras = getIntent().getExtras();
        if(extras!=null){
        petrolPriceURL =extras.getString("URLString");
        }
        // Get the TextView object on which to display the results
        response = (TextView)findViewById(R.id.error);
        response = (TextView)findViewById(R.id.title);
        try
        {
            // Get the data from the RSS stream as a string
            result =  petrolPriceString(petrolPriceURL);

            // Do some processing of the data to get the individual parts of the RSS stream
            // At some point put this processing into a separate thread of execution
            // Display the string in the TextView object just to demonstrate this capability
            // This will need to be removed at some point
            response.setText(result);
        }
        catch(IOException ae)
        {
            // Handle error
            response.setText("Error");
            // Add error info to log for diagnostics
            errorText.setText(ae.toString());
        } 

    }

    // End of onCreate

    // Method to handle the reading of the data from the RSS stream
    private static String petrolPriceString(String urlString)throws IOException
    {
        String result = "";
        InputStream anInStream = null;
        int response = -1;
        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        // Check that the connection can be opened
        if (!(conn instanceof HttpURLConnection))
                throw new IOException("Not an HTTP connection");
        try
        {
            // Open connection
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();
            // Check that connection is Ok
            if (response == HttpURLConnection.HTTP_OK)
            {
                // Connection is OK so open a reader 
                anInStream = httpConn.getInputStream();
                InputStreamReader in= new InputStreamReader(anInStream);
                BufferedReader bin= new BufferedReader(in);

                // Read in the data from the RSS stream
                String line = new String();
                while (( (line = bin.readLine())) != null)
                {
                    result = result + "\n" + line;
                }
            }
        }
        catch (Exception ex)
        {
                throw new IOException("Error connecting");
        }

        // Return result as a string for further processing
         new AsyncTask<String, String, String>() {
            IOException exception = null;
            @Override protected String doInBackground(String... params) {
                try {
                    Log.v(TAG, "index=" + "hello");
                    return petrolPriceString(params[0]);
                } catch (IOException e) {
                    exception = e;
                    return null;
                }
            }
            @Override protected void onPostExecute(String result) {
                if (exception != null) {
                    // handle our exception

                } else {
                    // handle our result
                }
            }
        }.execute(urlString);

        return result;

    }
    // End of petrolPriceString
 // End of Activity class
}

I'm rather new to android and very new to the concept of threads so any help would be greatly appreciated

codeMagic
  • 44,549
  • 13
  • 77
  • 93
  • well the first code yes does work as for the actual asynctask code well im not too sure on that one. I have no errors if thats what u mean – user3071845 Aug 13 '14 at 14:26
  • 1
    `AsyncTask` actually don't speed up execution, it just separates it from UI Thread which means that UI Thread can perform other job at the time. – Alex Salauyou Aug 13 '14 at 14:27
  • so i should move all my code in PetrolPriceString to the AsyncTask? Yeh Sasha Salauyou i want the method to run in the background as it can cause errors if i add more later on – user3071845 Aug 13 '14 at 14:31
  • (String urlString)throws IOException - how would i do this in my inner class? – user3071845 Aug 13 '14 at 14:46
  • ive edited the code is this better? thank you everyone for helping me understand this as well as hopefully have the right code now – user3071845 Aug 13 '14 at 17:05
  • @user3071845 I've rolled back your edit. Please don't change the original code as it will be unhelpful for future users with the same problem. If you have a new question then post it separately – codeMagic Aug 13 '14 at 17:18
  • right so how will i show the eventual solution? also was my edit the correct code? will i create a separate code segment after my original code stating its the solution? – user3071845 Aug 13 '14 at 17:22
  • You don't need to post a complete solution with your code because other people are surely going to have different code. You *could* add the solution as an answer but it typically isn't needed. There are multiple ways to accomplish it but the solution **is** to move all of that code to a background thread and run it only once. – codeMagic Aug 13 '14 at 18:03
  • i added an answer simply to help others. Thanks for all your help – user3071845 Aug 13 '14 at 18:05

2 Answers2

2

It looks to me like you are only running

Log.v(TAG, "index=" + "hello");
return petrolPriceString(params[0]);

on a background thread. When you first call this method here

result =  petrolPriceString(petrolPriceURL)

it is running through that network code then running the AsyncTask which calls the method again. It seems like it is calling itself recursively.

I would suggest making the AsynctTask it's own inner class then execute it, running all of the code in your method.

See this answer on how to do that.

AsyncTask Docs

Community
  • 1
  • 1
codeMagic
  • 44,549
  • 13
  • 77
  • 93
  • how do i execute it within my PetrolPriceActivity activity? would i simply use TalkToServer AsyncTask = new MyTask(); AsyncTask.execute(); – user3071845 Aug 13 '14 at 14:28
  • @user3071845 use the example in the link to create an inner class in your `Activity` (you can name it whatever you want). Then execute it that way wherever you need to. `AsyncTask.execute(petrolPriceURL)` but that variable should be camel-case to adhere to Java standards. – codeMagic Aug 13 '14 at 14:45
  • hi i think ive got it working however how would i pass my result variable from my inner class to my petrolPriceActivity class? this is all i need to get it working as when i check my logcat i do have the correct information – user3071845 Aug 13 '14 at 15:44
  • As that linked answer shows, since it's an inner class of the `Activity`, you can simply update your `View` in `onPostExecute()`. – codeMagic Aug 13 '14 at 15:45
0

I wrote an answer myself to help others with the same problem.

Put the petrolPriceString(..) code into an inner class of PetrolPriceActivity, which extends AsyncTask.

And execute it in the onCreate method:

new asyncTask().execute(petrolPriceURL);

Anything done afterwards to update the UI is handled on onPostExecute rather than onCreate.

package org.me.myandroidstuff;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class PetrolPriceActivity extends Menu {
    private TextView response;
    private TextView errorText;
    private String petrolPriceURL;
    private static final String TAG = "PetrolPrice";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);

        Bundle extras = getIntent().getExtras();
        if (extras!=null) {
            petrolPriceURL =extras.getString("URLString");
        }
        // Get the TextView object on which to display the results
        new asyncTask().execute(petrolPriceURL);
    }

    public class asyncTask extends AsyncTask<String, Void, String> {
           @Override
           protected String doInBackground(String...parmans) {
               String urlString = petrolPriceURL;
               {
                    String result = "";
                    InputStream anInStream = null;
                    int response = -1;
                    URL url = null;
                    try {
                        url = new URL(urlString);
                    } catch (MalformedURLException e) {
                        return null;
                    }

                    URLConnection conn = null;
                    try {
                        conn = url.openConnection();
                    } catch (IOException e) {
                        return null;
                    }

                    // Check that the connection can be opened
                    if (!(conn instanceof HttpURLConnection))
                        try {
                            throw new IOException("Not an HTTP connection");
                        } catch (IOException e) {
                            return null;
                        }
                    try {
                        // Open connection
                        HttpURLConnection httpConn = (HttpURLConnection) conn;
                        httpConn.setAllowUserInteraction(false);
                        httpConn.setInstanceFollowRedirects(true);
                        httpConn.setRequestMethod("GET");
                        httpConn.connect();
                        response = httpConn.getResponseCode();
                        // Check that connection is OK
                        if (response == HttpURLConnection.HTTP_OK) {
                            // Connection is OK so open a reader 
                            anInStream = httpConn.getInputStream();
                            InputStreamReader in= new InputStreamReader(anInStream);
                            BufferedReader bin= new BufferedReader(in);

                            // Read in the data from the RSS stream
                            String line = new String();
                            while (( (line = bin.readLine())) != null) {
                                result = result + "\n" + line;
                            }
                        }
                    } catch (IOException ex) {
                            try {
                                throw new IOException("Error connecting");
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                    }

                    return result;
                }
           }

           @Override
           protected void onPostExecute(String result) {
               // Get the data from the RSS stream as a string
               response = (TextView)findViewById(R.id.error);
               response = (TextView)findViewById(R.id.title);

               try {
                    // Get the data from the RSS stream as a string
                    result =  doInBackground(petrolPriceURL);

                    response.setText(result);
                    Log.v(TAG, "index=" + result);
                } catch(Exception ae) {
                    // Handle error
                    response.setText("Error");
                    // Add error info to log for diagnostics
                    errorText.setText(ae.toString());
                }
            }
        }
}
Christian Strempfer
  • 7,291
  • 6
  • 50
  • 75