0

I cant set my ListView dynamically after getting json response from backend.

SherlockNavigationDrawer extends ActionBarActivity

Activity -

public class Forum extends SherlockNavigationDrawer implements OnClickListener {
    AsyncTask<Void, String, Void> forumTask;
    ProgressDialog pDialog;
    TextView newPost;
    Button first, last, next, prev;
    ListView list;
    LinearLayout nopost;
    MyPostListAdapter adapter;

    public static final String MyPREFERENCES = "MyPrefs";
    SharedPreferences sharedpreferences;
    String get = "";
    JSONObject json;
    JSONParser jp;
    JSONArray id, user_id, user_name, date, file_path, description, title,
            hut_name, hut_id, ttl_likes, ttl_comment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.forum);
        setTitle("Space Huts | Forum");

        // newPost = (TextView) findViewById(R.id.tv_test);
        first = (Button) findViewById(R.id.bt_first);
        prev = (Button) findViewById(R.id.bt_prev);
        next = (Button) findViewById(R.id.bt_next);
        last = (Button) findViewById(R.id.bt_last);
        list = (ListView) findViewById(R.id.lv_posts);
        nopost = (LinearLayout) findViewById(R.id.ll_none);

        first.setOnClickListener(this);
        prev.setOnClickListener(this);
        next.setOnClickListener(this);
        last.setOnClickListener(this);

        // do a get request to server for getting latest 5 pagination posts
        doGETrqst("first");

    }

    private void doGETrqst(final String page) {
        // TODO Auto-generated method stub
        forumTask = new AsyncTask<Void, String, Void>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(Forum.this);
                pDialog.setMessage("Refreshing " + page + " page.....");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }

            @Override
            protected Void doInBackground(Void... arg0) {

                sharedpreferences = getSharedPreferences(MyPREFERENCES,
                        Context.MODE_PRIVATE);
                String usrid = sharedpreferences.getString("sesid", "");
                // Create URL string
                String URL = "http://xxx.xxx?id="
                        + usrid + "&page=" + page;
                Log.i("json url ", URL);

                try {

                    jp = new JSONParser();
                    JSONObject json = jp.getJSONFromUrl(URL);

                    id = json.getJSONArray("id");
                    user_id = json.getJSONArray("user_id");
                    user_name = json.getJSONArray("user_name");
                    date = json.getJSONArray("date");
                    file_path = json.getJSONArray("file_path");
                    description = json.getJSONArray("description");
                    title = json.getJSONArray("title");
                    hut_name = json.getJSONArray("hut_name");
                    hut_id = json.getJSONArray("hut_id");
                    ttl_likes = json.getJSONArray("ttl_likes");
                    ttl_comment = json.getJSONArray("ttl_comment");
                     Log.e("recieved" , id.getString(2));

                } catch (Exception ex) {

                    Log.e("error","error");
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {

                forumTask = null;
                pDialog.dismiss();
                setListView();



            }

        };

        forumTask.execute(null, null, null);



    }

    private void setListView() {
        // TODO Auto-generated method stub

        final List<Posts> listposts = new ArrayList<Posts>();

        // create list view arraylist for list adapter
        for (int i = 0, length = title.length(); i < length - 1; ++i) {
            Posts post = new Posts();
            try {

                post.setHutname(hut_name.getString(i));
                post.setPostname(title.getString(i));
                post.setUsername(user_name.getString(i));
                post.setDate(date.getString(i));
                listposts.add(post);
            } catch (JSONException e) {
                Toast.makeText(this, "Oooppss connectivity error",
                        Toast.LENGTH_SHORT).show();
            }

        }

        // if there are new posts to show , remove nopost linear layout
        if (listposts.size() > 0) {
            nopost.setVisibility(View.GONE);
            //set the adapter

            adapter = new MyPostListAdapter(listposts , Forum.this );
            list.setAdapter(adapter);



        }




    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
        case R.id.bt_first:
            doGETrqst("first");
            break;
        case R.id.bt_next:
            doGETrqst("next");
            break;
        case R.id.bt_prev:
            doGETrqst("prev");
            break;
        case R.id.bt_last:
            doGETrqst("last");
            break;

        }

    }

}

I want to fill my list view dynamically by getting json response from backend , when user press buttons to get next or previous posts.

However there are no errors in logcat , neither the list view is shown .But this part of setListView() do works ,as my linearlayout implements View.GONE successfully -

if (listposts.size() > 0) {
                nopost.setVisibility(View.GONE);
                //set the adapter

                adapter = new MyPostListAdapter(listposts , Forum.this );
                list.setAdapter(adapter);



            }

