1

私が乗っている2つのエラーであなたの助けが必要です

  1. ファイルを作成しているスレッドの作成
  2. ファイルの処理後、ファイルをサーバーに送信するために AsyncTask が実行されます (multipart/form-data)

最初の部分は次のようになります。

public void startResultTransfer(final int timestamp, final int duration, final String correction, final float textSize, final int age, final int switch_count, final Activity activity){

    synchronized(DataTransmission.class){ 

        new Thread() {
            public void run() {
                FileWriter fw = null;
                //1.Check if file exists
                File file = new File(FILE_PATH);
                if(!file.exists()){
                    //File does not exists, when we have to generate the head-line
                    try {
                        fw = new FileWriter(FILE_PATH);
                        fw.append("timestamp\tduration\tcorrection\ttext_size\tage\tswitch_count"); //Headline
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                //2. Write Result
                try {
                    if(fw == null)
                        fw = new FileWriter(FILE_PATH);
                    fw.append("\n"+String.valueOf(timestamp)+"\t");
                    fw.append(""+String.valueOf(duration)+"\t");
                    fw.append(""+correction+"\t");
                    fw.append(""+String.valueOf(textSize)+"\t");
                    fw.append(""+String.valueOf(age)+"\t");
                    fw.append(""+String.valueOf(switch_count)+"\t");
                    fw.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                //3. File Transfer
                if(isOnline(activity))
                    transferFileToServer(activity);
            }
        }.start();

    }
}

関数「transferFileToServer」は次のようになります。

public synchronized void transferFileToServer(Activity activity){
    String id = id(activity);
    File file = new File(FILE_PATH);

    if(id != null && file.exists()){
        final String url = URL+id;
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TransmissionTask task = new TransmissionTask();
                task.execute(url);
            }
        });

    }

}

今、説明メッセージとともに「ExceptionInInitializerError」を取得しています

原因 java.lang.RuntimeException Can't create handler inside thread that has not called Looper.prepare()"

「activity.runOnUiThread」の行。

最初の関数では、いくつかの事前設定の後に「transferFileToServer」を呼び出す必要があります。ただし、関数も最初の関数からアタッチせずに呼び出す必要があります。

Thread の最後で AsyncTask を実行するための MessageHandler を実装する必要がありますか? http://developer.android.com/reference/android/os/Looper.html

または、「transferFileToServer」関数の「AsyncTask」をスレッドに変更する必要がありますか? UI 操作を行わないためです。

編集: Async-Task から開始されたメソッド

class TransmissionTask extends AsyncTask<String, Void, String> {

    public TransmissionTask() {

    }

    @Override
    protected String doInBackground(String... params) {
        synchronized(DataTransmission.class){
            try {

                HttpURLConnection urlConn;
                java.net.URL mUrl = new java.net.URL(params[0]);
                urlConn = (HttpURLConnection) mUrl.openConnection();
                urlConn.setDoOutput(true);
                urlConn.setRequestMethod("POST");

                String boundary = "---------------------------14737809831466499882746641449";
                String contentType = "multipart/form-data; boundary="+boundary;
                urlConn.addRequestProperty("Content-Type", contentType);

                DataOutputStream request = new DataOutputStream(urlConn.getOutputStream());
                request.writeBytes("\r\n--"+boundary+"\r\n");
                request.writeBytes("Content-Disposition: form-data; name=\"userfile\"; filename=\""+FILE_NAME+"\"\r\n");
                request.writeBytes("Content-Type: application/octet-stream\r\n\r\n");

                File myFile = new File(FILE_PATH);
                int size = (int) myFile.length();
                byte[] bytes = new byte[size];
                try {
                    BufferedInputStream buf = new BufferedInputStream(new FileInputStream(myFile));
                    buf.read(bytes, 0, bytes.length);
                    buf.close();
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } 
                request.write(bytes);
                request.writeBytes("\r\n--"+boundary+"--\r\n");

                request.flush();
                request.close();

                InputStream responseStream = new BufferedInputStream(urlConn.getInputStream());

                BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
                String line = "";
                StringBuilder stringBuilder = new StringBuilder();
                while ((line = responseStreamReader.readLine()) != null)
                {
                    stringBuilder.append(line).append("\n");
                }
                responseStreamReader.close();

                String response = stringBuilder.toString();
                responseStream.close();
                urlConn.disconnect();

                return response;

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if(result != null){
            if(result.toLowerCase().contains("erfolgreich")){
            //If successfull delete File
            File file = new File(FILE_PATH);
            file.delete();
            }
        }   

    }

}
4

1 に答える 1