2016-05-28 11 views
1

私はアンドロイドでAsyncTaskを使用してサーバーにリクエストし、別のクラスにデータを受け取ります。私はAsyncTaskが何も返さないことを知っているので、インターフェイスを使って文字列を返すために他の人が作ったコードを使っていました。返信インターフェイス付きのAndroidでのAsyncTask

ここでは、AsyncTaskクラスのコードがあります。今

public class WebRequest extends AsyncTask<String, Void, String> { 

//Data 
public String mFileContents = "false"; 

//API-Info 
public WebRequestResponse delegate = null; 

public WebRequest(WebRequestResponse asyncResponse) { 
    delegate = asyncResponse;//Assigning call back interfacethrough constructor 
} 


@Override 
protected String doInBackground(String... params) { 
    mFileContents = downloadFile(params[0]); 
    if(mFileContents == null) { 
     Log.d("DownloadData", "Error Downloading"); 
    } 
    return mFileContents; 
} 

protected void oonPostExecute(String result) { 
    super.onPostExecute(result); 
    delegate.processFinish(mFileContents); 
    Log.d("DownloadData", "Result was: " + result); //result 
} 

private String downloadFile(String urlPath) { 
    StringBuilder tempBuffer = new StringBuilder(); 
    try { 
     URL url = new URL(urlPath); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     int response = connection.getResponseCode(); 
     Log.d("DownloadData", "The response code was " + response); 
     InputStream is = connection.getInputStream(); 
     InputStreamReader isr = new InputStreamReader(is); 

     int charRead; 
     char[] inputBuffer = new char[500]; 
     while(true){ 
      charRead = isr.read(inputBuffer); 
      if(charRead <=0) { 
       break; 
      } 
      tempBuffer.append(String.copyValueOf(inputBuffer, 0, charRead)); 
     } 

     return tempBuffer.toString(); 

    } catch(IOException e) { 
     Log.d("DownloadData", "IO Exception reading data: " + e.getMessage()); 
     e.printStackTrace(); 
    } catch(SecurityException e) { 
     Log.d("DownloadData", "Security exception. Needs permissions? " + e.getMessage()); 
    } 
    return null; 
} 

} 

、インタフェース:同期クラスで

public interface WebRequestResponse { 
void processFinish(String output); 
} 

私はこれがあります。

public class API implements WebRequestResponse { 

をそして私が作るの以下のように実行します。

public static void StartRequest(String url) { 
    String response = null; 
    WebRequest Request = new WebRequest(new WebRequestResponse() { 

     @Override 
     public void processFinish(String output) { 
      Test(output); //Testing the response code 
     } 
    }); 
    Request.execute(url); 
} 

コードは決して呼び出されず、何も返されないという問題があります。 Log.dを使用して私はここから何も動作しないことがわかりました: "delegate.processFinish(mFileContents);" AsyncTaskクラスに割り当てられています。私は間違って何をしていますか?

おかげRucsiへ

+3

oをダブルでonPostExecuteを足すたことがわかっあなたは二重の「OO」と ''保護された無効oonPostExecute(文字列の結果を)書くことを意味していましたか? – Rucsi

+0

笑....ありがとうxDDD – Onelio

+0

:)うれしい私は助けることができました!この種のエラーが起こらないように注釈@overrideを追加することは良い習慣であることに注意してください。 – Rucsi

答えて

2

おかげで、私彼は私が

関連する問題