错误:在BackgroundTask中,我在try块中获取arraylist中的数据,但是当我到达errorListener()之后,我的arrayList变为null。在LogCat中我发现了这些问题。我如何解决这个问题.. ??
package com.example.rahul.volley_jarray;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.util.ArrayList;
public class DisplayList extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Contact> arrayList=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_list);
recyclerView= (RecyclerView) findViewById(R.id.recylerView);
layoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
BackgroundTask backgroundTask=new BackgroundTask(DisplayList.this);
arrayList=backgroundTask.getList();
Log.d("dispaly Array List",""+arrayList.toString());
adapter=new RecyclerAdapter(arrayList);
Log.d("My adapter",arrayList.toString());
recyclerView.setAdapter(adapter);
}
}
错误:在这个地方。 BackgroundTask
package com.example.rahul.volley_jarray;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by rahul on 7/4/2016.
*/
public class BackgroundTask {
Context context;
ArrayList<Contact> arrayList=new ArrayList<>();
String str_url="https://raw.githubusercontent.com/ianbar20/JSON-Volley-Tutorial/master/Example-JSON-Files/Example-Array.JSON";
String data="";
public BackgroundTask(Context context)
{
this.context=context;
}
public ArrayList<Contact> getList()
{
final JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.GET, str_url, (String) null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d("My Json",response.toString());
int count = 0;
while (count < response.length()) {
try {
JSONObject jsonObject = response.getJSONObject(count);
JSONObject jsonObject1 = jsonObject.getJSONObject("phone");
Contact contact = new Contact(jsonObject.getString("name"), jsonObject.getString("email"), jsonObject1.getString("home"));
Log.d("contact", "" + contact.toString());
arrayList.add(contact);
Log.d("arrayList" + count, "" + arrayList.toString());
count++;
} catch (JSONException e) {
e.printStackTrace();
Log.d("Mytag", e.toString());
}
Log.d("arrayList in while" + count, "" + arrayList.toString());
Log.d("arrayList2" + count, "" + arrayList.toString());
if (arrayList.toString() == null) {
Log.d("if first", "null");
} else {
Log.d("else first", "not null");
}
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,"Error...!!!",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
Log.d("final arrayList",""+arrayList.toString());
//return arrayList;
if(arrayList.toString()==null)
{
Log.d("if second","null");
}
else {
Log.d("else second","not null");
}
Log.d("JsonArray Request",""+jsonArrayRequest.toString());
MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
//
return arrayList;
}
}
// MySinglton类 包com.example.rahul.volley_jarray;
import android.content.Context;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
/**
* Created by rahul on 7/4/2016.
*/
public class MySingleton {
private static MySingleton mInstance;
private static Context mCtx;
private RequestQueue requestQueue;
private MySingleton(Context context) {
mCtx = context;
requestQueue = getRequestQueue();
Log.d("request queue", "" + requestQueue.toString());
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return requestQueue;
}
public static synchronized MySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySingleton(context);
}
Log.d("mInstaces", "" + mInstance);
return mInstance;
}
public <T> void addToRequestQueue(Request<T> request) {
Log.d("request",""+request.toString());
requestQueue.add(request);
Log.d("now request queue",""+requestQueue.toString());
}
}
答案 0 :(得分:1)
Volley执行异步请求。当你检查arrayList时它还没有完成(实际上它还没有在队列中),这就是为什么它是null (实际上应该是空的,因为你已经在字段中初始化它,而不是null)
您可以使用自定义侦听器,将其传递到请求类并将其命名为onResponse。
一些伪代码澄清:
//define this interface in background task and implement it in caller activity
public interface CustomReqFinished(){
public void onCustomReqFinished(ArrayList list){}
}
//in backgroundtask constructor store the activity you pass as follows
listener = (CustomReqFinished) activity; //set Activity as param instead of context
//in onResponse do this as last step
listener.onCustomReqFinished(arrayList);
编辑按要求澄清。在DisplayList中修改如下:
public class DisplayList extends AppCompatActivity implements CustomReqFinished {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Contact> arrayList=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_list);
recyclerView= (RecyclerView) findViewById(R.id.recylerView);
layoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
BackgroundTask backgroundTask=new BackgroundTask(this);
backgroundTask.getList();
}
@Override
public void onCustomReqFinished(ArrayList<Contact> list) {
Log.d("dispaly Array List",""+list.toString());
adapter=new RecyclerAdapter(list);
recyclerView.setAdapter(adapter);
}
}
在backgroundTask中修改如下:
public class BackgroundTask {
public interface CustomReqFinished{
public void onCustomReqFinished(ArrayList<Contact> list);
}
Context context;
CustomReqFinished listener;
ArrayList<Contact> arrayList=new ArrayList<>();
String str_url="https://raw.githubusercontent.com/ianbar20/JSON-Volley-Tutorial/master/Example-JSON-Files/Example-Array.JSON";
String data="";
public BackgroundTask(Activity activity)
{
this.context = activity;
this.listener = (CustomReqFinished) activity;
}
public void getList()
{
final JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(str_url, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d("My Json",response.toString());
int count = 0;
while (count < response.length()) {
try {
JSONObject jsonObject = response.getJSONObject(count);
JSONObject jsonObject1 = jsonObject.getJSONObject("phone");
Contact contact = new Contact(jsonObject.getString("name"), jsonObject.getString("email"), jsonObject1.getString("home"));
Log.d("contact", "" + contact.toString());
arrayList.add(contact);
Log.d("arrayList" + count, "" + arrayList.toString());
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
listener.onCustomReqFinished(arrayList);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,"Error...!!!",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
}
}