2016-12-08 77 views
1

因此,在Java中,我寫了一個典型的類,將json發送到其他服務器。 (我將包括下列全班的清晰度。)所以這是一個文件「Fetcher.java」Java中的「標準簡單」接口?

現在,您需要一個接口回調。接口很簡單,只是一個帶有字符串的函數。

public interface FetcherInterface { 
    public void fetcherDone(String result); 
} 

煩人,你需要爲整個文件,「FetcherInterface.java」

那麼這個接口是什麼,但「一個回調函數的字符串」。通常你需要的僅僅是「一次回調,沒有參數」。

其實........ 是否有某種標準接口我可以使用或類似的東西?

對於這樣一個簡單的「標準」接口,必須放入一個完整的接口似乎有點煩人。

這是怎麼回事?什麼是javaly解決方案?

看來你不能把它在同一個文件

enter image description here

也許我誤解的東西在那裏。如果你可以把它放在同一個文件中,那至少會很方便。

(lambda表達式尚未實際可用的。不管怎麼說,有時候你想要的界面。)


只是爲了清楚起見,這裏是你如何調用類

JSONObject j = new JSONObject(); 
    try { 
     j.put("height", 2.1); 
     j.put("width", 2.5); 
     j.put("command", "blah"); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    new Fetcher("mobile/login", j, new FetcherInterface() { 
       @Override 
       public void fetcherDone(String result) { 
        Log.d("DEV","all done"); 
        doSomething(result); 
       } 
     } 
    ).execute(); 

或確實

public class HappyClass extends Activity implements FetcherInterface { 
... 

private void someCall() { 
    JSONObject j = new JSONObject(); 
    try { 
     j.put("height", 2.1); 
     j.put("width", 2.5); 
     j.put("command", "blah"); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    new Fetcher("mobile/data", j, this).execute(); 
    devBlank(); 
} 

@Override 
public void fetcherDone(String result) { 
    Log.d("DEV","all done" +result); 
    doSomething(result); 
} 

這裏是全班... Fetcher.java文件

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

    private String urlTail; 
    private JSONObject jsonToSend; 
    private FetcherInterface callback; 

    // initializer... 
    Fetcher(String ut, JSONObject toSend, FetcherInterface cb) { 
     urlTail = ut; 
     jsonToSend = toSend; 
     callback = cb; 
    } 

    @Override 
    protected String doInBackground(Void... params) { 

     HttpURLConnection urlConnection = null; // declare outside try, to close in finally 
     BufferedReader reader = null;   // declare outside try, to close in finally 
     String rawJsonResultString = null; 
     String json = jsonToSend.toString(); 

     Log.d("DEV","the json string in Fetcher is " +json); 

     try { 
      URL url = new URL("https://falcon.totalfsm.com/" + urlTail); 

      Log.d("DEV","the full URL in Fetcher is " +url); 

      // open a json-in-the-body type of connection....... 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      urlConnection.setRequestMethod("POST"); 
      urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); 
      urlConnection.setDoOutput(true); 
      urlConnection.setDoInput(true); 
      urlConnection.setConnectTimeout(5000); 
      // urlConnection.setDoOutput(false); // can be important? 

      urlConnection.connect(); 

      OutputStream os = urlConnection.getOutputStream(); 
      os.write(json.getBytes("UTF-8")); 
      os.close(); 

      // annoyingly, you have to choose normal versus error stream... 
      InputStream inputStream; 
      int status = urlConnection.getResponseCode(); 
      if (status != HttpURLConnection.HTTP_OK) 
       inputStream = urlConnection.getErrorStream(); 
      else 
       inputStream = urlConnection.getInputStream(); 
      if (inputStream == null) { // nothing to do. 
       return null; 
      } 

      StringBuffer buffer = new StringBuffer(); 
      reader = new BufferedReader(new InputStreamReader(inputStream)); 
      String line; 
      while ((line = reader.readLine()) != null) { // adding newlines makes debugging easier 
       buffer.append(line + "\n"); 
      } 

      if (buffer.length() == 0) { // stream was empty 
       return null; 
      } 

      rawJsonResultString = buffer.toString(); 
      return rawJsonResultString; 

     } catch (IOException e) { 
      Log.e("PlaceholderFragment", "Error ", e); 
      return null; 
     } finally{ 
      if (urlConnection != null) { 
       urlConnection.disconnect(); 
      } 
      if (reader != null) { 
       try { 
        reader.close(); 
       } catch (final IOException e) { 
        Log.e("PlaceholderFragment", "Error closing stream", e); 
       } 
      } 
     } 
    } 

    @Override 
    protected void onPostExecute(String s) { 
     super.onPostExecute(s); 
     Log.d("DEV", "Fetcher done"); 
     if (s==null) { 
      Log.d("DEV","applying anti-null measures in Fetcher!"); 
      s = "message from app communications layer: 'null' returned from servers for that call at " +urlTail; 
     } 
     callback.fetcherDone(s); 
    } 
} 
+1

根據[文檔](https://developer.android.com/guide/platform/j8-jack.html),Android支持lambdas。如果您的API等級爲23或更低,則需要額外做一些工作。 –

+0

嗨泰德,謝謝,正如我所說,我欣賞lambda是一種即將到來的可能性。你知道有關於接口問題的答案嗎?有沒有「標準接口」或類似的東西? – Fattie

+0

'煩人的你需要一個完整的文件,「FetcherInterface.java」'不一定。您可以將該類放入另一個Java文件中,即:一個Activity類。 –

回答

1

我不好回答我自己的問題,但由於沒有其他答案,此信息可能會有所幫助。

DaveNewton和Rowtang在這裏提供的確切的答案:

(點1)如果你想要一個真正公共接口,它會在自己的文件。這就是Java的工作原理。沒有別的選擇。

(點2)通常,使用protected interface並宣告內部類接口。它可以在整個應用程序中使用。

所以......

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

    protected interface FetcherInterface { 
     public void fetcherDone(String result); 
    } 

    private String urlTail; 
    private JSONObject jsonToSend; 
    private FetcherInterface callback; 

    Fetcher(String ut, JSONObject toSend, FetcherInterface cb) { 
     urlTail = ut; 
     jsonToSend = toSend; 
     callback = cb; 
    } 

    @Override 
    protected String doInBackground(Void... params) { 
    .... 

(C#程序員也許會稱之爲 「IFetcher」。)