XML LAYOUT forum.xml -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"
    android:orientation="vertical"
    android:weightSum="0" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="20"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tv_newpost"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_gravity="center"
            android:background="@drawable/general_buttons"
            android:clickable="true"
            android:text="New Post"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@drawable/click_text_color"
            android:textSize="30dp" />

        <LinearLayout
            android:id="@+id/ll_none"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="10dp"
            android:background="@drawable/shadow"
            android:gravity="center"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/tv_none"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:fontFamily="sans-serif-thin"
                android:text="No New Post"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textColor="#000000" />

            <ImageView
                android:id="@+id/iv_none"
                android:layout_width="150dp"
                android:layout_height="match_parent"
                android:src="@drawable/none" />
        </LinearLayout>

        <ScrollView
            android:id="@+id/sv_posts"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <ListView
                android:id="@+id/lv_posts"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="5dp"
                android:visibility="gone" >

            </ListView>
        </ScrollView>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/bt_first"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:background="@drawable/general_buttons"
            android:paddingLeft="15dp"
            android:paddingRight="20dp"
            android:text="FIRST"
            android:textColor="@drawable/click_text_color" />

        <Button
            android:id="@+id/bt_prev"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/general_buttons"
            android:paddingLeft="15dp"
            android:paddingRight="20dp"
            android:text="&lt;&lt;"
            android:textColor="@drawable/click_text_color" />

        <Button
            android:id="@+id/bt_next"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/general_buttons"
            android:paddingLeft="20dp"
            android:paddingRight="15dp"
            android:text=">>"
            android:textColor="@drawable/click_text_color" >
        </Button>

        <Button
            android:id="@+id/bt_last"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:background="@drawable/general_buttons"
            android:paddingLeft="20dp"
            android:paddingRight="15dp"
            android:text="LAST"
            android:textColor="@drawable/click_text_color" />
    </LinearLayout>

</LinearLayout>

After getting responses i updated my code like this -

in onCreate() - before doGETReqst() -

adapter = new MyPostListAdapter(listResults , Forum.this );
        list.setAdapter(adapter);

in setListView() -

if (listposts.size() > 0) {
            nopost.setVisibility(View.GONE);
            //set the adapter

            listResults.clear();
            listResults.addAll(listposts);
            adapter.notifyDataSetChanged();



        }

My result is this, now how can i set this into scrollview, in which i nested ListView...i checked my all layouts - enter image description here

Finally after removing android:view="gone" , adding adapter.notifyDataSetChanged(); and removing scrollview above listview i was able to get this -

enter image description here

Thank you guyz

Divyanshu Jimmy
  • 2,542
  • 5
  • 32
  • 48

2 Answers2

2

Your adapter should be created with a List object (for example listResults) and in the setListView do something like:

if (listposts.size() > 0) {
  nopost.setVisibility(View.GONE);

  //clear old results
  listResults.clear();
  //load all results
  listResults.addAll(listposts);

  //notify the adapter about the changes
  adapter.notifyDataSetChanged();
}

The point is... create an adapter over an list so... you have ONE instance of that list. Then update the contents of that list (don't create a new instance), and tell the adapter that the collection has changed.

Try it and let mw know if it works.

Carlos Verdes
  • 3,037
  • 22
  • 20
  • its working but layout is not comming in scroll view...pls chk my editted answer. Its working even if i do adapter=null ; and then reinstantiate it :P – Divyanshu Jimmy Dec 23 '14 at 20:01
  • 1
    When you do adapter=null you are losing the pointer to adapter but the Activity has it... that's the reason why is still working. – Carlos Verdes Dec 23 '14 at 20:09
  • try putting layout_height=0 and layout_weight=1 – Carlos Verdes Dec 23 '14 at 20:16
  • 2
    Also I don't see why you have the listview inside of a scrollview. It's a bad practice anyway. See http://stackoverflow.com/questions/3495890/how-can-i-put-a-listview-into-a-scrollview-without-it-collapsing – imorsi Dec 23 '14 at 20:41
  • yup, i removed scrollview out of listview. This was wraping my listview completely :P – Divyanshu Jimmy Dec 23 '14 at 21:24
1

In your layout you have android:visibility="gone" set for your listview. I don't see that being toggled in your code.

The answer about updating the adapter instead of creating a new instance is also correct. Initialize your adapter along with your listview and set it (using setAdapter) in the initialization phase. Then when your new data comes in (I modified the code given in the other answer as it was confusing - what's listResults?):

adapter.clear();
//load all results
adapter.addAll(listposts);

//notify the adapter about the changes
adapter.notifyDataSetChanged();
imorsi
  • 346
  • 1
  • 11
  • 1
    Normally you create a list and pass that list to the adapter... listResults is that list so you work in the business layer with a Collection of data and not with Android adapters. If you find my answer ok please upvote ;) – Carlos Verdes Dec 23 '14 at 20:13