1

私はまったく問題のないこのコード行を持っていますが、唯一の問題は、このコードが実行されるたびに、アプリがすべてのプロセスが終了するのを待って、インターフェースがおそらく0.5秒間応答しないことです。私が見つけた最善の解決策は使用することでしたThreadが、それはいくつかの問題を引き起こすので、私AsyncTaskは理解するのに苦労していることに頼ります。このコード行に実装する方法を教えてもらえますか?

            ima.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    search.clearFocus();
                    currentItem = ssil;
                    if (currentRoom.equals("None")) {
                        Toast.makeText(StartMoving.this, "Please select a room before adding an item", Toast.LENGTH_LONG).show();
                    }else{

                        try {
                            String currentitemholder = startmoving.getSingleItemName(currentMove, currentRoom, currentItem);
                            if (currentitemholder.equals(currentItem)) {
                                String ssi = startmoving.getSingleItemValue(currentMove, currentRoom, currentItem);
                                String ssiw = startmoving.getSingleItemWeight(currentMove, currentRoom, currentItem);
                                String stw = startmoving.getTotalWeight(currentMove);
                                String srw = startmoving.getRoomWeight(currentMove, currentRoom);
                                String diw = startmoving.getListItemWeight(currentItem);
                                int istw = Integer.parseInt(stw);
                                int isiw = Integer.parseInt(ssiw);
                                int isi = Integer.parseInt(ssi);
                                int isrw = Integer.parseInt(srw);
                                int idiw = Integer.parseInt(diw);
                                currentItemValue = "" + ++isi;
                                currentItemWeight = "" + (isiw + idiw);
                                currentTotalItemWeight = "" + (istw + idiw);
                                currentRoomWeight = "" + (isrw + idiw);
                                currentTotalItem = startmoving.getTotalItem(currentMove) + 1; 
                                startmoving.updateItems(currentMove, currentRoom, currentItem, currentItemValue, currentItemWeight);
                                startmoving.setMoveWeight(currentTotalItemWeight, currentMove);
                                startmoving.setRoomWeight(currentRoomWeight, currentMove, currentRoom); 
                                startmoving.setTotalItem(currentMove, currentTotalItem);
                                String displayname = startmoving.getItemName(currentMove, currentRoom);
                                String displayvalue = startmoving.getItemValue(currentMove, currentRoom);
                                String displayweight = startmoving.getItemWeightLBS(currentMove, currentRoom);
                                String displaytotalweight = startmoving.getTotalWeightLBS(currentMove);
                                String displayroomweight = startmoving.getRoomWeightLBS(currentMove, currentRoom);
                                roomContent.setText(displayname);
                                itemValue.setText(displayvalue);
                                itemWeight.setText(displayweight);
                                totalweight.setText(displaytotalweight);
                                roomweight.setText(displayroomweight); 
                                int displaytotalitem = startmoving.getTotalItem(currentMove); 
                                totalitem.setText("" + displaytotalitem);
                            }
                        }catch (Exception e) {
                            // TODO Auto-generated catch block
                            currentItemValue = "1";
                            currentItemWeight = ssiw;
                            String stw = startmoving.getTotalWeight(currentMove);
                            String srw = startmoving.getRoomWeight(currentMove, currentRoom);
                            String diw = startmoving.getListItemWeight(currentItem);
                            int istw = Integer.parseInt(stw);
                            int isrw = Integer.parseInt(srw);
                            int idiw = Integer.parseInt(diw);
                            currentTotalItemWeight = "" + (istw + idiw);
                            currentRoomWeight = "" + (isrw + idiw);
                            currentTotalItem = startmoving.getTotalItem(currentMove) + 1; 
                            startmoving.addNewItems(currentMove, currentRoom, currentItem, currentItemValue, currentItemWeight);
                            startmoving.setMoveWeight(currentTotalItemWeight, currentMove);
                            startmoving.setRoomWeight(currentRoomWeight, currentMove, currentRoom); 
                            startmoving.setTotalItem(currentMove, currentTotalItem);
                            startmoving.setTotalItem(currentMove, currentTotalItem);
                            String displayname = startmoving.getItemName(currentMove, currentRoom);
                            String displayvalue = startmoving.getItemValue(currentMove, currentRoom);
                            String displayweight = startmoving.getItemWeightLBS(currentMove, currentRoom);
                            String displaytotalweight = startmoving.getTotalWeightLBS(currentMove);
                            String displayroomweight = startmoving.getRoomWeightLBS(currentMove, currentRoom);
                            roomContent.setText(displayname);
                            itemValue.setText(displayvalue);
                            itemWeight.setText(displayweight);
                            totalweight.setText(displaytotalweight);
                            roomweight.setText(displayroomweight); 
                            int displaytotalitem = startmoving.getTotalItem(currentMove); 
                            totalitem.setText("" + displaytotalitem);
                        }
                    }
                }
            });

            imr.setOnClickListener(new OnClickListener() {

                @SuppressLint("ShowToast")
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    search.clearFocus();
                    currentItem = ssil;
                    if (currentRoom.equals("None")) {
                        Toast.makeText(StartMoving.this, "Please select a room before removing an item", Toast.LENGTH_LONG).show();
                    }else{

                        try {
                            String currentitemholder = startmoving.getSingleItemName(currentMove, currentRoom, currentItem);
                            if (currentitemholder.equals(currentItem)) {
                                String ssi = startmoving.getSingleItemValue(currentMove, currentRoom, currentItem);
                                String ssiw = startmoving.getSingleItemWeight(currentMove, currentRoom, currentItem);
                                String stw = startmoving.getTotalWeight(currentMove);
                                String srw = startmoving.getRoomWeight(currentMove, currentRoom);
                                String diw = startmoving.getListItemWeight(currentItem);
                                int istw = Integer.parseInt(stw);
                                int isiw = Integer.parseInt(ssiw);
                                int isi = Integer.parseInt(ssi);
                                int isrw = Integer.parseInt(srw);
                                int idiw = Integer.parseInt(diw);
                                if (isi > 1) {
                                    currentItemValue = "" + --isi;
                                    currentItemWeight = "" + (isiw - idiw);
                                    currentTotalItemWeight = "" + (istw - idiw);
                                    currentRoomWeight = "" + (isrw - idiw);
                                    currentTotalItem = startmoving.getTotalItem(currentMove) - 1; 
                                    startmoving.updateItems(currentMove, currentRoom, currentItem, currentItemValue, currentItemWeight);
                                    startmoving.setMoveWeight(currentTotalItemWeight, currentMove);
                                    startmoving.setRoomWeight(currentRoomWeight, currentMove, currentRoom); 
                                    startmoving.setTotalItem(currentMove, currentTotalItem);
                                    startmoving.setTotalItem(currentMove, currentTotalItem);
                                    String displayname = startmoving.getItemName(currentMove, currentRoom);
                                    String displayvalue = startmoving.getItemValue(currentMove, currentRoom);
                                    String displayweight = startmoving.getItemWeightLBS(currentMove, currentRoom);
                                    String displaytotalweight = startmoving.getTotalWeightLBS(currentMove);
                                    String displayroomweight = startmoving.getRoomWeightLBS(currentMove, currentRoom);
                                    roomContent.setText(displayname);
                                    itemValue.setText(displayvalue);
                                    itemWeight.setText(displayweight);
                                    totalweight.setText(displaytotalweight);
                                    roomweight.setText(displayroomweight); 
                                    int displaytotalitem = startmoving.getTotalItem(currentMove); totalitem.setText("" + displaytotalitem);
                                }else{
                                    String sstw = startmoving.getTotalWeight(currentMove);
                                    String ssrw = startmoving.getRoomWeight(currentMove, currentRoom);
                                    int isstw = Integer.parseInt(sstw);
                                    int issrw = Integer.parseInt(ssrw);
                                    currentTotalItemWeight = "" + (isstw - idiw);
                                    currentRoomWeight = "" + (issrw - idiw);
                                    currentTotalItem = startmoving.getTotalItem(currentMove) - 1; startmoving.setMoveWeight(currentTotalItemWeight, currentMove);
                                    startmoving.setRoomWeight(currentRoomWeight, currentMove, currentRoom);
                                    startmoving.deleteItem(currentMove, currentRoom, currentItem); startmoving.setTotalItem(currentMove, currentTotalItem);
                                    startmoving.setTotalItem(currentMove, currentTotalItem);
                                    String displayname = startmoving.getItemName(currentMove, currentRoom);
                                    String displayvalue = startmoving.getItemValue(currentMove, currentRoom);
                                    String displayweight = startmoving.getItemWeightLBS(currentMove, currentRoom);
                                    String displaytotalweight = startmoving.getTotalWeightLBS(currentMove);
                                    String displayroomweight = startmoving.getRoomWeightLBS(currentMove, currentRoom);
                                    roomContent.setText(displayname);
                                    itemValue.setText(displayvalue);
                                    itemWeight.setText(displayweight);
                                    totalweight.setText(displaytotalweight);
                                    roomweight.setText(displayroomweight); 
                                    int displaytotalitem = startmoving.getTotalItem(currentMove); 
                                    totalitem.setText("" + displaytotalitem);
                                }   
                            }
                        }catch (Exception e) {
                            // TODO Auto-generated catch block

                        }
                    }
                }
            });

