我正在尝试做一个里面有listview的片段,我正在尝试使用JSON填充listview。我只有一个错误,我不知道在哪里发出单一错误。
错误指向getJSON();在返回的根视图下面说无效的方法声明
这是我扩展片段的代码,里面是listview
public class News extends Fragment {
private ListView lv;
private String JSON_STRING;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(news, container, false);
lv = (ListView) rootView.findViewById(R.id.listView3);
return rootView;
}
getJSON();
private void showResult(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY1);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String NID = jo.getString(Config.TAG_NID);
String title = jo.getString(Config.TAG_title);
String content = jo.getString(Config.TAG_content);
String n_date = jo.getString(Config.TAG_n_date);
HashMap<String,String> match = new HashMap<>();
match.put(Config.TAG_NID, NID);
match.put(Config.TAG_title,title);
match.put(Config.TAG_content,content);
match.put(Config.TAG_n_date,n_date);
list.add(match);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
getActivity(), list, R.layout.newsadapterlayout,
new String[]{Config.TAG_title,Config.TAG_content, Config.TAG_n_date, Config.TAG_NID},
new int[]{ R.id.title, R.id.content, R.id.n_date});
lv.setAdapter(adapter);
}
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
JSON_STRING = s;
showResult();
}
@Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(Config.URL_NEWS);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
非常感谢任何帮助。谢谢你们
答案 0 :(得分:0)
您无法在方法内声明类。
将private void getJSON()
与类GetJSON
分开,只需将代码移到方法之外,您仍然可以执行; GetJSON gj = new GetJSON();