Залп - получить данные от onResponse - PullRequest
0 голосов
/ 08 ноября 2018

У меня проблема с использованием Volley, я не могу получить данные из метода OnResponse. Мне нужно использовать Список снаружи, для операций с фрагментами, но я не смог получить его оттуда. Возможно, я делаю что-то не так, но мне не удалось найти решение на других сайтах.

Может кто-нибудь помочь мне найти решение, пожалуйста?

Вот мой код:

public class MainActivity extends AppCompatActivity
{

private static final String JSON_URL = "http://Something/v1/Api.php?apicall=gettopics";

ListView listView;
List<Topic> topicList;
List<Topic> topicList2;


@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    listView = (ListView) findViewById(R.id.listViewTopics);
    topicList = new ArrayList<>();
     loadTopics();
    if(topicList.isEmpty())
    {
        TextView t = findViewById(R.id.text);
        t.setText("Empty");
    }
}


class TopicAdapter extends ArrayAdapter<Topic>
{
    List<Topic> topicList;

    public List<Topic> getTopicList() {
        return topicList;
    }

    public TopicAdapter(List<Topic> topicList)
    {
        super(MainActivity.this, R.layout.layout_topic_list, topicList);
        this.topicList = topicList;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        LayoutInflater inflater = getLayoutInflater();
        View listViewItem = inflater.inflate(R.layout.layout_topic_list, null, true);

        TextView textViewName = listViewItem.findViewById(R.id.textViewTitle);

        final Topic topic = topicList.get(position);
        textViewName.setText(topic.getTitle());
        return listViewItem;
    }

}

public void loadTopics() {
    StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject obj = new JSONObject(response);
                        JSONArray topicArray = obj.getJSONArray("topics");
                        for (int i = 0; i < topicArray.length(); i++) {
                            JSONObject topicObject = topicArray.getJSONObject(i);
                            Topic topic = new Topic(topicObject.getInt("id"),topicObject.getInt("ordering"),topicObject.getString("title"));
                            topicList.add(topic);
                        }
                        TopicAdapter adapter = new TopicAdapter(topicList);
                        listView.setAdapter(adapter);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },

            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //displaying the error in toast if occurrs
                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });


    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

}

1 Ответ

0 голосов
/ 09 ноября 2018

Сначала в onCreate():

topicList = new ArrayList<>();
listView = (ListView) findViewById(R.id.listViewTopics);
adapter = new TopicAdapter(topicList); //note:define 'adapter' as a class field as 'listView' 
listView.setAdapter(adapter);

Затем в onResponse():

 topicList.clear();
 try{
     JSONObject obj = new JSONObject(response);
     JSONArray topicArray = obj.getJSONArray("topics");
     for (int i = 0; i < topicArray.length(); i++) {
         JSONObject topicObject = topicArray.getJSONObject(i);
         Topic topic = new Topic(topicObject.getInt("id"),topicObject.getInt("ordering"),topicObject.getString("title"));
         topicList.add(topic);
     }
     adapter.notifyDataSetChanged();
   } catch (JSONException e) {
     e.printStackTrace();
   }
...