2015-05-13 3 views
0

У меня возникли проблемы с загрузкой моего массива JSON в мой список. Я просто хочу, чтобы он загружал что-нибудь, но мне трудно получить его, даже добравшись до части getView. Любая помощь будет высоко оценена ... Я представил код двух соответствующих классов ниже.Проблема с Array Adapter для JSONArray

У меня есть следующий основной вид деятельности:

public class MainActivity extends ActionBarActivity { 

    public static PostArrayAdapter mainAdapter; 
    public static ArrayList<JSONObject> postArray; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     if (savedInstanceState == null) { 
      getSupportFragmentManager().beginTransaction() 
        .add(R.id.container, new PlaceholderFragment()) 
        .commit(); 
     } 
     // Instantiate the RequestQueue. 
     RequestQueue queue = Volley.newRequestQueue(this); 
     String url ="<<QUERY>>"; 

     Log.v("tag", "Logged this at least"); 

     JsonArrayRequest jsObjRequest = new JsonArrayRequest 
       (Request.Method.GET, url, new Response.Listener<JSONArray>() { 
        @Override 
        public void onResponse(JSONArray response) { 
         Log.i("tag", "Response: " + response.toString()); 
         try{ 
          ArrayList<JSONObject> tempArray = new ArrayList<JSONObject>(); 
          for(int i = 0; i<response.length(); i++){ 
           JSONObject post = response.getJSONObject(i); 
           tempArray.add(post); 
          } 
          postArray = tempArray; 
          Log.i("tag", "temp array: " + postArray.toString()); 
          mainAdapter.notifyDataSetChanged(); 
         } 
         catch(JSONException e){ 
          Log.e("Tag", "Error paring data "+e.toString()); 
         } 


        } 
       }, new Response.ErrorListener() { 

        @Override 
        public void onErrorResponse(VolleyError error) { 
         // TODO Auto-generated method stub 
         Log.d("tag", "Error: " + error.toString()); 
        } 
       }); 

     // Add the request to the RequestQueue. 
     queue.add(jsObjRequest); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_main, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    /** 
    * A placeholder fragment containing a simple view. 
    */ 
    public static class PlaceholderFragment extends Fragment { 

     public PlaceholderFragment() { 
     } 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
           Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
      postArray = new ArrayList<JSONObject>(); 
      mainAdapter = new PostArrayAdapter(getActivity(), postArray); 

      ListView listView = (ListView) rootView.findViewById(R.id.listview_main); 
      listView.setAdapter(mainAdapter); 

      listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
       @Override 
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
        Intent intent = new Intent(getActivity(), DetailActivity.class); 
        startActivity(intent); 
       } 
      }); 

      Log.i("tag", "Logged this at least"); 
      return rootView; 
     } 
    } 
} 

И следующий класс ArrayAdapter:

общественного класса PostArrayAdapter расширяет ArrayAdapter {

private final Context context; 
private final ArrayList<JSONObject> posts; 

public PostArrayAdapter(Context context, ArrayList<JSONObject> posts) { 
    super(context, R.layout.list_item_main, posts); 
    Log.i("tag", "Got Here 0"); 
    Log.i("tag", "Constructor response: " + posts.toString()); 
    this.context = context; 
    this.posts = posts; 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    Log.i("tag", "Got Here 1A"); 
    try { 
     Log.i("tag", "Got Here 1"); 
     JSONObject post = (JSONObject) this.posts.get(position); 
     Log.i("tag", "Got Here 2"); 
     LayoutInflater inflater = (LayoutInflater) context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     Log.i("tag", "Got Here 3"); 
     Log.i("tag", "Post: " + post.toString()); 


     if (post.get("post_type").equals("post")) { 
      Log.i("tag", "post"); 
      View rowView = inflater.inflate(R.layout.list_item_post, parent, false); 
      TextView postText = (TextView) rowView.findViewById(R.id.postText); 
      postText.setText("hello"); 
      return rowView; 
     } else if (post.get("post_type").equals("meme")) { 
      Log.i("tag", "meme"); 
      View rowView = inflater.inflate(R.layout.list_item_meme, parent, false); 
      return rowView; 
     } else if (post.get("post_type").equals("poll")) { 
      Log.i("tag", "poll"); 
      View rowView = inflater.inflate(R.layout.list_item_poll, parent, false); 
      return rowView; 
     } else if (post.get("post_type").equals("reply")) { 
      Log.i("tag", "reply"); 
      View rowView = inflater.inflate(R.layout.list_item_reply, parent, false); 
      TextView replyText = (TextView) rowView.findViewById(R.id.replyText); 
      replyText.setText("hello"); 
      return rowView; 
     } 
     return null; 
    } catch (JSONException e) { 
     e.printStackTrace(); 
     return null; 
    } 
} 

}

Я знаю, что JSONArray возвращает правильный ответ. Там, где у меня возникают проблемы, не получается, что адаптер обновляет значение после получения ответа. Есть ли у кого-нибудь возможные решения? Фактически, «Got Here 1A» никогда не называется (возможно, потому, что он не обновляется после уведомления адаптера об изменении)

+1

getView не может вернуть null – Blackbelt

+1

Попробуйте 'Просмотр rowView = inflater.inflate (R.layout.list_item_post, null, false);' – Mithun

+0

"Got Here 1A" никогда не вызывается. Я думаю, что проблема прежде, если я не ошибаюсь – John

ответ

0

Вы добавляете данные к адаптеру? Я не нашел связанного метода в вашем коде.

До mainAdapter.notifyDataSetChanged(); добавить mainAdapter.addAll(postArray);

Смежные вопросы