2016-07-04 35 views
0

我想使用Retrofit 2.0獲取股票代碼和價格,然後在列表視圖中顯示它們。問題是我努力編寫我的ApiService類,所以我可以做出異步請求。如何在Android中使用Retrofit 2.0獲取股票代碼和價格

public final class StockApiService { 

public interface StockApiServiceInterface { 
    // unsafe=true ensures unsafe response. Prevents HTML escape characters 
    @GET("/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=") 
    Call<ResultWrapper> listQuotes(
    **// I don’t know what to write here** 
} 
} 

我創建了基於POJO從這個URL返回的JSON數據:

https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback= 

這裏是我的代碼的其餘部分。

ResultWrapper

public class ResultWrapper { 

    @SerializedName("query") 
    @Expose 
    private Query query; 

    /** 
    * 
    * @return 
    *  The query 
    */ 
    public Query getQuery() { 
     return query; 
    } 

    /** 
    * 
    * @param query 
    *  The query 
    */ 
    public void setQuery(Query query) { 
     this.query = query; 
    } 

} 

查詢

public class Query { 

    @SerializedName("count") 
    @Expose 
    private Integer count; 
    @SerializedName("created") 
    @Expose 
    private String created; 
    @SerializedName("lang") 
    @Expose 
    private String lang; 
    @SerializedName("results") 
    @Expose 
    private Results results; 

    /** 
    * 
    * @return 
    *  The count 
    */ 
    public Integer getCount() { 
     return count; 
    } 

    /** 
    * 
    * @param count 
    *  The count 
    */ 
    public void setCount(Integer count) { 
     this.count = count; 
    } 

    /** 
    * 
    * @return 
    *  The created 
    */ 
    public String getCreated() { 
     return created; 
    } 

    /** 
    * 
    * @param created 
    *  The created 
    */ 
    public void setCreated(String created) { 
     this.created = created; 
    } 

    /** 
    * 
    * @return 
    *  The lang 
    */ 
    public String getLang() { 
     return lang; 
    } 

    /** 
    * 
    * @param lang 
    *  The lang 
    */ 
    public void setLang(String lang) { 
     this.lang = lang; 
    } 

    /** 
    * 
    * @return 
    *  The results 
    */ 
    public Results getResults() { 
     return results; 
    } 

    /** 
    * 
    * @param results 
    *  The results 
    */ 
    public void setResults(Results results) { 
     this.results = results; 
    } 

} 

報價

public class Quote { 

    @SerializedName("symbol") 
    @Expose 
    private String symbol; 

    public String getAsk() { 
     return ask; 
    } 

    public void setAsk(String ask) { 
     this.ask = ask; 
    } 

    public String getSymbol() { 
     return symbol; 
    } 

    public void setSymbol(String symbol) { 
     this.symbol = symbol; 
    } 

    @SerializedName("Ask") 
    @Expose 

    private String ask; 


} 

結果

public class Results { 

    @SerializedName("quote") 
    @Expose 
    private Quote quote; 

    /** 
    * 
    * @return 
    *  The quote 
    */ 
    public Quote getQuote() { 
     return quote; 
    } 

    /** 
    * 
    * @param quote 
    *  The quote 
    */ 
    public void setQuote(Quote quote) { 
     this.quote = quote; 
    } 

} 

MainActivity

public class MainActivity extends Activity{ 

private static final String API_BASE_URL = "http://query.yahooapis.com/v1/public/"; 
private Call<ResultWrapper> call; 
private ResultWrapper mResultWrapper; 
private List<Quote> items; 
private QuoteAdapter mQuoteAdapter; 
private String symbol = "symbol"; 

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

    // Random boolean used to generate Network error code by changing Stack Overflow API version 
    //random = new Random(); 
    //if (random.nextBoolean()){ 
    // version = "2.2"; 
    //} else { 
    // version = "fail"; 
    //} 

    Retrofit retrofit = new Retrofit.Builder() 
     .baseUrl(API_BASE_URL) 
     .addConverterFactory(GsonConverterFactory.create()) 
     .build(); 

    mQuoteAdapter = new QuoteAdapter(items); 
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.question_list); 
    recyclerView.setLayoutManager(new LinearLayoutManager(this)); 
    recyclerView.setAdapter(mQuoteAdapter); 

    StockApiServiceInterface stockApiServiceInterface = retrofit.create(StockApiServiceInterface.class); 

    call = stockApiServiceInterface.listQuotes(symbol); 
    call.enqueue(new Callback<ResultWrapper>() { 
    @Override public void onResponse(Response<ResultWrapper> response) { 
     try { 
     mResultWrapper = response.body(); 
     items = mResultWrapper.getQuery().getResults().getQuote(); 
       //questionsAdapter.swapList(items); 
     } catch (NullPointerException e){ 
     Toast toast = null; 
     if (response.code() == 401){ 
      toast = Toast.makeText(MainActivity.this, "Unauthenticated", Toast.LENGTH_SHORT); 
     } else if (response.code() >= 400){ 
      toast = Toast.makeText(MainActivity.this, "Client Error " + response.code() 
       + " " + response.message(), Toast.LENGTH_SHORT); 
     } 
     toast.show(); 
     } 
    } 

    @Override public void onFailure(Throwable t) { 
     Log.e("listQuotes threw: ", t.getMessage()); 
    } 
    }); 
} 

@Override protected void onStop() { 
    super.onStop(); 
    // Unsubscribe 
    call.cancel(); 
} 

@Override public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
    return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 
} 

activity_main.xml中

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    tools:context=".MainActivity"> 

<android.support.v7.widget.RecyclerView 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/question_list"/> 

</FrameLayout> 

question_item.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:id="@+id/question_item" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:minHeight="?android:attr/listPreferredItemHeight" 
     android:id="@+id/title"/> 
</LinearLayout> 

回答

2

您可以添加參數,每次修改請求。 例如:

public final class StockApiService { 

    public interface StockApiServiceInterface { 

     @GET("/yql?format=json&callback=") 
     Call<ResultWrapper> listQuotes(
       @Query("q") String query, 
       @Query("env") String env 
     ); 
    } 
} 

然後,你可以這樣調用:

stockApiServiceInterface.listQuotes(
     "select * from yahoo.finance.quotes where symbol in (\"YHOO\")", 
     "store://datatables.org/alltableswithkeys") 
    .enqueue(new Callback<ResultWrapper>() { 
     // ... 
    }); 
+0

感謝您的及時答覆,我改變了我的StockAPIService按照你的建議。現在只是想知道我在onResponse()中添加了什麼:call = stockApiServiceInterface.listQuotes( 「select * from yahoo.finance.quotes where symbol in(\」YHOO \「)」, 「store://datatables.org/ ())getQuery()。getResults()。getQuote (); //什麼代碼應該去這裏? } –

+0

@ D.Ace只需用請求主體的數據更新UI或者存儲數據供以後使用 – larsgrefer

+0

嗨我今天測試過了,它沒有返回正確的url。its returns this:http://query.yahooapis.com/yql?format=json&callback=&q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol% 20英寸20%(%22YHOO%22)&ENV =商店://datatables.org/alltableswithkeys –