ご覧のとおり、これらはデータベースを呼び出し(データの送受信)、GUIに表示する2つのボタンです。

編集

素晴らしい応答者に感謝します!正しい答えを決める前に、まずAsyncTaskを勉強します。あなたが私にくれたこのすべての情報をまだ処理する必要があります。

編集 は、startmovingが私のデータベースモジュールであることを言及するのを忘れました

4

4 に答える 4

2

ファイルの読み込みやデータへのアクセスなど、長時間続く操作を実行すると、Androidアプリケーションのユーザーインターフェースは、対応するコードが終了するまでブロックされます。

AsyncTask

AsyncTaskクラスを使用するには、クラスを拡張し、少なくともdoInBackground()メソッドをオーバーライドする必要があります。

実装する必要がある最も一般的な方法は次のとおりです。

   1. onPreExecute() – called on the UI thread before the thread starts running. This method is usually used to setup the task, for example by displaying a progress bar.

   2. doInBackground(Params…) – this is the method that runs on the background thread. In this method you should put all the code you want the application to perform in background. Referring to our Simple RSS Aplication, you would put here the code that downloads the XML feed and does the parsing. The doInBackground() is called immediately after onPreExecute(). When it finishes, it sends the result to the onPostExecute().

   3. onProgressUpdate() - called when you invoke publishProgress() in the doInBackground().

   4. onPostExecute(Result) – called on the UI thread after the background thread finishes. It takes as parameter the result received from doInBackground().

