2016-11-23 67 views
0

我正在使用runOnUiThread處理背景中的一些數據,但在處理中使用的變量(ishr)的值在最後變爲nullandroid如何從線程獲取值到mainUI

我試圖調試它,每件事情都正常工作,值存在於runOnUiThread塊,但它是null出來時,有沒有辦法在mainUI中獲取值?

public String ishra=""; 
TextView ish = (TextView) findViewById(R.id.ish); 
runOnUiThread(new Runnable(){ 
      @Override 
      public void run(){ 
       processdata.in.background(result); 
      } 
     }); 

ish.setText(ishra); 


process.data.in.background(String match) 
{ 
    if (match=="True"){ 
     getdatafromhttp(); 
     processdata(resultfromhttp); 
    } 
} 

private void processdata(String data) 
{ 
    try 
    { 
     JSONObject json = new JSONObject(data); 
     JSONObject a = json.getJSONObject("data"); 
     ishra = a.getString("Surprise"); 
    } 
    catch (JSONException e) 
    { 
     Log.wtf("log", e); 
    } 
} 
+1

'runOnUiThread'不是後臺進程 –

+0

'processdata.in.background ...'是做什麼的?代碼在哪裏? – Tigger

+0

你似乎有一個上下文(因爲你調用findViewById),所以不應該把它叫做runOnUiThread,你可以直接調用'processdata.in.background'。 – scorpiodawg

回答

0

個人而言,我將重新編寫代碼來使用AsyncTask或做如下修改:

// ishra is not required any more 
//public String ishra=""; 
TextView ish = (TextView) findViewById(R.id.ish); 
runOnUiThread(new Runnable(){ 
     @Override 
     public void run(){ 
      // Set the text here 
      ish.setText(processdata.in.background(result)); 
     } 
    }); 

// Not required any more 
//ish.setText(ishra); 

// Return a String 
private String process.data.in.background(String match) 
{ 
    private String result = ""; 
    if (match=="True"){ 
     // What does getdatafromhttp() do? It may need to be changed. 
     getdatafromhttp(); 
     result = processdata(resultfromhttp); 
    } 
    return result; 
} 

private String processdata(String data) 
{ 
    String result = ""; 
    try 
    { 
     JSONObject json = new JSONObject(data); 
     JSONObject a = json.getJSONObject("data"); 
     // Get the result 
     result = a.getString("Surprise"); 
    } 
    catch (JSONException e) 
    { 
     Log.wtf("log", e); 
    } 
    // Return the result String 
    return result; 
} 

之所以你的代碼不工作是因爲你調用ish.setText(ishra);runOnUiThread()方法。這意味着在調用setText()方法之後,runOnUiThread()內的String被更新爲ishra

你可以像這樣以及轉移ish.setText(ishra);

public void run(){ 
    processdata.in.background(result); 
    ish.setText(ishra); 
} 

如果你的代碼是堅實的,這應該工作了。

+0

謝謝,你們也是一個很好的解決方案 – reader

+0

謝謝,你們是一個很好的解決方案。之前嘗試urs我正在尋找其他解決方案,我發現離子[鏈接](https://github.com/koush/ion)kaushikdutta這是簡單的解決方案再次感謝您的答覆 – reader