我正在尝试使用Volley在Fragment中使用GSON解析JSON。但我在两个地方得到编译时错误
new Response.Listener<String>
:说听众无法解决
new Response.ErrorListener()
:说无法解析ErrorListener
无法解析方法“fromJson”
public class Gson extends Fragment
{
RecyclerView recyclerView;
Response responseobj;
CustomAdapter customAdapter;
String url = "https://newsapi.org/v1/articles?source=techcrunch&apiKey=ed28d2d13805495a9b896ecb0c7b6ed1";
Gson gson;
RequestQueue requestQueue;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.gson, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.movielist);
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
StringRequest stringRequest = new StringRequest( com.android.volley.Request.Method.GET, url, new Response.Listener<String>()
{
@Override
public void onResponse(String response)
{
// Do something with the response
gson = new Gson();
responseobj = gson.fromJson(response, Response.class);
customAdapter = new CustomAdapter(getActivity().getApplicationContext(), responseobj.getArticles());
recyclerView.setAdapter(customAdapter);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
// Handle error
}
});
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
requestQueue.add(stringRequest);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("GSON Parsing");
}
}
答案 0 :(得分:0)
我认为问题出在你的Response类中,根据你的链接应该是这样的:
public class FragmentGson extends Fragment
其次更改您的片段名称(可能是您导入错误)
- src [Folder]
- content [Folder]
- migrations [Folder]
- __init__.py
- admin.py
- apps.py
- models.py
- tests.py
- views.py
- main [Folder]
- settings [Folder]
- __init__.py
- base.py
- migrations [Folder]
- __init__.py
- db.sqlite3
- models.py
- urls.py
- views.py
- wsgi.py
- posts [Folder]
- migrations [Folder]
- templatetags [Folder]
- __init__.py
- admin.py
- apps.py
- forms.py
- models.py
- tests.py
- urls.py
- utils.py
- views.py
- templates
- base.html
- blogbase.html
答案 1 :(得分:0)
如果您收到无法解析Reponse.listener的消息,可能是因为它未知。您是否正确添加了像compile 'com.android.volley:volley:1.0.0'
这样的Volley依赖项并在Fragment中正确导入了Volley?
答案 2 :(得分:0)
从您粘贴的代码中,我发现Response responseobj
指的是您在片段中创建并导入的Response类。与此同时,您正在使用new Response.Listener<>()
,它应该是排球库中Response
类的实例。现在如果未导入凌空的Response
,它将显示错误。
这意味着您还必须从排球中导入Response
课程。确保你已经添加了这两个导入。
import com.android.volley.Response;
第二件事是,您必须将片段名称从Gson
更改为其他内容。否则会引起问题