ListView不可见

时间:2014-12-23 19:01:02

标签: android json listview

在从后端获取json响应后,我无法动态设置ListView。

SherlockNavigationDrawer扩展了ActionBarActivity

活动 -

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;

        }

    }

}

我希望通过从后端获取json响应来动态填充我的列表视图,当用户按下按钮获取下一个或上一个帖子时。

然而,logcat中没有错误,也没有显示列表视图。但 setListView()的这一部分确实有效,因为我的linearlayout成功实现了View.GONE -

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>

获得回复后我更新了我的代码 -

onCreate()中的

- 在doGETReqst() -

之前
adapter = new MyPostListAdapter(listResults , Forum.this );
        list.setAdapter(adapter);
setListView() -

中的

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

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



        }

我的结果就是这个,现在怎样才能将其设置为scrollview,其中我嵌套了ListView ...我检查了我的所有布局 - enter image description here

最后删除android:view =&#34;去了#34; ,添加adapter.notifyDataSetChanged();并删除listview上方的scrollview我能够得到这个 -

enter image description here

谢谢guyz

2 个答案:

答案 0 :(得分:2)

应该使用List对象(例如listResults)创建适配器,并在setListView中执行以下操作:

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();
}

关键是......在列表上创建一个适配器,这样......你有一个该列表的实例。 然后更新该列表的内容(不要创建新实例),并告诉适配器该集合已更改。

尝试一下,让mw知道它是否有效。

答案 1 :(得分:1)

在您的布局中,您为列表视图设置了android:visibility="gone"。我没有看到你的代码被切换。

关于更新适配器而不是创建新实例的答案也是正确的。初始化适配器和listview并在初始化阶段设置它(使用setAdapter)。然后当你的新数据进来时(我修改了另一个答案中给出的代码,因为它令人困惑 - 什么是listResults?):

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

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