我正在尝试为我的搜索视图实现自动填充textview
功能,因为与内容提供商相比,我觉得这很容易。问题是我在nullpointerexception
获得autoComplete.setAdapter(aAdapter)
。
这是我的代码的一部分: Records.java
public class Records extends Fragment{
String Name;
GridView MyGrid;
List<String> array=new ArrayList<String>();
ArrayList<String> Location=new ArrayList<String>();
ArrayList<String> Books=new ArrayList<String>();
ArrayList<String> Entertainment=new ArrayList<String>();
SearchView searchView ;
String data;
List<String> suggest;
AutoCompleteTextView autoComplete;
ArrayAdapter<String> aAdapter;
//For Categories
public String readJSONFeed(String URL){
StringBuilder stringBuilder=new StringBuilder();
HttpClient httpClient=new DefaultHttpClient();
HttpGet httpGet=new HttpGet(URL);
try{
HttpResponse response=httpClient.execute(httpGet);
StatusLine statusLine=response.getStatusLine();
int StatusCode=statusLine.getStatusCode();
if(StatusCode==200){
HttpEntity entity=response.getEntity();
InputStream inputStream=entity.getContent();
BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line=reader.readLine())!=null){
stringBuilder.append(line);
}
inputStream.close();
}else{
Log.d("JSON", "Failed to download file");
}
}catch(Exception e){
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
public class ReadJSONFeedTask2 extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... urls) {
// TODO Auto-generated method stub
String result= readJSONFeed(urls[0]);
Log.d(" JSON: ", "> " + result);
try{
//SubCategories subcategories=new SubCategories();
JSONArray jsonArray=new JSONArray(result);
Log.d(" JSON: ", "> " + jsonArray.length());
for(int i=0;i<jsonArray.length();i++){
JSONObject json=jsonArray.getJSONObject(i);
suggest.add(json.getString("Name"));
Log.d(" AMNA: ", "> " + suggest.get(i));
}
}catch (Exception e) {
Log.d("ReadJSONFeedTask1",e.getLocalizedMessage());
}
Log.d(" ACTIVITY: ", "> " + getActivity());
return null;
}
@Override
protected void onPostExecute(String result){
//aAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,suggest);
aAdapter = new ArrayAdapter<String>(getActivity(),R.layout.item,suggest);
Log.d(" ACTIVITY: ", "> " + getActivity());
autoComplete.setThreshold(2);
autoComplete.setAdapter(aAdapter);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.gridview, container,false );
setHasOptionsMenu(true);
ActionBar actionbar = getActivity().getActionBar();
getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
actionbar.show();
suggest = new ArrayList<String>();
MyGrid=(GridView)v.findViewById(R.id.gridView);
new ReadJSONFeedTask().execute("http://10.0.2.2:63365/WebSite5/Registration/Categories.ashx");
new ReadJSONFeedTask1().execute("http://10.0.2.2:63365/WebSite5/Registration/SubCategory.ashx");
MyGrid.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
-
----------
---------
AlertDialog.Builder dialog=new AlertDialog.Builder(getActivity());
if(position==0){
final String[] loc = Location.toArray(new String[Location.size()]);
Log.d(" Inside Alert: ", "> " + loc.length + Location.size());
dialog.setTitle("Choose Location by Category");
dialog.setItems(loc, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
searchView.setQueryHint("Search For "+loc[which]);
}
});
}
else if(position==1){
final String[] books=Books.toArray(new String[Books.size()]);
dialog.setTitle("Choose Book By Category").setItems(books, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
searchView.setQueryHint("Search For "+books[which]);
new ReadJSONFeedTask2().execute("http://10.0.2.2:63365/WebSite5/Registration/Books.ashx");
}
});
}
else if(position==2){
final String[] enter=Entertainment.toArray(new String[Entertainment.size()]);
dialog.setTitle("Choose Entertainment By Category").setItems(enter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//searchView.setQueryHint("Search For "+enter[which]);
}
});
}
dialog.create();
dialog.show();
}
});
return v;
}
@Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager)getActivity(). getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.help).getActionView();
searchView.setIconified(false);
searchView.setQueryHint("Search for recomendations");
autoComplete = (AutoCompleteTextView) searchView.findViewById(R.id.autoCompleteTextView1);
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
// Do not iconify the widget; expand it by default
}
}
RES / XML / Searchable.xml
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_label"
android:hint="@string/search_hint"
>
</searchable>
RES /菜单/ main.xml中
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/help"
android:icon="@drawable/ic_action_search"
android:title="search"
android:showAsAction="always"
android:actionViewClass="android.widget.SearchView"
android:actionLayout="@layout/searchable" />
</item>
<item android:id="@+id/home" android:title="refresh"
android:icon="@drawable/ic_action_refresh"
android:showAsAction="always" />
</menu>
RES /布局/ searchable.xml
<?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">
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:imeOptions="actionSearch"
android:text="AutoCompleteTextView"
android:inputType="textAutoComplete|textAutoCorrect" >
<requestFocus />
</AutoCompleteTextView>
</LinearLayout>
logcat的:
08-02 08:05:41.354: E/AndroidRuntime(1594): FATAL EXCEPTION: main
08-02 08:05:41.354: E/AndroidRuntime(1594): java.lang.NullPointerException
08-02 08:05:41.354: E/AndroidRuntime(1594): at com.example.swipetabs.Records$ReadJSONFeedTask2.onPostExecute(Records.java:205)
08-02 08:05:41.354: E/AndroidRuntime(1594): at com.example.swipetabs.Records$ReadJSONFeedTask2.onPostExecute(Records.java:1)
08-02 08:05:41.354: E/AndroidRuntime(1594): at android.os.AsyncTask.finish(AsyncTask.java:631)
08-02 08:05:41.354: E/AndroidRuntime(1594): at android.os.AsyncTask.access$600(AsyncTask.java:177)
08-02 08:05:41.354: E/AndroidRuntime(1594): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
08-02 08:05:41.354: E/AndroidRuntime(1594): at android.os.Handler.dispatchMessage(Handler.java:99)
08-02 08:05:41.354: E/AndroidRuntime(1594): at android.os.Looper.loop(Looper.java:137)
08-02 08:05:41.354: E/AndroidRuntime(1594): at android.app.ActivityThread.main(ActivityThread.java:5039)
08-02 08:05:41.354: E/AndroidRuntime(1594): at java.lang.reflect.Method.invokeNative(Native Method)
08-02 08:05:41.354: E/AndroidRuntime(1594): at java.lang.reflect.Method.invoke(Method.java:511)
08-02 08:05:41.354: E/AndroidRuntime(1594): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-02 08:05:41.354: E/AndroidRuntime(1594): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-02 08:05:41.354: E/AndroidRuntime(1594): at dalvik.system.NativeStart.main(Native Method)
编辑Logcat:
08-02 09:08:08.641: E/AndroidRuntime(910): FATAL EXCEPTION: main
08-02 09:08:08.641: E/AndroidRuntime(910): java.lang.NullPointerException
08-02 09:08:08.641: E/AndroidRuntime(910): at com.example.swipetabs.Records.onCreateView(Records.java:232)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.support.v4.view.ViewPager.populate(ViewPager.java:1064)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.support.v4.view.ViewPager.populate(ViewPager.java:911)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1432)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.view.View.measure(View.java:15513)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4827)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.view.View.measure(View.java:15513)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.view.View.measure(View.java:15513)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4827)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
08-02 09:08:08.641: E/AndroidRuntime(910): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.view.View.measure(View.java:15513)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.view.Choreographer.doFrame(Choreographer.java:532)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.os.Handler.handleCallback(Handler.java:725)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.os.Handler.dispatchMessage(Handler.java:92)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.os.Looper.loop(Looper.java:137)
08-02 09:08:08.641: E/AndroidRuntime(910): at android.app.ActivityThread.main(ActivityThread.java:5039)
08-02 09:08:08.641: E/AndroidRuntime(910): at java.lang.reflect.Method.invokeNative(Native Method)
08-02 09:08:08.641: E/AndroidRuntime(910): at java.lang.reflect.Method.invoke(Method.java:511)
08-02 09:08:08.641: E/AndroidRuntime(910): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-02 09:08:08.641: E/AndroidRuntime(910): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-02 09:08:08.641: E/AndroidRuntime(910): at dalvik.system.NativeStart.main(Native Method)
更改onCreateView():
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.gridview, container,false );
setHasOptionsMenu(true);
ActionBar actionbar = getActivity().getActionBar();
getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
actionbar.show();
suggest = new ArrayList<String>();
autoComplete = (AutoCompleteTextView) searchView.findViewById(R.id.autoCompleteTextView1);
MyGrid=(GridView)v.findViewById(R.id.gridView);
new ReadJSONFeedTask().execute("http://10.0.2.2:63365/WebSite5/Registration/Categories.ashx");
new ReadJSONFeedTask1().execute("http://10.0.2.2:63365/WebSite5/Registration/SubCategory.ashx");
MyGrid.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
AlertDialog.Builder dialog=new AlertDialog.Builder(getActivity());
if(position==0){
final String[] loc = Location.toArray(new String[Location.size()]);
Log.d(" Inside Alert: ", "> " + loc.length + Location.size());
dialog.setTitle("Choose Location by Category");
dialog.setItems(loc, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
searchView.setQueryHint("Search For "+loc[which]);
}
});
}
else if(position==1){
final String[] books=Books.toArray(new String[Books.size()]);
dialog.setTitle("Choose Book By Category").setItems(books, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
searchView.setQueryHint("Search For "+books[which]);
new ReadJSONFeedTask2().execute("http://10.0.2.2:63365/WebSite5/Registration/Books.ashx");
}
});
}
else if(position==2){
final String[] enter=Entertainment.toArray(new String[Entertainment.size()]);
dialog.setTitle("Choose Entertainment By Category").setItems(enter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//searchView.setQueryHint("Search For "+enter[which]);
}
});
}
dialog.create();
dialog.show();
}
});
return v;
}
答案 0 :(得分:1)
您在onCreateOptionsMenu方法中初始化autoComplete变量,当菜单显示时调用
autoComplete = (AutoCompleteTextView) searchView.findViewById(R.id.autoCompleteTextView1);
你应该在之前初始化它。
尝试这样做。使类变量ArrayAdapter保持结果ReadJSONFeedTask2
private ArrayAdapter<String> YourAdapter = null;
@Override
protected void onPostExecute(String result){
YourAdapter = new ArrayAdapter<String>(getActivity(),R.layout.item,suggest);
}
并且在onCreateOptionsMenu方法中添加此适配器
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
...
autoComplete = (AutoCompleteTextView) searchView.findViewById(R.id.autoCompleteTextView1);
autoComplete.setThreshold(2);
autoComplete.setAdapter(YourAdapter);
...
}