在RecyclerView中显示GET okhttp gson数据时类强制转换异常

时间:2018-04-03 10:09:59

标签: android listview android-recyclerview recycler-adapter

public class MainActivity extends AppCompatActivity {
private static final String URL = "http://simplifiedcoding.net/demos/marvel";
public RecyclerView recyclerView;
public RecyclerAdapter adapter;
OkHttpClient client;
private  ProgressDialog progressDialog;
private Hero[] heroes;
private List<String> demo;
private List<Hero> heroList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    demo=new ArrayList<>();
    heroList=new ArrayList<>();
    recyclerView=findViewById(R.id.recyclerview);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    new PostDataToServer().execute();
    adapter=new RecyclerAdapter(getApplicationContext(),heroList);
    recyclerView.setAdapter(adapter);
}
public class PostDataToServer extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog=new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("please wait ...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }
    @Override
    protected Void doInBackground(Void... arg0) {
        try {
            client = new OkHttpClient();
            String response=ResponseApi.GET(client, URL);
            Gson gson=new Gson();
            Type type=new TypeToken<Collection<Hero>>() {}.getType();
            Collection<Hero> enums=gson.fromJson(response,type);
            heroes=enums.toArray(new Hero[enums.size()]);
        }
        catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        for (int i=0;i<heroes.length;i++) {
            String it = heroes[i].getName();
            Toast.makeText(getApplicationContext(),it, Toast.LENGTH_SHORT).show();
            demo.add(it);
        }
        adapter.notifyDataSetChanged();
    }
}

}

public static String GET(OkHttpClient client,String url) throws IOException {
    Request request = new Request.Builder()
            .url(url)
            .build();
    Response response = client.newCall(request).execute();
    return response.body().string();
}

我为GET方法创建了一个单独的类,它接受参数HTTP客户端和url。和一个单独的类Hero,其中包含构造函数和getter以及setter。我还创建了一个单独的RecyclerAdapter类。 在这里,我无法在List<Hero>中添加数据。 所以我在List<String>添加了数据 我也无法将list<string>对象转换为List<Hero>对象。 所以,我无法在Recycler视图中显示数据。 请提前帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

我建议使用网络操作进行改造2.0。 使用下面的代码.. 在gradle文件中添加以下依赖项。

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'

然后为api调用接口,如下所示..

interface ApiInterface {
@GET("marvel/")
fun getData(): Call<List<Hero>>

}

然后在下面制作改造对象..

类ApiClient {

companion object {
    val BASE_URL = "https://simplifiedcoding.net/demos/"
    var retrofit: Retrofit? = null
    fun getClient(): Retrofit? {
        if (retrofit == null) {
            val interceptor = HttpLoggingInterceptor()
            interceptor.level = HttpLoggingInterceptor.Level.BODY
            val client = OkHttpClient.Builder().apply {
            readTimeout(20, TimeUnit.SECONDS)
            writeTimeout(20, TimeUnit.SECONDS)
            connectTimeout(20, TimeUnit.SECONDS)
            addInterceptor(interceptor)
            addInterceptor { chain ->
                var request = chain.request()
                request = request.newBuilder()
                        .build()
                val response = chain.proceed(request)
                response
            }
            }
            retrofit = Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client.build())

                    .addConverterFactory(GsonConverterFactory.create())
                    .build()

        }

        return retrofit
    }
}

} 然后在主要活动中调用并从服务器获取数据,如下所示..

 private fun getHeroData() {
    val dialog= ProgressDialog(mContext)
    showProgress(dialog)
    var apiInterface: ApiInterface = ApiClient.getClient()!!.create(ApiInterface::class.java)
    var hero: Call<List<Hero>>
    hero = apiInterface.getData()
    hero.enqueue(object : Callback<List<Hero>> {
        override fun onFailure(call: Call<List<Hero>>?, t: Throwable?) {
            closeDialog(dialog)
            Toast.makeText(mContext, t?.message, Toast.LENGTH_SHORT).show()
            Log.d("Error:::",t?.message)
        }

        override fun onResponse(call: Call<List<Hero>>?, response: Response<List<Hero>>?) {
           mHeroDataList.clear()
            if (response != null && response.isSuccessful && response.body() != null) {
                closeDialog(dialog)
                mHeroDataList .addAll(response.body()!!)
                setAdapter(mHeroDataList)
            }
        }

    })
}