我想做一個片段,裏面有一個listview,我想用JSON填充listview。我只有一個錯誤,我不知道該把單個錯誤放在哪裏。該錯誤說,無法訪問的聲明,當我把getJSON()下面}它說無效方法聲明Android如何解析JSON到一個擴展片段的類裏面的listtview
這是我的代碼與listview裏面的一個片段。有錯誤指向getJSON();在rootview下面。由於
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();
}
}