Android功能不会返回完整的ArrayList。

huangapple go评论77阅读模式
英文:

Android function doesn't return full ArrayList

问题

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);
    }
}
英文:

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&lt;String&gt; arrayList = new ArrayList&lt;String&gt;();
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(&quot;Ootmarsum&quot;);
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&lt;String&gt; jsonParse() {
final ArrayList&lt;String&gt; steden = new ArrayList&lt;String&gt;();
String url = &quot;https://android.frielinck.net/?format=json&quot;;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener&lt;JSONObject&gt;() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray(&quot;data&quot;);
for (int i = 0; i &lt; jsonArray.length(); i++) {
JSONObject employee = jsonArray.getJSONObject(i);
String city = employee.getString(&quot;city&quot;);
steden.add(city);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
return (steden);
}
}

答案1

得分: 1

当您调用jsonParse()时,它会在后台线程上进行调用,您的主线程会继续执行下一行代码,并且不会等待从jsonParse()获取响应。

就像您的代码一样,它会将ArrayList(该ArrayList尚未填充,因为后台线程尚未完成)传递给适配器。

在适配器获取其列表之后,后台线程可能会完成并返回列表,并将其添加到ArrayList中,但这不会影响已经创建的适配器。

查看此答案了解更多

英文:

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

答案2

得分: 0

以下是翻译好的内容:

  1. 将 jsonParse 更改为以下内容,并在 for 循环结束时调用 updateLV();
   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. 添加一个名为 updateLV() 的新函数;
  private void updateLV(){
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
        listview.setAdapter(arrayAdapter);
    }
英文:

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&lt;String&gt; steden = new ArrayList&lt;String&gt;();
String url = &quot;https://android.frielinck.net/?format=json&quot;;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener&lt;JSONObject&gt;() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray(&quot;data&quot;);
for (int i = 0; i &lt; jsonArray.length(); i++) {
JSONObject employee = jsonArray.getJSONObject(i);
String city = employee.getString(&quot;city&quot;);
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);
}

huangapple
  • 本文由 发表于 2020年4月8日 23:31:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/61104399.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定