-1

わかりましたので、コードが UI スレッドで実行されるように、AsycTask を拡張する内部クラスを作成しました。ただし、このエラーが発生しているので、これは onPostExecute の一部を doInBackground で実行する必要があることを意味すると思いますが、これが何であるかを正確に把握することはできません

public class asyncTask extends AsyncTask<String, Integer, String> {

        ProgressDialog dialog = new ProgressDialog(PetrolPriceActivity.this);

        @Override
           protected void onPreExecute() {
          dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
          dialog.setProgress(0);
          dialog.setMax(100);
          dialog.setMessage("loading...");
          dialog.show();
           }

         @Override
           protected String doInBackground(String...parmans){
                {

                    for(int i = 0; i < 100; i++){


                        publishProgress(1);
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }


                    String urlString = petrolPriceURL;
                    String result = "";
                    InputStream anInStream = null;
                    int response = -1;
                    URL url = null;

                    try {
                        url = new URL(urlString);
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        return null;
                    }
                    URLConnection conn = null;
                    try {
                        conn = url.openConnection();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        return null;
                    }

                    // Check that the connection can be opened
                    if (!(conn instanceof HttpURLConnection))
                        try {
                            throw new IOException("Not an HTTP connection");
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            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) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                    }

            return result;

                }
           }
           @Override

           protected void onProgressUpdate(Integer...progress){

               dialog.incrementProgressBy(progress[0]);
           }

           @Override
           protected void onPostExecute(String result) {
               // Get the data from the RSS stream as a string

               errorText = (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
                    errorText.setText("Error");
                    // Add error info to log for diagnostics
                    errorText.setText(ae.toString());
                } 
                if(dialog.getProgress() == dialog.getMax())
                dialog.dismiss();

           }
        }

誰かが私のエラーを指摘し、コードが私の doInBackground にあると思われる場所の例を示すことができれば、それは素晴らしいことです。ありがとう

4

2 に答える 2

2

問題:

result =  doInBackground(petrolPriceURL);

別のスレッドではなく UI スレッドで実際に実行されるのdoInbackgroundメソッドを暗黙的に呼び出しているため、 になります。onPostExecuteAndroid:NetworkOnMainThreadException

doInBackgroundまた、実行する前に既に実行されていることを呼び出す必要はありonPostExecuteませんAsynctaskresultのパラメータを直接使用するだけonPostExecuteです。

サンプル:

@Override
       protected void onPostExecute(String result) {
           // Get the data from the RSS stream as a string

           errorText = (TextView)findViewById(R.id.error);
           response = (TextView)findViewById(R.id.title);

            response.setText(result);

            if(dialog.getProgress() == dialog.getMax())
            dialog.dismiss();

       }
于 2014-08-13T22:42:21.147 に答える
2

エラーはコードのこの部分に関連していると思われます:

try
 {
 // Get the data from the RSS stream as a string
 result =  doInBackground(petrolPriceURL);
 response.setText(result);
 Log.v(TAG, "index=" + result);
 }

asynctask.execute を呼び出すと、doInBackgound が自動的に呼び出されます。タスクを正しく開始するには、(1) タスクの新しいインスタンスを作成する必要があります。(2) doInBackground で使用する必要がある文字列パラメーターを execute メソッドに渡します。(3) それらを使用する。(4) 結果を onPostExecute に返す。

例えば:

 //in your activity or fragment
 MyTask postTask = new MyTask();
 postTask.execute(value1, value2, value3);

 //in your async task
 @Override
 protected String doInBackground(String... params){

      //extract values
      String value1 = params[0];
      String value2 = params[1];
      String value3 = params[2];

      // do some work and return result
      return value1 + value2;
 }

 @Override
 protected void onPostExecute(String result){

      //use the result you returned from you doInBackground method
 }

doInBackground メソッドですべての「作業」を行うようにしてください。メイン/UI スレッドで使用する結果を返します。これは、(メイン/UI スレッドで実行される) onPostExecute メソッドに引数として自動的に渡されます。

于 2014-08-13T22:42:34.670 に答える