2013-06-18 6 views
1

채팅 코드를받을 코드가 있습니다. 하지만 나는 그것을 AsyncTask에 넣으려고 할 때 혼란 스러웠습니다. 나는 postexecute에 넣을 때 read.readline()에 대해 경고 read cannot be resolved을 가지고 있습니다.
이 코드가 백그라운드에서 작동하도록하고 싶습니다. 어떤 메시지가오고 있는지 확인하고 싶습니다. 그리고 나는 코드를 항상 백그라운드에서 실행되도록 만들기 위해 물어보고 싶습니다. 사용하려면 AsyncTask을 사용하거나 다른 방법이 있습니까?
아무도 나를 도와주세요, 나는 그것을 만드는 방법을 혼란스러워합니다. 당신은AsyncTask에 코드를 넣기가 혼동했습니다.

메시지 부분을 내가 시도

HttpURLConnection connection; 
     URL url = null; 
     try{ 
      linkurl = new Koneksi(this); 
      SERVER_URL = linkurl.getUrl(); 
      SERVER_URL += "/mobile/ChatRoom.php?idu="+param2+"&idch="+param3+"&idcm="+param4; 
      url = new URL(SERVER_URL); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.setDoOutput(true); 
      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
      connection.setRequestMethod("POST");  

      HttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(SERVER_URL); 
      //ArrayList<NameValuePair> param = new ArrayList<NameValuePair>(); 
      //add parameter 
       //httpPost.setEntity(new UrlEncodedFormEntity(param)); 

       HttpResponse httpRespose = httpClient.execute(httpPost); 
       HttpEntity httpEntity = httpRespose.getEntity(); 

       //read content 
       InputStream in = httpEntity.getContent(); 
       BufferedReader read = new BufferedReader(new InputStreamReader(in)); 
       String msg = "tes"; 
       while(true) 
       { 

        try { 
         msg = read.readLine(); 
         Log.d("","MSGGG: "+ msg); 

         //msgList.add(msg); 
        } catch (IOException e) { 
         // TODO Auto-generated catch block 
         e.getMessage(); 
        } 
        if(msg == null) 
        { 
         break; 
        } 
        else 
        { 
         showMessage(msg, false); 
        } 
       }} 
     catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

      } 

AsyncTask를 일부받을 감사 - 업데이트를하지만 난이 코드를 삽입해야합니다 경우 getintent()에서 경고를 얻을?

public class ReceivedTask extends AsyncTask<String, String, String> { 

    Bundle bundle = this.getIntent().getExtras(); 
    final String param2 = bundle.getString("keyUserId"); 
    final String param3 = bundle.getString("keyChatsId"); 
    String param4 = bundle.getString("keyMessagesId"); 

    @Override 
    protected void onPreExecute() { 
     // TODO Auto-generated method stub 
     super.onPreExecute(); 
    } 

    @Override 
    protected String doInBackground(String... arg0) { 
     // TODO Auto-generated method stub 

     HttpURLConnection connection; 
     URL url = null; 
     try{ 
      linkurl = new Koneksi(ChatRoom.this); 
      SERVER_URL = linkurl.getUrl(); 
      SERVER_URL += "/mobile/ChatRoom.php?idu="+param2+"&idch="+param3+"&idcm="+param4; 
      url = new URL(SERVER_URL); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.setDoOutput(true); 
      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
      connection.setRequestMethod("POST");  

      HttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(SERVER_URL); 
      //ArrayList<NameValuePair> param = new ArrayList<NameValuePair>(); 
      //add parameter 
       //httpPost.setEntity(new UrlEncodedFormEntity(param)); 

       HttpResponse httpRespose = httpClient.execute(httpPost); 
       HttpEntity httpEntity = httpRespose.getEntity(); 

       //read content 
       InputStream in = httpEntity.getContent(); 
       BufferedReader read = new BufferedReader(new InputStreamReader(in)); 
       String msg = "tes"; 
       while(true) 
       { 

        try { 
         msg = read.readLine(); 
         Log.d("","MSGGG: "+ msg); 

         //msgList.add(msg); 
        } catch (IOException e) { 
         // TODO Auto-generated catch block 
         e.getMessage(); 
        } 
        if(msg == null) 
        { 
         break; 
        } 
        else 
        { 
         showMessage(msg, false); 
        } 
       }} 
     catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

      } 
    } 

ChatRoom.java - 내 전체 코드