今あなたのコード選択で、あなたができること。

すべてのデータベース操作およびデータ操作コードはメソッドに書き込まれ、doInBackground(Params…)メソッドにデータを表示しますonPostExecute(Result)

ありがとう。

于 2012-10-24T04:32:13.853 に答える
1

AsyncTaskは、ビューがあるGUIにアクセスできないdoInBackground()別のスレッド内ですべてを実行します。

preExecute()またpostExecute()、この新しいスレッドで重い作業が発生する前後にGUIにアクセスできるようにすることで、長い操作の結果をに渡して、postExecute()処理の結果を表示することもできます。

Androidは、いわゆるUIスレッドと呼ばれる1つのスレッドを介してユーザーインターフェイスを変更します。インターネットからファイルをダウンロードするなど、UIスレッドで直接長時間実行する操作を実行すると、対応するタスクが完了するまで、アプリケーションのユーザーインターフェイスが「フリーズ」します。これが発生すると、ユーザーはアプリケーションが遅いと感じるのが非常に簡単になります。

AsyncTaskを使用すると、UIスレッドを適切かつ簡単に使用できます。このクラスを使用すると、スレッドやハンドラーを操作しなくても、バックグラウンド操作を実行してUIスレッドで結果を公開できます。

  1. onPreExecute()–スレッドの実行が開始される前にUIスレッドで呼び出されます。この方法は通常、プログレスバーを表示するなどしてタスクを設定するために使用されます。

  2. doInBackground(Params…)–これはバックグラウンドスレッドで実行されるメソッドです。このメソッドでは、アプリケーションで実行するすべてのコードをバックグラウンドで配置する必要があります。Simple RSS Aplicationを参照すると、XMLフィードをダウンロードして解析を行うコードをここに配置します。doInBackground()は、onPreExecute()の直後に呼び出されます。終了すると、結果がonPostExecute()に送信されます。

  3. onProgressUpdate()--doInBackground()でpublishProgress()を呼び出すと呼び出されます。

  4. onPostExecute(Result)–バックグラウンドスレッドが終了した後、UIスレッドで呼び出されます。doInBackground()から受け取った結果をパラメーターとして受け取ります。

