簡體   English   中英

在擴展片段中使用 ListAdapter 失敗

[英]Failed using ListAdapter in extends Fragment

我試圖將 JSON 數據更新到 ListView。 使用 ListAdapter 時失敗。 片段不允許嗎? 我堅持要使用擴展片段。 有什么方法嗎?

請幫我。 謝謝。

這是整個代碼的一部分。

 public class ScheduleFragment extends Fragment {


    public ProgressDialog pDialog;

    private ListView myListView;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> subjectList;     

    // url to get all subjects list
    private static String url_all_subjects = "http://192.168.1.12/android_project/get_subjects.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_STUDENT = "students";
    private static final String TAG_MATRIX_ID = "matrix";
    private static final String TAG_NAME = "name";

    // subject JSONArray
    JSONArray subject = null;


public ScheduleFragment(){}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View rootView = inflater.inflate(R.layout.fragment_schedule, container, false);



 //------------------------------------CREATING A LISTVIEW-----------------------

    // Loading subject in Background Thread
    new LoadAllSubject().execute();

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

    myListView = (ListView) rootView.findViewById(R.id.textViewMatrix);

    // on selecting single subject
    myListView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String matrix_id = ((TextView) view.findViewById(R.id.textViewMatrix)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getActivity().getApplicationContext(),
                    SingleSubject.class);

            // sending matrix id to next activity
            in.putExtra(TAG_MATRIX_ID, matrix_id);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        }
    });

    return rootView;
}

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllSubject extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = ProgressDialog.show(ScheduleFragment.this.getActivity(), "Progress", "Loading subjects. Please wait...", false);
        //pDialog.setMessage("Loading subjects. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_subjects, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Subject
                subject = json.getJSONArray(TAG_STUDENT);

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

                    // Storing each json item in variable
                    String id = c.getString(TAG_MATRIX_ID);
                    String name = c.getString(TAG_NAME);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_MATRIX_ID, id);
                    map.put(TAG_NAME, name);

                    // adding HashList to ArrayList
                    subjectList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity

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

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                         getActivity(), subjectList,
                        R.layout.all_subject, new String[] { TAG_MATRIX_ID,
                                TAG_NAME},
                        new int[] { R.id.matrix_id, R.id.name });
                // updating listview
                myListView.setListAdapter(adapter);
            }


    }

}

 }

這是 all_subject.xml

 <!-- Subject matrix_id - will be HIDDEN - used to pass to other activity -->
<TextView
    android:id="@+id/matrix_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:visibility="gone" />


<!-- Name Label -->
<TextView
    android:id="@+id/name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingTop="6dip"
    android:paddingLeft="6dip"
    android:textSize="17dip"
    android:textStyle="bold" />

您需要擴展ListFramgent setListAdapterListFragment一個方法。

無需使用runOnUiThread onPostExecute在 ui 線程上調用。

編輯:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View rootView = inflater.inflate(R.layout.fragment_schedule, container, false);
    subjectList = new ArrayList<HashMap<String, String>>();
    myListView = (ListView) rootView.findViewById(R.id.textViewMatrix);
     new LoadAllSubject().execute();
    myListView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            String matrix_id = ((TextView) view.findViewById(R.id.textViewMatrix)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getActivity().getApplicationContext(),
                    SingleSubject.class);

            // sending matrix id to next activity
            in.putExtra(TAG_MATRIX_ID, matrix_id);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        }
    });

    return rootView;
}

然后

  protected void onPostExecute(String file_url) {
   super.onPostExecute(file_url); 
    pDialog.dismiss();
    ListAdapter adapter = new SimpleAdapter(
                       getActivity(), subjectList,
                    R.layout.all_subject, new String[] { TAG_MATRIX_ID,
                            TAG_NAME},
                    new int[] { R.id.matrix_id, R.id.name });
    myListView.setAdapter(adapter);
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM