2014-07-15 92 views
-1

我使用ThreadWebservice,但我不能得到Thread的數據,因爲我不能從Thread返回數據。如何從線程返回值?

這是我WebService.java

public class Webservice { 
    static String result; 
    public static String readUrl(final String url) { 
     Thread thread = new Thread(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        HttpClient client = new DefaultHttpClient(); 
        HttpPost method = new HttpPost(url); 
        HttpResponse response = client.execute(method); 
        InputStream stream = response.getEntity().getContent(); 
        result = ConvertInputStreamToString(stream); 
        Log.i("xxx","OK" + result); 

       } catch (ClientProtocolException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
      thread.start(); 
      return result; 
    } 

    private static String ConvertInputStreamToString(InputStream inputstteam) { 
     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        inputstteam)); 
      StringBuilder builder = new StringBuilder(); 
      String line = ""; 

      while ((line = reader.readLine()) != null) { 
       builder.append(line); 
      } 
      return builder.toString(); 
     } 
     catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 
} 

這是NotesActivity.java

public class NotesActivity extends Activity { 

    private ArrayList<StructTask> nettasks = new ArrayList<StructTask>(); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Thread thread = new Thread(new Runnable() { 

      @Override 
      public void run() { 
       String result = Webservice.readUrl("http://192.168.200.101:8081/note-server/"); 
       if (result != null) { 
        try { 
         JSONArray tasks = new JSONArray(result); 
         for (int i = 0; i < tasks.length(); i++) { 
          JSONObject object = tasks.getJSONObject(i); 
          //Log.i("LOG", "Task: " + object.getString("task_title")); 
          StructTask task = new StructTask(); 
          task.id = object.getLong("task_id"); 
          task.title = object.getString("task_title"); 
          task.desc = object.getString("task_desc"); 
          task.done = object.getBoolean("task_done"); 
          nettasks.add(task); 

          for (StructTask taskes : nettasks) { 
           Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done); 
          } 
         } 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 

       } 
       else 
       { 
        Log.i("OK", "TaskesOK: " + result); 
        Log.i("LOG", "Task: " + "NULL"); 
       } 

      } 
     }); 
     thread.start(); 

    } 
} 

這是我StructTask.java

public class StructTask { 
    public long id; 
    public String title; 
    public String desc; 
    public boolean done; 
} 

此代碼返回給我NULL。

+1

你真的不想要onCreate中新線程的典當。這可能會導致各種問題,包括內存泄漏和應用程序生命週期問題。你需要做的是檢查Android設備AsyncTask。 – Bex

+0

您可以使用sharedprefrences臨時存儲數據或使用靜態變量並在您的線程中分配值 –

+0

爲什麼您不使用async? – Andy

回答

1

剛剛嘗試這種方式

1)Webservice.java

public class Webservice { 
     public interface WebCallListener{ 
      void onCallComplete(String result); 
     } 
     public static void readUrl(final String url,final WebCallListener callListener) { 
      Thread thread = new Thread(new Runnable() { 
       @Override 
       public void run() { 
        try { 
         HttpClient client = new DefaultHttpClient(); 
         HttpPost method = new HttpPost(url); 
         HttpResponse response = client.execute(method); 
         InputStream stream = response.getEntity().getContent(); 
         callListener.onCallComplete(ConvertInputStreamToString(stream)); 
        } catch (ClientProtocolException e) { 
         e.printStackTrace(); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 
       } 
      }); 
      thread.start(); 
     } 

     private static String ConvertInputStreamToString(InputStream inputstteam) { 
      try { 
       BufferedReader reader = new BufferedReader(new InputStreamReader(
         inputstteam)); 
       StringBuilder builder = new StringBuilder(); 
       String line = ""; 

       while ((line = reader.readLine()) != null) { 
        builder.append(line); 
       } 
       return builder.toString(); 
      } 
      catch (IOException e) { 
       e.printStackTrace(); 
      } 
      return null; 
     } 
    } 

2)NotesActivity.java

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     Webservice.readUrl("http://192.168.200.101:8081/note-server/",new WebCallListener() { 
      @Override 
      public void onCallComplete(String result) { 
       if (result != null) { 
        try { 
         JSONArray tasks = new JSONArray(result); 
         for (int i = 0; i < tasks.length(); i++) { 
          JSONObject object = tasks.getJSONObject(i); 
          //Log.i("LOG", "Task: " + object.getString("task_title")); 
          StructTask task = new StructTask(); 
          task.id = object.getLong("task_id"); 
          task.title = object.getString("task_title"); 
          task.desc = object.getString("task_desc"); 
          task.done = object.getBoolean("task_done"); 
          nettasks.add(task); 

         } 
         for (StructTask taskes : nettasks) { 
           Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done); 
          } 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 

       } 
       else 
       { 
        Log.i("OK", "TaskesOK: " + result); 
        Log.i("LOG", "Task: " + "NULL"); 
       } 
      } 
     }); 

    } 
+0

@ Biraj Zalavadia。在NotesActivity.java中,我無法使用WebCallListener。它說我:WebCallListener不能解析爲一個類型。 –

+0

導入它的人。我已經在Webservice類中創建它。同時複製 –

+0

類別的東西出錯了。它在這裏工作。 –

0

你可以用你的代碼中的一些事情是這樣的:

private class ImageDownloader extends AsyncTask { 

    @Override 
    protected Bitmap doInBackground(String... param) { 
     // TODO Auto-generated method stub 
     return myBackgroundImageDownloadFun(param[0]); 
    } 

    @Override 
    protected void onPreExecute() { 
     Log.i("Async-Example", "onPreExecute Called"); 
     simpleWaitDialog = ProgressDialog.show(ImageDownladerActivity.this, 
       "Wait", "Downloading Image"); 

    } 

    @Override 
    protected void onPostExecute(Bitmap result) { 
     Log.i("Async-Example", "onPostExecute Called"); 
     MyImageView.setImageBitmap(result); 
     simpleWaitDialog.dismiss(); 

    } 
0

爲此,您可以使用的AsyncTask即

private class Webservice extends AsyncTask<Void, Void, ArrayList<StructTask>> { 
    private ArrayList<StructTask> nettasks = new ArrayList<StructTask>(); 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
    } 

    @Override 
    protected ArrayList<StructTask> doInBackground(Void... params) { 
     try { 
      String result = readUrl("http://192.168.200.101:8081/note-server/"); 
      JSONArray tasks = new JSONArray(result); 
      for (int i = 0; i < tasks.length(); i++) { 
       JSONObject object = tasks.getJSONObject(i); 
       //Log.i("LOG", "Task: " + object.getString("task_title")); 
       StructTask task = new StructTask(); 
       task.id = object.getLong("task_id"); 
       task.title = object.getString("task_title"); 
       task.desc = object.getString("task_desc"); 
       task.done = object.getBoolean("task_done"); 
       nettasks.add(task); 
      } 
      for (StructTask taskes : nettasks) { 
       Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done); 
      } 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return nettasks; 
    } 
/* after parsing response this method will be called*/ 


    @Override 
    protected void onPostExecute(ArrayList<StructTask> result) { 
     // TODO Auto-generated method stub 
     super.onPostExecute(result); 
    } 

    private String readUrl(String url) throws Exception{ 
     HttpClient client = new DefaultHttpClient(); 
     HttpPost method = new HttpPost(url); 
     HttpResponse response = client.execute(method); 
     InputStream stream = response.getEntity().getContent(); 
     String result = ConvertInputStreamToString(stream); 
     Log.i("xxx", "OK" + result); 
     return result; 
    } 

    private String ConvertInputStreamToString(InputStream inputstteam) { 
     try { 
      BufferedReader reader = new BufferedReader(
        new InputStreamReader(inputstteam)); 
      StringBuilder builder = new StringBuilder(); 
      String line = ""; 

      while ((line = reader.readLine()) != null) { 
       builder.append(line); 
      } 
      return builder.toString(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 
} 

在onCreate方法您的活動類嘗試這樣

調用

Webservice service = new Webservice(); service.excute();

所以它會開始執行上面的線程。

我認爲這會幫助你