public class ChatRoom extends Activity { 
    public Koneksi linkurl; 
    String SERVER_URL; 
    private EditText messageText; 
    private TextView meLabel; 
    private TextView friendLabel; 
    private ViewGroup messagesContainer; 
    private ScrollView scrollContainer; 
/* private Handler handler = new Handler();*/ 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.chatpage); 

     messagesContainer = (ViewGroup) findViewById(R.id.messagesContainer); 
     scrollContainer = (ScrollView) findViewById(R.id.scrollContainer); 

     Button sendMessageButton = (Button) findViewById(R.id.sendButton); 

     Bundle bundle = this.getIntent().getExtras(); 
     /*final String paramnama = bundle.getString("nama");*/ 
     messageText = (EditText) findViewById(R.id.messageEdit); 
     meLabel = (TextView) findViewById(R.id.meLabel); 
     friendLabel = (TextView) findViewById(R.id.friendLabel); 
     meLabel.setText("me"); 


     final String param1 = bundle.getString("keyCourseId"); 
     final String param2 = bundle.getString("keyUserId"); 
     final String param3 = bundle.getString("keyChatsId"); 
     String param4 = bundle.getString("keyMessagesId"); 


     sendMessageButton.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 

       ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 
       postParameters.add(new BasicNameValuePair("messages", messageText.getText().toString())); 

       String response = null; 

       try { 
        linkurl = new Koneksi(ChatRoom.this); 
        SERVER_URL = linkurl.getUrl(); 
        SERVER_URL += "/mobile/ChatKirimTeks.php?idu="+param2+"&idch="+param3; 
        response = CourseHttpClient.executeHttpPost(SERVER_URL, postParameters); 

        String res = response.toString(); 

        res = res.trim(); 

        res = res.replaceAll("\\s+",""); 
        if(res.equals("1")){ 
         String messageString = messageText.getText().toString(); 
         showMessage(messageString, true); 
         messageText.getText().clear(); 
        }else 
        { 
         createDialog("Maaf", "Messages Anda Gagal Terkirim"); 
        } 
       } 

       catch (Exception e) { 

        messageText.setText(e.toString()); 

       } 

      } 

     }); 


     HttpURLConnection connection; 
     URL url = null; 
     try{ 
      linkurl = new Koneksi(this); 
      SERVER_URL = linkurl.getUrl(); 
      SERVER_URL += "/mobile/ChatRoom.php?idu="+param2+"&idch="+param3+"&idcm="+param4; 
      url = new URL(SERVER_URL); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.setDoOutput(true); 
      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
      connection.setRequestMethod("POST");  

      HttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(SERVER_URL); 
      //ArrayList<NameValuePair> param = new ArrayList<NameValuePair>(); 
      //add parameter 
       //httpPost.setEntity(new UrlEncodedFormEntity(param)); 

       HttpResponse httpRespose = httpClient.execute(httpPost); 
       HttpEntity httpEntity = httpRespose.getEntity(); 

       //read content 
       InputStream in = httpEntity.getContent(); 
       BufferedReader read = new BufferedReader(new InputStreamReader(in)); 
       String msg = "tes"; 
       while(true) 
       { 

        try { 
         msg = read.readLine(); 
         Log.d("","MSGGG: "+ msg); 

         //msgList.add(msg); 
        } catch (IOException e) { 
         // TODO Auto-generated catch block 
         e.getMessage(); 
        } 
        if(msg == null) 
        { 
         break; 
        } 
        else 
        { 
         showMessage(msg, false); 
        } 
       }} 
     catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

      } 


    public class ReceivedTask extends AsyncTask<String, String, String> { 

     @Override 
     protected void onPreExecute() { 

     } 

     @Override 
     protected String doInBackground(String... arg0) { 
      // TODO Auto-generated method stub 
      HttpURLConnection connection; 
      URL url = null; 
      try{ 
       linkurl = new Koneksi(ChatRoom.this); 
       SERVER_URL = linkurl.getUrl(); 
       SERVER_URL += "/mobile/ChatRoom.php?idu="+param2+"&idch="+param3+"&idcm="+param4; 
       url = new URL(SERVER_URL); 
       connection = (HttpURLConnection) url.openConnection(); 
       connection.setDoOutput(true); 
       connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
       connection.setRequestMethod("POST");  

       HttpClient httpClient = new DefaultHttpClient(); 
       HttpPost httpPost = new HttpPost(SERVER_URL); 
       //ArrayList<NameValuePair> param = new ArrayList<NameValuePair>(); 
       //add parameter 
        //httpPost.setEntity(new UrlEncodedFormEntity(param)); 

        HttpResponse httpRespose = httpClient.execute(httpPost); 
        HttpEntity httpEntity = httpRespose.getEntity(); 

        //read content 
        InputStream in = httpEntity.getContent(); 
        BufferedReader read = new BufferedReader(new InputStreamReader(in)); 
      } 
      catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       return null; 
      } 

     } 
     @Override 
     protected void onPostExecute(String result) { 
      // TODO Auto-generated method stub 
      super.onPostExecute(result); 
      String msg = "tes"; 
      while(true) 
      { 

       try { 
        msg = read.readLine(); 
        Log.d("","MSGGG: "+ msg); 

        //msgList.add(msg); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.getMessage(); 
       } 
       if(msg == null) 
       { 
        break; 
       } 
       else 
       { 
        showMessage(msg, false); 
       } 
      } 
     } 
    } 

    public void showMessage(String message, boolean leftSide) { 
     final TextView textView = new TextView(ChatRoom.this); 
     textView.setTextColor(Color.BLACK); 
     textView.setText(message); 

     int bgRes = R.drawable.left_message_bg; 

     LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
       LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); 

     if (!leftSide) { 
      bgRes = R.drawable.right_message_bg; 
      params.gravity = Gravity.RIGHT; 
     } 

     textView.setLayoutParams(params); 

     textView.setBackgroundResource(bgRes); 

     runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       messagesContainer.addView(textView); 

       // Scroll to bottom 
       if (scrollContainer.getChildAt(0) != null) { 
        scrollContainer.scrollTo(scrollContainer.getScrollX(), scrollContainer.getChildAt(0).getHeight()); 
       } 
       scrollContainer.fullScroll(View.FOCUS_DOWN); 
      } 
     }); 
    } 

    private void createDialog(String title, String text) { 
     AlertDialog ad = new AlertDialog.Builder(this) 
     .setPositiveButton("Ok", null) 
     .setTitle(title) 
     .setMessage(text) 
     .create(); 
     ad.show(); 
    } 
} 
+0

