-1

アクティビティにアクセスし、非同期クラスからテキストを設定したい。

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button getBtn = (Button) findViewById(R.id.btn_result);

        getBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                           TextView txt_res = (TextView)findViewById(R.id.txt_Result);
                           new GetText(txt_res).execute(); // Async class
                }
        });
    }
}

//非同期クラス

public class GetText AsyncTask<Void, Void, Void>{
    private TextView txt_res;

    public GetText (TextView txt_res) {
        this.txt_res = txt_res;
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
                     String Result = GetTextFromDb();
        } catch (Exception e) {

        }
        return null;
    }

     @Override
 protected void onPostExecute(Void result)
    {
        try
        {
            Log.v("Success", "Success"); // I see "Success" at Logcat
            txt_res.SetText("Success"); // Textview didn't change
        }catch (Exception e) {
            Log.v("Error", e.getMessage()); // No error at Logcat

        }
    }
}

私は自分の質問を再定義します。テキストビューは変更されません。私の間違いは何ですか。

もう一度質問を再定義します。2 つの関数 (doInBackground、onPostExecute) で Textview が変更されませんでした。

4

1 に答える 1

1

基本的に2つのオプションがあります。明らかにasychからメインスレッドに直接アクセスすることはできないため、適切な形式を使用する必要があります。

  1. タスクの終了後にテキストビューを更新する必要がある場合は、onPostExecuteで更新を行うだけです。

  2. テキストビューに中間の進行状況が表示されている場合は、onProgressUpdateを使用してください

編集:

さて、ここにあなたの問題があります。asycnタスクでは、doInBackgroundから値を返す必要があります。タイプをStringに変更し、onPostExecute(String result)を変更します。Voidは、何も返さないことを意味します。また、非同期タスクの上部にある3つのパラメーターの2番目も文字列に変更する必要があります。

また、メソッドはtextview.setText( "");です。textview.SetText( "")ではありません。後者はコンパイルしないでください

于 2012-11-25T02:32:19.787 に答える