在扩展片段使用ListAdapter失败

在扩展片段使用ListAdapter失败

本文介绍了在扩展片段使用ListAdapter失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图JSON数据更新到ListView控件。它使用ListAdapter时失败。是片段剪掉允许?我坚持要使用的延伸片段。是否有任何方法?

I trying to update the JSON data into ListView. It failed when using ListAdapter. Is fragment didnt allow that ? I insist want to use the extends Fragment. Is there any method on that ?

请帮助我。谢谢你。

下面是整个code的一部分。

Here is part of the whole code.

 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

This is 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 setListAdapter ListFragment 的方法。

You need to extend ListFramgent. setListAdapter is a method of ListFragment.

没有必要使用 runOnUiThread onPostExecute 调用UI线程上。

No need to use runOnUiThread. onPostExecute is invoked on the ui thread.

编辑:

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

这篇关于在扩展片段使用ListAdapter失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 10:33