Listview和简单的适配器 [英] Listview and simple adapter

查看:80
本文介绍了Listview和简单的适配器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向用户列出信息。当我调试信息成功时,列表视图没有显示任何输出。这意味着列表视图应该输出信息。没有显示信息。检查我的代码进行更正< br $> b $ b

我的尝试:



I am listing information to a user.the listview isn't bringing out any output,when i debug information is successful.so meaning the listview should output the information.nothing is showing for the information.check my code for corrections

What I have tried:

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;

    private String TAG = MainActivity.class.getSimpleName();

    private ProgressDialog pDialog;
    private ListView lv;

    // URL to get contacts JSON
    private static String url = "http://..../EventMaster/api/Events/Upcomings";

    ArrayList<HashMap<String, String>> EventList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setUpToolbar();
        setUpDrawer();

        EventList = new ArrayList<>();

        lv = (ListView) findViewById(R.id.list);

        new GetEvents().execute();
    }

    private void setUpToolbar() {

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("Event Master");
    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetEvents extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }
        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {

                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray events = jsonObj.getJSONArray("Model");

                    // looping through All Contacts
                    for (int i = 0; i < events.length(); i++) {
                        JSONObject c = events.getJSONObject(i);

                        String id = c.getString("EventId");
                        String name = c.getString("EventName");
                        String description = c.getString("Description");
                        String venue = c.getString("VenueName");


                        /** Phone node is JSON Object
                        JSONObject phone = c.getJSONObject("phone");
                        String mobile = phone.getString("mobile");
                        String home = phone.getString("home");
                        String office = phone.getString("office"); */

                        // tmp hash map for single contact
                        HashMap<String, String> event = new HashMap<>();

                        // adding each child node to HashMap key => value
                        event.put("EventId", id);
                        event.put("EventName", name);
                        event.put("Description", description);
                        event.put("VenueName", venue);

                        // adding contact to contact list
                        EventList.add(event);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, EventList,
                    R.layout.event_item_list, new String[]{"name", "description",
                    "venue"}, new int[]{R.id.Eventname,
                    R.id.Eventdescription, R.id.Venue});

            lv.setAdapter(adapter);
        }

    }


    private void setUpDrawer() {

        NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.nav_drwr_fragment);
        DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerFragment.setUpDrawer(R.id.nav_drwr_fragment, drawerLayout, toolbar);
    }


}

推荐答案

我只是做了一点测试你的代码它的工作原理我怀疑的值传递到 SimpleAdapter 构造函数与 event_item_list.xml 文件中的构造函数不匹配。



MainActivity .java:

I just did a little test using most of your code. It works so I suspect the from and to values you are passing to the SimpleAdapter constructor do not match those in the event_item_list.xml file.

MainActivity.java:
public class MainActivity extends AppCompatActivity
{
    ProgressDialog pDialog;
    ArrayList<HashMap<String, String>> EventList;
    ListView lv;

    //================================================================

    @Override
    protected void onCreate( Bundle savedInstanceState )
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EventList = new ArrayList<HashMap<String, String>>();

        lv = (ListView) findViewById(android.R.id.list);

        new GetEvents().execute();
    }

    //================================================================
    //================================================================

    private class GetEvents extends AsyncTask<Void, Void, Void>
    {
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();

            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        //============================================================

        @Override
        protected Void doInBackground(Void... arg0)
        {
            try
            {
                HashMap<String, String> event = new HashMap<>();
                event.put("EventId", "ID1");
                event.put("EventName", "Name1");
                event.put("Description", "Description1");
                event.put("VenueName", "Venue1");
                EventList.add(event);

                event = new HashMap<>();
                event.put("EventId", "ID2");
                event.put("EventName", "Name2");
                event.put("Description", "Description2");
                event.put("VenueName", "Venue2");
                EventList.add(event);

                event = new HashMap<>();
                event.put("EventId", "ID3");
                event.put("EventName", "Name3");
                event.put("Description", "Description3");
                event.put("VenueName", "Venue3");
                EventList.add(event);
            }
            catch(Exception e)
            {
                Log.d("Test2", e.getMessage());
            }

            return null;
        }

        //============================================================

        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);

            if (pDialog != null)
                pDialog.dismiss();

            try
            {
                ListAdapter adapter = new SimpleAdapter(MainActivity.this,
                    EventList,
                    R.layout.event_row,
                    new String[]{"EventName", "Description", "VenueName"},
                    new int[]{R.id.Eventname, R.id.Eventdescription, R.id.Venue});

                lv.setAdapter(adapter);
            }
            catch(Exception e)
            {
                Log.d("Test2", e.getMessage());
            }
        }
    }
}



activity_main.xml:


activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.test.MainActivity">

    <ListView android:id="@android:id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>



event_row.xml:


event_row.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView android:id="@+id/Eventname"
              android:layout_weight="1"
              android:layout_width="0dp"
              android:layout_height="wrap_content" />

    <TextView android:id="@+id/Eventdescription"
              android:layout_weight="1"
              android:layout_width="0dp"
              android:layout_height="wrap_content" />

    <TextView android:id="@+id/Venue"
              android:layout_weight="1"
              android:layout_width="0dp"
              android:layout_height="wrap_content" />

</LinearLayout>


这篇关于Listview和简单的适配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