showMessage의 기능은 무엇입니까? doInbackGround()에서 로컬로 읽을 것을 선언하면. 그것을 asynctask 클래스 변수로 선언하면 onPostExecute – Raghunandan

+0

@Raghunandan showMessage에서 사용할 수 있습니다. 메시지를 버블에 넣기 위해 사용합니다. 감사합니다 – blackneko

+0

당신은 UI 폼 doInbackground를 업데이트 할 수 없습니다. – Raghunandan

답변

1

Android에서 사용자 인터페이스 스레드에서 인터넷에 액세스 할 수 없으므로 오류 메시지 read cannot be resolved이 표시됩니다. 당신은 배경 스레드에서 그렇게해야합니다. 사실, AsyncTask을 사용하는 것은 가능한 한 사용자 인터페이스 스레드를 자유롭게 유지하는 것입니다.

나는 항상 AsyncTask을 사용할 때마다 작업의 모든 매개 변수를 포함하는 클래스를 만들고 결과를 저장하는 다른 클래스를 만듭니다. 또한 결과 클래스가 발생할 수있는 오류 조건을 나타낼 수 있는지 확인합니다. 예외가 발생했습니다. 그래서 내가 사용하는 일반적인 템플릿 (NB : 이것은 진행 보고서가 필요하지 않은 경우)과 같습니다.

public class MyActivity extends Activity { 

    static class MyAsyncTaskParameters { 
     // put all the parameters that the task will need here 
    } 

    void KickOffAsynctask(...) { // various arguments as required by the task in hand 
     MyAsyncTaskParameters params = new MyAsyncTaskParameters(...); // package up all the parameters 
     MyAsyncTask newtask = new MyAsyncTask(); 
     newtask.execute(params); 
    } 

    static class MyAsyncTaskResults { 
     // put all the results that the task can generate here 
     // NOTE: errors can occur in tasks, also exceptions 
     //  can be thrown in tasks, so make it possible 
     //  for this class to describe all error conditions that can occur 
    } 

    static class MyAsyncTask extends AsyncTask<MyAsyncTaskParameters, Void, MyAsyncTaskResults> { 

     @Override 
     protected MyAsyncTaskResults doInBackground(MyAsyncTaskParameters... params) { 
      MyAsyncTaskResults results = new MyAsyncTaskResults(); 
      try { 
       MyAsyncTaskParameters taskParameters = params[0]; 
       // This method will run in a background thread, so 
       // do as much as possible of the AsyncTask here. 
      } catch (Throwable e) { 
       // Set results object to indicate that an exception occurred. 
      } 
      return results; 
     } 

     @Override 
     protected void onPostExecute(MyAsyncTaskResults res) { 
      // This method will run in the User Interface thread. 
      // Use it to deal with the results stored in res. 
      // If an error has occurred, the res object will have it stored 
      // so take appropriate action, e.g. report to user. 
     } 

    } 

} 
+0

Stochastically, 제 질문에 답해 주셔서 대단히 감사합니다. D. 설명해 주셔서 감사합니다. 나는 그것을 시도 할 것입니다. : D – blackneko

+0

@blackneko가 그 도움을 전혀하지 않았습니까? – Stochastically

+0

예, 대단히 감사합니다. D – blackneko

0

사용 AsyncTask, doInBackground(...)에서 작업을하고. 거기에서 메시지를 반환하고 onPostExecute(...)에 반환 된 값을 처리합니다.

@Override 
protected void onPostExecute(String result) { 
    String msg = "tes"; // Why? You have 'result' String reference one line above. 

스트림을 onPostExecute으로 읽지 마십시오. 백그라운드 작업의 일부로 수행하십시오. 그렇지 않으면 UI 스레드가 차단됩니다.

onPostExecute을 참조하십시오.

+0

그래서 모든 메시지 부분 코드를'doInBackground (...)'에 넣으시겠습니까? O.o 감사합니다. – blackneko

+0

물론 가능합니다. 당신의 메시지가 아주 아주 아주 아주 아주 아주 아주 아주 긴 경우에? 스트림을 읽는 스레드를 차단합니다. – SK9

+0

owie .. 내 나쁜 ... 다른 코드에서 복사했기 때문에 깜빡 했네. 죄송합니다 .. – blackneko

관련 문제