Base Adapter会抛出零点警告

时间:2015-12-06 14:02:30

标签: android android-listview baseadapter

我正在尝试使用基本适配器创建列表视图,但它显示我的空白屏幕但有警告,这是我的适配器类

public class SuggestionListAdapter extends BaseAdapter implements View.OnClickListener {
    private Activity activity;
    private List suggestion;
    private Post post = null;
    private LayoutInflater inflater;

    /*Constructor*/
    public SuggestionListAdapter(Activity activity, List<Post> suggestion) {
        this.activity = activity;
        this.suggestion = suggestion;
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//        LayoutInflater inflater = LayoutInflater.from(activity);
    }

    /*Ends Here*/

    @Override
    public int getCount() {
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.row_of_list_suggestions, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.txtvNameSuggestion = (TextView) convertView.findViewById(R.id.txtvNameSuggestion);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.txtvNameSuggestion.setText("hello");
        return convertView;
    }

    @Override
    public void onClick(View v) {

    }


    /**
     * ****** Create a holder Class to contain inflated xml file elements ********
     */
    public static class ViewHolder {

        public TextView txtvNameSuggestion;
        public TextView txtvUsernameSuggestion;

        public ImageView frmUserImgRound;
        public ImageView imgvUserPic;
        public Button btnFollowUnFollow;
    }
}

这就是我在搜索活动中调用它的方式

public class SearchActivity extends ListActivity {
    private TextView txtvName, txtvUsername;
    private ImageView imgvUserPic;
    private Button btnFollowUnFollow;
    private ListView list;
    private List<Post> userslist = new ArrayList<Post>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_search);
        doMySearch("hello");
    }

    @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_search, 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();

        // Get the intent, verify the action and get the query
        Intent intent = getIntent();
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            doMySearch(query);
        }


        return super.onOptionsItemSelected(item);
    }

    public void doMySearch(String Query) {
        class SendPostReqAsyncTask extends AsyncTask<Void, Void, String> {

            ProgressDialog dialog;

            // Show Progress bar before downloading Music
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Shows Progress Bar Dialog and then call doInBackground method
                dialog = ProgressDialog.show(SearchActivity.this, "", "Loading. Please wait...", true);
            }

            @Override
            protected String doInBackground(Void... params) {
                HttpClient httpClient = new DefaultHttpClient();
                StringBuilder url = new StringBuilder(MyAppUtil.API_URL); // Build URL as a String
                String stUrlParams = "post/getUserHomeList/1/" + AppGlobal.currentUserId + "/25/0";
                url.append(stUrlParams);
                HttpGet httpGet = new HttpGet(url.toString());
                try {
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    InputStream inputStream = httpResponse.getEntity().getContent();
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    StringBuilder stringBuilder = new StringBuilder();
                    String bufferedStrChunk = null;
                    while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
                        stringBuilder.append(bufferedStrChunk);
                    }
                    return stringBuilder.toString();
                } catch (ClientProtocolException cpe) {
                    System.out.println("First Exception caz of HttpResponese :" + cpe);
                    cpe.printStackTrace();
                } catch (IOException ioe) {
                    System.out.println("Second Exception caz of HttpResponse :" + ioe);
                    ioe.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String result) {
//                super.onPostExecute(result);
                //close process dialog
                if (this.dialog != null) {
                    this.dialog.dismiss();
                }
                //parse json
                System.out.println(result);
                JsonParser jsonParser = new JsonParser(result);
                String message = jsonParser.getResponseMessage();
                if (jsonParser.isSuccess()) {
                    System.out.println(message);
                    JSONArray postDataArr = jsonParser.getResponseDataRow(JsonParser.API_KEY_POST_DATASET);
                    System.out.println(postDataArr.length());
                    Post post = new Post();
                    // Parsing json
                    for (int i = 0; i < postDataArr.length(); i++) {

                        try {
                            userslist.add(post);
                            list = (ListView) findViewById(R.id.list1);

                            ListAdapter adapter = new SuggestionListAdapter(SearchActivity.this, userslist);
                            list.setAdapter(adapter);// line #153  here
                            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                                @Override
                                public void onItemClick(AdapterView<?> parent, View view,
                                                        int position, long id) {
//                                    Toast.makeText(SearchActivity.this, "You Clicked at " + userslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
                                }
                            });
//                            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                                @Override
//                                public void onItemClick(AdapterView<?> parent, final View view,
//                                                        int position, long id) {
//                                    final String item = (String) parent.getItemAtPosition(position);
//                                    Log.v("SDSD", "DDFFFFFFF");
//                                }
//                            });

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    MyAppUtil.getToast(getApplicationContext(), message);
                }
            }
        }
        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        sendPostReqAsyncTask.execute();
    }


}

我的XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.almaarijsoft.kanvas.Activities.SearchActivity">

    <ListView
        android:id="@+id/list1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

