2016-11-23 17 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