0

私が見たすべての場所で、彼らはonClickでスレッド化を使用しました。ドキュメントに記載されているように、メインスレッドでネットワーク操作を実行できないため、スレッドを使用せざるを得なくなりました。では、このようなものをコーディングしたボタンにスレッドをどのように配置しますか?

public void firstbutton(View view) 
{
//some code
}

助けてくれてありがとう!

編集:

        public void firstbutton(View view) 
    {
        InputMethodManager inputMgr = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        EditText editText = (EditText)findViewById(R.id.editText1);
        inputMgr.hideSoftInputFromWindow(editText.getWindowToken(), 0);

        EditText idnumber=(EditText)findViewById(R.id.editText1);
        String idnumber2= idnumber.getText().toString();
        int i = Integer.parseInt(editText.getText().toString());
        idnum=i;
        setContentView(R.layout.viewer);
        Context context = view.getContext();
        Drawable image = ImageOperations(context, WEB ADDRESS HIDDEN FOR PRIVACY"+idnumber2);
        ImageView icon = new ImageView(context);
        icon = (ImageView)findViewById(R.id.imageView1);
        icon.setImageDrawable(image);
};


public Drawable ImageOperations(Context ctx, String url) {
    try {
        InputStream is = (InputStream) this.fetch(url);
        Drawable d = Drawable.createFromStream(is, "src");
        return d;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

public Object fetch(String address) throws MalformedURLException,IOException
{
URL url = new URL(address);
Object content = url.getContent();
return content;
}
4

2 に答える 2

1

それはあなたが何を達成したいかによります。

ネットワーク関連の新しいスレッドを開始したいだけの場合は、次のThreadような方法を使用できます。

public void firstbutton(View view) 
{
    new Thread() {
        @Override
        public void run() {
            // Do your network stuff
        }
    }.start();
}

ネットワーク操作が完了した後でUIを更新する必要がある場合は、AsyncTaskおそらくより良い選択です。

    new AsyncTask<Void,Void,ResultType>() {
        @Override
        protected ResultType doInBackground(Void... params) {
            // Do network stuff
            return someResult;
        }

        protected void onPostExecute(ResultType result) {
            // Update UI with your result
        };
    };
于 2012-11-19T14:55:25.430 に答える
0

ええと、onClick()メソッド内で行うのとまったく同じ方法です。

私はあなたのボタンがクリックされたときにあなたのメソッドが呼び出されると思います(私が間違っているかどうか教えてください)firstbutton()(したがって私はonClick()によって実行されます)

してください、あなたは書くことができます:

public void firstbutton(View view) {
   new Thread(new Runnable() {
       public void run() {
            // Do your network stuff
     }).start();
}

(または、通常どおりAsyncTaskクラスを使用することもできます...)

于 2012-11-19T14:57:33.333 に答える