AsyncTaskはジェネリッククラスであり、AsyncTaskの3つのタイプを使用します。

Params – the input. what you pass to the AsyncTask
Progress – if you have any updates, passed to onProgressUpdate()
Result – the output. what returns doInBackground()

タスクが作成されると、次のように実行できます。

new DownloadTast().execute(url1, url2, urln);

これがAsyncTaskの一例です

于 2012-10-24T04:39:33.553 に答える
1

さて、あなたに解決策を与えることなく、Androidで非同期リクエストについて読み始めるのが最善だと思います:http://developer.android.com/reference/android/os/AsyncTask.html。Webの非同期性を理解すると、UIがレンダリングされる可能性のあるデータから分離されていることを理解するのに役立ちます。

応答性は、UIをデータから分離したい最大の理由です。これは、EDT(Event Dispath Thread)を使用したJava Swing開発者にとっておそらく最もよく説明されています:http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html。開発者が実行時間の長いプロセスをボタンなどにアタッチし、独自のスレッドを使用して処理を高速化することで修正しようとする、低速なアプリの例は非常に多くありました。Swingは最終的にSwingWorkerとdoInBackground()を使用してJava6でこれを修正しました。AndroidにやってくるSwing開発者にとって、彼らはおそらくAsyncTaskを見て、なぜJavaではそれほど単純ではなかったのかと尋ねるでしょう。

したがって、時間をかけてAsyncTaskに慣れ、その使用方法、さらに柔軟性を高めるためにリスナーと組み合わせる方法を理解してから、コードを変更する方法を理解してください。

正しい方向に向けられるためにさらに助けが必要な場合はお知らせください。

于 2012-10-24T04:42:11.403 に答える
1

基本的に、AsyncTaskクラスを拡張し、独自の実装を作成する必要があります。doInBackground()関数が非UIスレッドで実行されるという事実を利用し、それが返す結果をUIスレッドで実行されるonPostExecute()関数で使用できます。

コードがデータベースを呼び出すとおっしゃっていたので、「startmoving」オブジェクトがデータベースモジュールであると想定します。以下のサンプルコードでは、実際のクラス名がコードに表示されていないため、これを単にMovingDbクラスと呼びます。

// this will hold all your calculated value
private class DisplayInfo {
   String displayName, displayValue, displayWeight, displayTotalWeight, displayRoomWeight;
   int displayTotalItem;
}

private class ItemHolderTask extends AsyncTask<MovingDb, Integer, DisplayInfo> {

   protected DisplayInfo doInBackground(MovingDb... movingDbs) {
      // this code runs in background thread so do your DB work here
      if (movingDbs != null && movingDbs.length > 0 && movingDbs[0] != null) {
         MovingDb startMoving = movingDbs[0];
         // move all your db operations here
         String currentItemHolder = startMoving.getSingleIteName(....)
         // blah blah
         DisplayInfo displayInfo = new DisplayInfo();
         displayInfo.displayName = startMoving.getItemName(...);
         displayInfo.displayValue = startMoving.getItemValue(...);
         // set up the rest of your display info values
         return displayInfo;
      }
   }

   protected void onPostExecute(DisplayInfo displayInfo) {
      // the displayInfo you return from doInBackground comes here
      if (displayInfo != null) {
         roomContent.setText(displayInfo.displayName);
         itemValue.setText(displayInfo.displayValue);
         // and so on...
      }
   }
}

onClick関数では、ItemHolderTaskを開始するだけです。

new ItemHolderTask().execute(startMoving);
于 2012-10-24T04:48:40.123 に答える