如何使用Android中的Retrofit 2.0获取股票代码和价格

时间:2016-07-04 22:27:19

标签: android listview retrofit retrofit2

我想使用Retrofit 2.0来获取股票代码和价格,然后在列表视图中显示它们。问题是我正在努力编写我的ApiService类,因此我可以发出异步请求。

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**
 }
}

我根据从此网址返回的json数据创建了我的POJO:

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>

1 个答案:

答案 0 :(得分: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>() {
        // ...
    });