Fragment中的ListView未显示在MainActivity中

时间:2015-06-26 02:36:04

标签: android listview android-fragments

我从这个API获取数据并将其解析为片段中的列表视图。但是,我似乎无法将其显示在主要活动上。有人能指出我正确的方向吗?

EDIT1:可以找到布局文件here

主要活动:

    package com.example.szen95.meddict;

    import android.os.Bundle;
    import android.support.v7.app.ActionBarActivity;
    import android.view.Menu;
    import android.view.MenuItem;

    public class MainActivity extends ActionBarActivity {

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

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }

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

SearchFragment:

    package com.example.szen95.meddict;

import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;


public class SearchFragment extends ListFragment {

//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_search_fragment);
//        if (savedInstanceState == null) {
//            getSupportFragmentManager().beginTransaction()
//                    .add(R.id.container, new SearchFragment())
//                    .commit();
//        }
//    }


    private ProgressDialog pDialog;

    // URL to get contacts JSON
    private static String url = "http://dailymed.nlm.nih.gov/dailymed/services/v2/drugclasses.json";

    // JSON Node names
    private static final String TAG_DATA = "data";
    private static final String TAG_CODE = "code";
    private static final String TAG_CODING_SYSTEM = "codingsystem";
    private static final String TAG_TYPE = "type";
    private static final String TAG_NAME = "name";


    // contacts JSONArray
    JSONArray data = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();

    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState) {

        // Retrieving the currently selected item number
        int position = getArguments().getInt("position");

        // Creating view correspoding to the fragment
        View v = inflater.inflate(R.layout.activity_search_fragment, container, false);

        // Updating the action bar title
//        getActivity().getActionBar().setTitle(options[position]);

        // Calling async task to get json
        new GetData().execute();

        return v;
    }

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

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

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

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

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    data = jsonObj.getJSONArray(TAG_DATA);

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

                        String code = c.getString(TAG_CODE);
                        String codingsystem = c.getString(TAG_CODING_SYSTEM);
                        String type = c.getString(TAG_TYPE);
                        String name = c.getString(TAG_NAME);
;

                        // tmp hashmap for single contact
                        HashMap<String, String> data = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        data.put(TAG_CODE, code);
                        data.put(TAG_CODING_SYSTEM, codingsystem);
                        data.put(TAG_TYPE, type);
                        data.put(TAG_NAME, name);

                        // adding contact to contact list
                        dataList.add(data);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            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
             * */
            SimpleAdapter adapter = new SimpleAdapter(getActivity(), dataList,
                    R.layout.list_item, new String[] { TAG_NAME, TAG_CODE}, new int[] { R.id.name,
                    R.id.code});

            setListAdapter(adapter);
        }

    }

}

3 个答案:

答案 0 :(得分:1)

取消对searchFragment中的onCreate方法的评论,因为您的片段没有给任何布局充气

答案 1 :(得分:1)

可以使用FragmentManager将片段放入布局中。 使用以下内容添加MainActivity的替换onCreate

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fts = fragmentManager.beginTransaction();
Fragment fragment = new SearchFragment();
String fragmentTag = "SearchFragment";
fts.add(R.id.main_container, fragment, fragmentTag);
fts.commit();
    }

将您的layout_activity_main.xml更改为以下内容。你不需要这里的列表视图。只需确保您有一个布局容器main_container即可放置片段。

<?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:orientation="vertical">

    <FrameLayout android:id="@+id/main_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
         >
    </FrameLayout>

    <!-- Main ListView
     Always give id value as list(@android:id/list)

    <ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:divider="@null"/>
    -->
</LinearLayout>

答案 2 :(得分:1)

我认为你的问题是由Jason解析引起的。

private static final String TAG_CODING_SYSTEM = "codingSystem";

Jason密钥区分大小写。但是请下次尝试自己调试,这是成为更好的编码器的唯一方法。干杯!