2016-11-23 8 views
0

runOnUiThreadを使用して、バックグラウンドでデータを処理していますが、処理に使用されている変数(ishr)の値が最後にnullになっています。 androidスレッドからメインUIに値を取得する方法

が、私はそれをデバッグしようとした、すべてのものが正常に動作し、値が runOnUiThreadブロック内に存在するが、それはそれから出てきたときに、それは nullで、mainUIの値を取得する方法はありますか?

// 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; 
} 

あなたがrunOnUiThread()方法のish.setText(ishra);外を呼び出しているため、機能していない、あなたのコードがある理由:

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'は' 'やる... processdata.in.backgroundんどのようなバックグラウンドプロセス –

+0

ではないでしょうか?そのコードはどこですか? – Tigger

+0

コンテキストを持っているようです(findViewByIdを呼び出しているので)。これをrunOnUiThreadとして呼び出す必要はなく、単に 'processdata.in.background'を直接呼び出すことができます。 – scorpiodawg

答えて

0

は個人的に私はAsyncTaskを使用するか、次の変更を行うためにコードを再書きます。これは、あなたがsetText()メソッドを呼び出した後runOnUiThread()ishraに割り当てられStringが更新されることを意味します。

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

をそして、あなたのコードが固体である場合、それはあまりにも動作するはずです:

あなたはとても同様のようish.setText(ishra);をシフトすることができます。

+0

ありがとう、あなたも良い解決策です – reader

+0

ありがとう、あなたの良い解決策です。 ursを試す前に私は他の解決策を探していました。私はkaushikduttaによってion [link](https://github.com/koush/ion)を見つけました。 – reader

関連する問題