<?xml version="1.0" encoding="utf-8"?><!--android:background="@drawable/selector_list_row"-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@color/gray_dark">

    <LinearLayout
        android:id="@+id/llUserInfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/black_gray"
        android:orientation="vertical"
        android:paddingBottom="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingTop="5dp"
        android:weightSum="1"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginBottom="1dp">

        <!-- ========== START ROW1  ========== -->

        <RelativeLayout
            android:id="@+id/rltRow1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <!-- User Picture Frame -->
            <FrameLayout
                android:id="@+id/frmUserImgRound"
                android:layout_width="32dp"
                android:layout_height="32dp"
                android:layout_alignParentLeft="true"
                android:layout_marginRight="8dp">

                <ImageView
                    android:id="@+id/imgvUserPic"
                    android:layout_width="32dp"
                    android:layout_height="32dp"
                    android:layout_alignParentLeft="true"
                    android:layout_marginRight="8dp" />

                <ImageView
                    android:layout_width="32dp"
                    android:layout_height="32dp"
                    android:src="@drawable/shap_round_frame_small_selector" />

            </FrameLayout>

            <!-- Username -->
            <TextView
                android:id="@+id/txtvUsernameSuggestion"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:layout_toRightOf="@+id/frmUserImgRound"
                android:text="m.rashid.se"
                android:textColor="@color/orange"
                android:textSize="@dimen/post_description"
                android:textStyle="bold" />

            <Button
                android:id="@+id/btnFollowUnFollow"
                android:layout_width="100dp"
                android:layout_height="25dp"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:background="@color/gray"
                android:text="@string/btn_follow"
                style="@style/AppTheme2"
                />
        </RelativeLayout>
        <!-- ========== END ROW1  ========== -->

        <!-- ========== START ROW2  ========== -->

        <RelativeLayout
            android:id="@+id/rltRow2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <!-- Username -->
            <TextView
                android:id="@+id/txtvNameSuggestion"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="40dp"
                android:text="M. Rashid Hussain"
                android:textColor="@color/gray"
                android:textSize="@dimen/post_created_at"
                android:textStyle="bold" />
        </RelativeLayout>
    </LinearLayout>

</RelativeLayout>

这些是我得到的警告。

12-06 18:56:42.074  24567-24567/com.almaarijsoft.kanvas W/System.err﹕ java.lang.NullPointerException
12-06 18:56:42.074  24567-24567/com.almaarijsoft.kanvas W/System.err﹕ at com.almaarijsoft.kanvas.Activities.SearchActivity$1SendPostReqAsyncTask.onPostExecute(SearchActivity.java:153)
12-06 18:56:42.074  24567-24567/com.almaarijsoft.kanvas W/System.err﹕ at com.almaarijsoft.kanvas.Activities.SearchActivity$1SendPostReqAsyncTask.onPostExecute(SearchActivity.java:89)
12-06 18:56:42.074  24567-24567/com.almaarijsoft.kanvas W/System.err﹕ at android.os.AsyncTask.finish(AsyncTask.java:632)
12-06 18:56:42.074  24567-24567/com.almaarijsoft.kanvas W/System.err﹕ at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-06 18:56:42.074  24567-24567/com.almaarijsoft.kanvas W/System.err﹕ at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
12-06 18:56:42.074  24567-24567/com.almaarijsoft.kanvas W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102)
12-06 18:56:42.074  24567-24567/com.almaarijsoft.kanvas W/System.err﹕ at android.os.Looper.loop(Looper.java:136)
12-06 18:56:42.074  24567-24567/com.almaarijsoft.kanvas W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5579)
12-06 18:56:42.074  24567-24567/com.almaarijsoft.kanvas W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
12-06 18:56:42.074  24567-24567/com.almaarijsoft.kanvas W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
12-06 18:56:42.074  24567-24567/com.almaarijsoft.kanvas W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
12-06 18:56:42.074  24567-24567/com.almaarijsoft.kanvas W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
12-06 18:56:42.074  24567-24567/com.almaarijsoft.kanvas W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
12-06 18:56:42.074  24567-24567/com.almaarijsoft.kanvas W/System.err﹕ java.lang.NullPointerException
12-06 18:56:42.074  24567-24567/com.almaarijsoft.kanvas W/System.err﹕ at com.almaarijsoft.kanvas.Activities.SearchActivity$1SendPostReqAsyncTask.onPostExecute(SearchActivity.java:153)
12-06 18:56:42.074  24567-24567/com.almaarijsoft.kanvas W/System.err﹕ at com.almaarijsoft.kanvas.Activities.SearchActivity$1SendPostReqAsyncTask.onPostExecute(SearchActivity.java:89)

2 个答案:

答案 0 :(得分:1)

setContentView中的

SearchActivity已被注释掉,因此没有可通过findViewById找到的小部件。这就是NPE的原因。第二个错误是在适配器中实现getCount。它不应该返回0而是返回数据集的大小。 E.g。

@Override
public int getCount() {
    return suggestion == null ? 0 : suggestion.size();      
}

答案 1 :(得分:0)

避免在除了onCreate之外的任何地方加载XML布局。

此行返回null并应移动(或者您在此活动布局中没有list1 id)

getItem

您还应该至少在BaseAdapter中实现getCount和{{1}},或者切换到具有为您实现的ArrayAdapter。