2016-07-06 39 views
-3

錯誤響應後變成空:在BackgroundTask我得到在try塊ArrayList中的數據,但是當我errorListener後達到()之後,我的ArrayList變成零。在LogCat中我發現了這些問題。我如何解決這個問題..?的ArrayList中jsonArrayRequest

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

你什麼錯誤?請堆棧跟蹤。 – SlashG

+0

你的arrayList不是null,但它可能是空的。 'arrayList.toString()== null'是無稽之談。你知道你的JSON請求是排隊和異步處理嗎?你知道* callback *或* listener *是什麼嗎? – JimmyB

+0

沒有錯誤。我的arrayList變爲null,所以沒有在recylerView中顯示? –

回答

1

排氣會執行異步請求。當您檢查的ArrayList它尚未完成(實際上它甚至不是在隊列中還),這就是爲什麼它是空(實際上應該是空的,因爲你在場上初始化它已經,不爲空)

您可以使用自定義監聽器,它傳遞到請求類和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); 

編輯澄清的要求。在顯示列表修改如下:

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); 
    } 
    } 
+0

m不清楚您的解決方案請清除此問題。我是新手,初學者很清楚@ user6547359。 –

+0

給我一個短消息我會爲你發佈更多的代碼 – user6547359

+0

@RahulGupta所有的​​代碼顯然可以做得更好,但你現在應該明白了。 – user6547359