Эй, я новичок в фрагментах в андроиде. У меня есть 3 фрагмента, и это второй. Я хочу, чтобы данные были установлены в виде списка из api json. Я использую библиотеку Volley.Json parsing by RequestQueue Волейбол в фрагментах, дающих неожиданные ответы?
Но когда я запустил это, ничего не задано в текстовом режиме, и журналы показывают, что requestqueue работает, но не отображается. Я использовал то же самое в обычной деятельности и там работал, но не здесь.
Пожалуйста, помогите мне с этим.
TwoFragment .java
public class TwoFragment extends Fragment {
RequestQueue requestQueue;
String url = "apiUrl";
ArrayList<HistoryEx> histories;
HistoryAdapterEx historyAdapter;
ListView lv;
TextView tv;
public TwoFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_two, null);
histories = new ArrayList<>();
historyAdapter = new HistoryAdapterEx(getActivity(),histories);
lv = (ListView) getView().findViewById(R.id.recentex);
lv.setAdapter(historyAdapter);
getRecent();
return v;
}
void getRecent() {
requestQueue = Volley.newRequestQueue(this.getActivity());
JsonObjectRequest jor = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray ja = response.getJSONArray("entries");
for (int i = 0; i < ja.length(); i++) {
JSONObject jb = ja.getJSONObject(i);
String extype = jb.getString("type");
String exname = jb.getString("name");
HistoryEx history = new HistoryEx();
history.setExname(exname);
history.setExtype(extype);
histories.add(history);
tv.setText(exname);
}
//while ends to get object
} catch (JSONException e) {
e.printStackTrace();
}
}//onresponse
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error in loading history.", Toast.LENGTH_LONG).show();
Log.e("Volley", error.toString());
}
}
) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", "jjhj");
return headers;
}
};
requestQueue.add(jor);
/*
end of Json parsing
*/
}
}
HistoryAdapterEx.java
public class HistoryAdapterEx extends BaseAdapter {
ArrayList<HistoryEx> histories;
LayoutInflater inflater;
Activity activity;
public HistoryAdapterEx(Activity activity, ArrayList groups){
super();
this.histories =new ArrayList<>();
this.activity=activity;
this.histories =groups;
}
public int getCount() {
return histories.size();
}
public Object getItem(int i) {
return histories.get(i);
}
public long getItemId(int i) {
return 0;
}
public View getView(int i, View view, ViewGroup viewGroup) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.list_item_ex1, null);
TextView name = (TextView) view.findViewById(R.id.exercise);
TextView ac1 = (TextView) view.findViewById(R.id.Achieved1);
TextView ac2 = (TextView) view.findViewById(R.id.Achieved2);
TextView ac3 = (TextView) view.findViewById(R.id.Achieved3);
TextView ta1 = (TextView) view.findViewById(R.id.target1);
TextView ta2 = (TextView) view.findViewById(R.id.target2);
TextView ta3= (TextView) view.findViewById(R.id.target3);
HistoryEx history = histories.get(i);
System.out.println("ex.. "+history);
name.setText(history.getExname());
ac1.setText(history.getExname());
ac2.setText(history.getExname());
ac3.setText(history.getExname());
ta1.setText(history.getExtype());
ta2.setText(history.getExtype());
ta3.setText(history.getExtype());
//interests.setText(history.getDescription());
//description.setText(history.getInterests());
return view;
}
}
Спасибо за ответ, но оно не работает с этим. Я нашел решение, я не добавил historyAdapter.notifyDataSetChanged(); после разбора :( –
@AbhishekSeth, потому что вы ничего не добавили к истории. Список перед настройкой истории. Список адаптера и когда вы выполняете historyAdapter.notifyDataSetChanged(); изменение списка историй отражает адаптер. –
Что делать, если 'getRecent' метод имеет вызов веб-сервиса внутри него? Будет ли он ждать, прежде чем возвращать представление с данными? –