简体   繁体   中英

Android function doesn't return full ArrayList

So i'm trying to get some data into a listview. I'm calling the function jsonParse() to fill my ArrayList, which is used by my arrayAdapter. But when i'm running my app the listview isn't filled.

I can see in debug mode that the arraylist 'steden' does indeed get filled with data from my url. However, when it returns the arraylist, it is empty. How can i make sure it doesn't empty itself?

package com.example.taxifooi;
import android.content.Intent;
import android.os.Bundle;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


public class Locatie extends AppCompatActivity {
    private RequestQueue mQueue;
    private String naam;
    private String coord;
    private String stad;
    private FloatingActionButton fab;
    ArrayList<String> arrayList = new ArrayList<String>();
    ListView listview;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_locatie);
        listview = (ListView) findViewById(R.id.listview);
        fab = findViewById(R.id.locationFab);
        mQueue = Volley.newRequestQueue(this);
        jsonParse();
        arrayList.add("Ootmarsum");

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Locatie.this, newLocation.class);
                Locatie.this.startActivity(intent);
            }
        });

        ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
        listview.setAdapter(arrayAdapter);
        arrayAdapter.add(jsonParse());
    }



    public ArrayList<String> jsonParse() {
        final ArrayList<String> steden = new ArrayList<String>();
        String url = "https://android.frielinck.net/?format=json";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("data");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject employee = jsonArray.getJSONObject(i);
                                String city = employee.getString("city");
                                steden.add(city);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        mQueue.add(request);
        return (steden);
    }

}

When you call jsonParse() it will make call on background thread, and your main thread go for run next line, and it will not wait to get response from jsonParse() .

And as your code it will pass the arrayList (which is yet not filled as background thread not completed yet) to adapter.

After adapter got their list, your background thread might complete and return lisst and add it to arrayList, but it will not affect on already created adapter.

Check this answer for more

with a little help figured it out.

  1. Change the jsonParse to this, and call updateLV(); at the end of the for loop.
   private void jsonParse() {
        final ArrayList<String> steden = new ArrayList<String>();
        String url = "https://android.frielinck.net/?format=json";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("data");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject employee = jsonArray.getJSONObject(i);
                                String city = employee.getString("city");
                                arrayList.add(city);

                            }
                            updateLV();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        mQueue.add(request);
    }
  1. add a new function called updateLV();
  private void updateLV(){
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
        listview.setAdapter(arrayAdapter);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM