ListView从数据库中获取数据并以片段

时间:2016-01-11 06:31:49

标签: android json android-fragments android-listview

patientlist_listview.xml

<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipe_refresh_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
   >

<ListView
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:dividerHeight="0dp"
    android:divider="@null"
    android:listSelector="@drawable/list_row_selector"
    />

</android.support.v4.widget.SwipeRefreshLayout>

activity_icon_text_tabs.xml

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabGravity="fill"  />
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

OneFragment.java

package info.androidhive.materialtabs.fragments;

public class OneFragment extends Fragment {


private SwipeRefreshLayout swipeRefreshLayout;
public OneFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.patientlist_listview, container, false);

    return view;

}

}

IconTextTabactivity.java

public class IconTextTabsActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
        R.drawable.ic_tab_favourite,
        R.drawable.ic_tab_call,
        R.drawable.ic_tab_contacts
};


private static final String TAG = PatientList.class.getSimpleName();
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;

// Movies json url
private static final String url = "http://192.168.0.102/test/apps.php";
private ProgressDialog pDialog;
private List<Patient> patientList = new ArrayList<Patient>();
private ListView listView;
private CustomListAdapter listadapter;

private SwipeRefreshLayout swipeRefreshLayout;

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

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();
}

private void setupTabIcons() {
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    tabLayout.getTabAt(1).setIcon(tabIcons[1]);
    tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    setContentView(R.layout.patientlist_listview);

    listView = (ListView) findViewById(R.id.list);
    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);

    listadapter = new CustomListAdapter(this, patientList);
    listView.setAdapter(listadapter);

    pDialog = new ProgressDialog(this);
    // Showing progress dialog before making http request
    pDialog.setMessage("Loading...");
    pDialog.show();

    // changing action bar color
   // getActionBar().setBackgroundDrawable(
    //        new ColorDrawable(Color.parseColor("#00BBD3")));

    swipeRefreshLayout.setOnRefreshListener(this);

    /**
     * Showing Swipe Refresh animation on activity create
     * As animation won't start on onCreate, post runnable is used
     */
    swipeRefreshLayout.post(new Runnable() {
                                @Override
                                public void run() {
                                    swipeRefreshLayout.setRefreshing(true);
                                    fetchPatients();
                                }
                            }
    );

    listView.setAdapter(listadapter);

    // Click event for single list row
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(IconTextTabsActivity.this, "row " + position + " was pressed", Toast.LENGTH_LONG).show();
            switch (position) {
                case 0:
                    TextView c =(TextView)view.findViewById(R.id.title);
                    String item = c.getText().toString();
                    Log.d("id", item);
                    break;

                case 1:
                    break;
            }

        }

    });


    adapter.addFrag(new OneFragment(), "ONE");
    adapter.addFrag(new TwoFragment(), "TWO");
    adapter.addFrag(new ThreeFragment(), "THREE");
    viewPager.setAdapter(adapter);
}

/**
 * This method is called when swipe refresh is pulled down
 */
@Override
public void onRefresh() {
    fetchPatients();
}
/**
 * Fetching movies json by making http call
 */
private void fetchPatients() {

    // showing refresh animation before making http call
    swipeRefreshLayout.setRefreshing(true);

    // appending offset to url
    //String url = URL_TOP_250 + offSet;

    // Creating volley request obj
    JsonArrayRequest movieReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hidePDialog();
                    Log.d("id", "hi") ;
                    // Parsing json
                    // reset the list
                    patientList.clear();
                    listadapter.notifyDataSetChanged();

                    for (int i = 0; i < response.length();i++) {
                        try {
                            Log.d("id","hi1") ;
                            Log.d("i","i:"+i);

                            Patient patient = new Patient();

                            Log.d("length", "length:" + response.length());
                            JSONObject objid= response.getJSONObject(i);
                            //get id
                            patient.setTitle(objid.getString("id"));


                            JSONObject objimage= response.getJSONObject(++i);
                            patient.setThumbnailUrl(objimage.getString("image"));
                            //Log.d("i","i:"+i);



                            movie.setYear(obj.getInt("releaseYear"));

                            // Genre is json array
                            JSONArray genreArry = obj.getJSONArray("genre");
                            ArrayList<String> genre = new ArrayList<String>();
                            for (int j = 0; j < genreArry.length(); j++) {
                                genre.add((String) genreArry.get(j));
                            }
                            movie.setGenre(genre);
                            */

                            // adding movie to movies array
                            if(i%2==1)
                                patientList.add(patient);


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    listadapter.notifyDataSetChanged();

                    // stopping swipe refresh
                    swipeRefreshLayout.setRefreshing(false);

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            hidePDialog();
            Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();

            // stopping swipe refresh
            swipeRefreshLayout.setRefreshing(false);

        }
    });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(movieReq);
}

@Override
public void onDestroy() {
    super.onDestroy();
    hidePDialog();
}

private void hidePDialog() {
    if (pDialog != null) {
        pDialog.dismiss();
        pDialog = null;
    }
}


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

public PatientList() {
    // Required empty public constructor

}


//public View onCreateView(LayoutInflater inflater, ViewGroup container,
 //                        Bundle savedInstanceState) {
 //   // Inflate the layout for this fragment
  //  return inflater.inflate(R.layout.patientlist_listview, container, false);
//}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

}

我希望从数据库中获取数据并在显示页面到选项卡之前设置为listview。然而,它崩溃了。列表视图和选项卡项目可以正常运行,但我无法合并它们,我得到以下错误。请给我一些帮助。谢谢

01-11 01:22:04.467 10373-10373/? I/art: Late-enabling -Xcheck:jni
01-11 01:22:04.917 10373-10410/info.androidhive.materialtabs D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
01-11 01:22:04.934 10373-10373/info.androidhive.materialtabs D/Atlas: Validating map...
01-11 01:22:05.004 10373-10410/info.androidhive.materialtabs D/libEGL: loaded /system/lib/egl/libEGL_emulation.so
01-11 01:22:05.005 10373-10410/info.androidhive.materialtabs D/libEGL: loaded /system/lib/egl/libGLESv1_CM_emulation.so
01-11 01:22:05.024 10373-10410/info.androidhive.materialtabs D/libEGL: loaded /system/lib/egl/libGLESv2_emulation.so
01-11 01:22:05.071 10373-10410/info.androidhive.materialtabs I/OpenGLRenderer: Initialized EGL, version 1.4
01-11 01:22:05.090 10373-10410/info.androidhive.materialtabs D/OpenGLRenderer: Enabling debug mode 0
01-11 01:22:05.109 10373-10410/info.androidhive.materialtabs W/EGL_emulation: eglSurfaceAttrib not implemented
01-11 01:22:05.109 10373-10410/info.androidhive.materialtabs W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xeed0d7c0, error=EGL_SUCCESS
01-11 01:22:17.679 10373-10373/info.androidhive.materialtabs D/AndroidRuntime: Shutting down VM
01-11 01:22:17.680 10373-10373/info.androidhive.materialtabs E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: info.androidhive.materialtabs, PID: 10373
                                                                           java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.materialtabs/info.androidhive.materialtabs.activity.IconTextTabsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.TabLayout.setupWithViewPager(android.support.v4.view.ViewPager)' on a null object reference
                                                                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
                                                                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                               at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                               at android.os.Looper.loop(Looper.java:135)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at java.lang.reflect.Method.invoke(Method.java:372)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                            Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.TabLayout.setupWithViewPager(android.support.v4.view.ViewPager)' on a null object reference
                                                                               at info.androidhive.materialtabs.activity.IconTextTabsActivity.onCreate(IconTextTabsActivity.java:80)
                                                                               at android.app.Activity.performCreate(Activity.java:5990)
                                                                               at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
                                                                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                                                                               at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                               at android.os.Looper.loop(Looper.java:135) 
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5254) 
                                                                               at java.lang.reflect.Method.invoke(Native Method) 
                                                                               at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
01-11 01:27:17.701 10373-10373/? I/Process: Sending signal. PID: 10373 SIG: 9

0 个答案:

没有答案