-1

当我在行中执行用于过滤的java.lang.NullPointerException代码时出现错误 ( )ListViewEditText

AllSuggestionsActivity.this.adapter.getFilter().filter(cs);

请帮助。

public class AllSuggestionsActivity extends ListActivity {

    EditText inputSearch;
    ListView lstList;

    // Progress Dialog
    private ProgressDialog pDialog;

    ArrayAdapter<String> adapter = null;

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

    ArrayList<HashMap<String, String>> suggestionsList;

    // url to get all suggestions list
    private static String url_all_suggestions = "http://10.0.2.2/JKUAT-M-SUGGESTION-BOX/get_all_suggestions.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_SUGGESTIONS = "suggestions";
    private static final String TAG_SID = "sid";
    private static final String TAG_SUBJECT = "subject";

    // suggestions JSONArray
    JSONArray suggestions = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_suggestions);

        inputSearch = (EditText) findViewById(R.id.inputSearch);
        lstList = (ListView) findViewById(android.R.id.list);


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

        // Loading suggestions in Background Thread
        new LoadAllSuggestions().execute();

        // Get listview
        ListView lv = getListView();

        /**
         * Enabling Search Filter
         * */
        inputSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text
                AllSuggestionsActivity.this.adapter.getFilter().filter(cs);   
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub                          
            }
        });


        // on seleting single suggestion
        // launching Edit Suggestion Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

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

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        EditSuggestionActivity.class);
                // sending sid to next activity
                in.putExtra(TAG_SID, sid);

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

    }

    // Response from Edit Suggestion Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted suggestion
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }

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

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AllSuggestionsActivity.this);
            pDialog.setMessage("Loading all suggestions. Please wait.......");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

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

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

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

                if (success == 1) {
                    // suggestions found
                    // Getting Array of Suggestions
                    suggestions = json.getJSONArray(TAG_SUGGESTIONS);

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

                        // Storing each json item in variable
                        String id = c.getString(TAG_SID);
                        String subject = c.getString(TAG_SUBJECT);

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

                        // adding each child node to HashMap key => value
                        map.put(TAG_SID, id);
                        map.put(TAG_SUBJECT, subject);

                        // adding HashList to ArrayList
                        suggestionsList.add(map);
                    }
                } else {
                    // no suggestions found
                    Intent i = new Intent(getApplicationContext(),
                            MainScreenActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all suggestions
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AllSuggestionsActivity.this, suggestionsList,
                            R.layout.list_item, new String[] { TAG_SID,
                                    TAG_SUBJECT }, new int[] { R.id.sid,
                                    R.id.subject });
                    // updating listview
                    setListAdapter(adapter);
                }
            });
        }
    }
}

列表视图的 xml 代码:

<?xml version="1.0" encoding="utf-8"?>

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">    

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">

    <EditText
        android:id="@+id/inputSearch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:ems="10"
        android:maxLines="1"
        android:hint="Search" >
        <requestFocus />
    </EditText>-->

        <!-- 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"/>

    </LinearLayout>


    enter code here

</ScrollView>
4

2 回答 2

0

您已将适配器初始化为 null 并且从未使用实际值重新初始化它。所以当行执行AllSuggestionsActivity.this。adapter.getFilter() .filter(cs) 粗体部分是抛出 NullPointerException 的地方。

ArrayAdapter<String> adapter = null;

此外,看起来您的适配器依赖于一些 JSON 数据,如果是这种情况并且您尝试为该数据设置过滤选项,您可以在适配器准备好数据后在 onPostExecute() 中为您的编辑文本设置文本观察器。

最后,您应该在 onPostExecute() 中去掉 runOnUiThread。onPostExecute() 默认在主 UI 线程上运行,因此不需要 runOnUiThread 存在。

于 2013-05-31T06:50:03.063 回答
0

请找到错误的解决方案:

public class AllSuggestionsActivity extends ListActivity {

SimpleAdapter adapter;

EditText inputSearch;

// Progress Dialog
private ProgressDialog pDialog;

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

ArrayList<HashMap<String, String>> suggestionsList;

// url to get all suggestions list
private static String url_all_suggestions = "http://10.0.2.2/JKUAT-M-SUGGESTION-BOX/get_all_suggestions.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_SUGGESTIONS = "suggestions";
private static final String TAG_SID = "sid";
private static final String TAG_SUBJECT = "subject";

// suggestions JSONArray
JSONArray suggestions = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_suggestions);

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

    // Loading suggestions in Background Thread
    new LoadAllSuggestions().execute();

    // Get listview
    ListView lv = getListView();

    // on seleting single suggestion
    // launching Edit Suggestion Screen
    lv.setOnItemClickListener(new OnItemClickListener() {

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

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    EditSuggestionActivity.class);
            // sending sid to next activity
            in.putExtra(TAG_SID, sid);

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

}

// Response from Edit Suggestion Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received
        // means user edited/deleted suggestion
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

}

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

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AllSuggestionsActivity.this);
        pDialog.setMessage("Loading all suggestions. Please wait.......");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

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

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

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

            if (success == 1) {
                // suggestions found
                // Getting Array of Suggestions
                suggestions = json.getJSONArray(TAG_SUGGESTIONS);

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

                    // Storing each json item in variable
                    String id = c.getString(TAG_SID);
                    String subject = c.getString(TAG_SUBJECT);

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

                    // adding each child node to HashMap key => value
                    map.put(TAG_SID, id);
                    map.put(TAG_SUBJECT, subject);

                    // adding HashList to ArrayList
                    suggestionsList.add(map);
                }
            } else {
                // no suggestions found
                Intent i = new Intent(getApplicationContext(),
                        MainScreenActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all suggestions
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */

                adapter = new SimpleAdapter(
                        AllSuggestionsActivity.this, suggestionsList,
                        R.layout.list_item, new String[] { TAG_SID,
                                TAG_SUBJECT }, new int[] { R.id.sid,
                                R.id.subject });
                // updating listview
                setListAdapter(adapter);

                /**
                 * Enabling Search Filter
                 * */
                inputSearch = (EditText) findViewById(R.id.inputSearch);

                inputSearch.addTextChangedListener(new TextWatcher() {

                    @Override
                    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                        // When user changed the Text
                        AllSuggestionsActivity.this.adapter.getFilter().filter(cs);   
                    }

                    @Override
                    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                            int arg3) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void afterTextChanged(Editable arg0) {
                        // TODO Auto-generated method stub                          
                    }
                });
            }
        });
    }
}

}

xml文件保持不变

于 2013-06-01T18:33:42.680 回答