2017-04-20 64 views
0

我是Android的新手,我嘗試使用php腳本與訪問簡單數據庫的本地主機通信。 我在doInBackground()方法中定義了一個任務,該方法從本地主機上存儲的數據庫獲取值(我不知道該部分是否可以工作)。 我想使用doInBackground方法返回的結果在活動的textview中設置文本。使用doInBackground的結果來設置textView

public class BackgroundWorker extends AsyncTask<String,Void,String> { 

    Context context; 


    BackgroundWorker(Context ctx) 
    { 
     context = ctx; 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     String group = params[0]; 
     String child = params[1]; 
     String address = "http://10.0.2.2/conn.php"; 

     URL url = null; 
     try { 
      url = new URL(address); 
      HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
      httpURLConnection.setRequestMethod("POST"); 
      httpURLConnection.setDoOutput(true); 
      httpURLConnection.setDoInput(true); 
      OutputStream outputStream = httpURLConnection.getOutputStream(); 
      BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); 
      String post_data = URLEncoder.encode("group", "UTF-8") + "=" + URLEncoder.encode(group, "UTF-8") + "&" 
        + URLEncoder.encode("child", "UTF-8") + "=" + URLEncoder.encode(child, "UTF-8"); 
      bufferedWriter.write(post_data); 
      bufferedWriter.flush(); 
      bufferedWriter.close(); 
      outputStream.close(); 
      InputStream inputStream = httpURLConnection.getInputStream(); 
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1")); 
      String result = ""; 
      String line; 
      while ((line = bufferedReader.readLine()) != null) { 
       result += line; 
      } 
      bufferedReader.close(); 
      inputStream.close(); 
      httpURLConnection.disconnect(); 
      return result; 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

    } 


    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
    } 

    @Override 
    protected void onPostExecute(String s) { 

     super.onPostExecute(s); 
    } 

    @Override 
    protected void onProgressUpdate(Void... values) { 
     super.onProgressUpdate(values); 
    } 
} 

以及活動類:

public class viewTT extends Activity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_view_tt); 


     Button btnNextScreen = (Button) findViewById(R.id.button); 
     TextView txtName = (TextView) findViewById(R.id.textView); 
     TextView txtName2 = (TextView) findViewById(R.id.textView2); 

     Intent i = getIntent(); 
     // Receiving the Data 
     String group= i.getStringExtra("group"); 
     String child = i.getStringExtra("child"); 
     txtName.setText(group+" "+child); 

     BackgroundWorker backgroundWorker = new BackgroundWorker(this); 
     backgroundWorker.execute(group,child); 



     btnNextScreen.setOnClickListener(new View.OnClickListener() { 

        public void onClick(View arg0) 
        { 
       //Starting a new Intent 
          Intent nextScreen = new Intent(getApplicationContext(), MainActivity.class); 
          startActivity(nextScreen); 
        } 
     }); 
    } 
} 

我想設置txtName2。

+0

後'doInBackground'稱爲返回的結果,然後將這些結果傳遞給'onPostExecute'在這裏你可以設置'txtName2.setText(結果);' –

+1

是'BackgroundWorker'和' viewTT'物理2個不同的文件? – Yazan

+0

[如何從另一個類更新活動的TextView]的可能重複(http://stackoverflow.com/questions/10996479/how-to-update-a-textview-of-an-activity-from-another-類) – Yazan

回答

2

您可以使用一個接口將數據返回到您的活動

接口

public interface AsyncResponse { 
    public void onFinish(Object output); 
} 

SomeAsyncTask類

public class SomeAsyncTask extends AsyncTask<String, String, String> { 
private AsyncResponse asyncResponse; 

public SomeAsyncTask(AsyncResponse asyncResponse) { 
    this.asyncResponse = asyncResponse; 

} 

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

    //Do something 
    ..... 
    //Finally return something 

    return "returnSomeString"; 
} 

@Override 
protected void onPostExecute(String s) { 
    super.onPostExecute(s); 
    asyncResponse.onFinish(s); 
}} 

在您的活動要設置視圖像這樣調用SomeAsyncTask類

SomeAsyncTask someAsyncTask=new SomeAsyncTask(new AsyncResponse() { 
     @Override 
     public void onFinish(Object output) { 
      String result= (String) output; 
      //Finally set your views 
     } 
    }); 
    someAsyncTask.execute(); 
} 
+1

你創建了一個對asynctask內部活動的硬引用,這很容易導致內存泄漏。 – njzk2

+0

如果他想要內存泄漏,那麼它會使用'static'而不是使用太多的代碼。 –

+0

現在可以,如果不是我建議我做錯了。 –

-1

這是你在你的BackgroundWorker類主線程

protected void onPostExecute(String s) { 
    // s is your string 
    super.onPostExecute(s); 
} 

字符串添加該代碼...

private String textFortxtName2; 

public String getTextFortxtName2() { 
    return textFortxtName2; 
} 

public void setTextFortxtName2(String textFortxtName2) { 
    this.textFortxtName2 = textFortxtName2; 
} 

再加入這個

protected void onPostExecute(String s) { 
// s is your string 
textFortxtName2 = s; 
super.onPostExecute(s); 

}

現在你可以得到文字弗羅姆侑主要活動,,,

... 
BackgroundWorker backgroundWorker = new BackgroundWorker(this); 
backgroundWorker.execute(group,child); 
txtName2.setText(backgroundWorker.getTextFortxtName2()); 

這是所有:) 是否會有任何疑問或袋子請COMENT

+0

如果任務沒有完成(通常不會被完成),該怎麼辦 –

+0

BackgroundWorker(Context ctx) { context = ctx; }後臺工作者類的構造函數仍然只能初始化上下文嗎? –

+0

我無法理解你的問題,會發生什麼? –

0

定義的接口取的結果backgroundworker並使worker構造函數接受第二個參數interface.call,該接口對象在post上執行並將結果作爲參數。不是用它想:

BackgroundWorker backgroundWorker = new BackgroundWorker(this, new bgWorkerListener() { 
      @Override 
      public void onResult(String s) { 
       txtname2.settext(s); 
      } 
     }); 
     backgroundWorker.execute(group, child);