Member 13053943 Ответов: 1

Listview и простой адаптер


Я перечисляю информацию пользователю.listview не выводит никаких выходных данных,когда я отлаживаю информацию. successful.so это означает, что listview должен выводить информацию.ничего не показывает для получения информации.проверьте мой код на наличие исправлений

Что я уже пробовал:

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


}

David Crow

Что делать activity_main.xml и event_item_list.xml похож?

1 Ответов

Рейтинг:
10

David Crow

Я только что провел небольшой тест, используя большую часть вашего кода. Это работает так что я подозреваю from и to значения, которые вы передаете SimpleAdapter конструктор не совпадает с теми, что есть в event_item_list.xml файл.

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:
<?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:
<?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>