基本适配器抛出空点警告
Posted
技术标签:
【中文标题】基本适配器抛出空点警告【英文标题】:Base Adapter throws null point warning 【发布时间】:2016-03-11 03:37:27 【问题描述】:我正在尝试使用基本适配器创建列表视图,但它显示为空白屏幕但带有警告,这是我的适配器类
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_
android:layout_
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_
android:layout_ />
</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_
android:layout_
android:background="@color/gray_dark">
<LinearLayout
android:id="@+id/llUserInfo"
android:layout_
android:layout_
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_
android:layout_>
<!-- User Picture Frame -->
<FrameLayout
android:id="@+id/frmUserImgRound"
android:layout_
android:layout_
android:layout_alignParentLeft="true"
android:layout_marginRight="8dp">
<ImageView
android:id="@+id/imgvUserPic"
android:layout_
android:layout_
android:layout_alignParentLeft="true"
android:layout_marginRight="8dp" />
<ImageView
android:layout_
android:layout_
android:src="@drawable/shap_round_frame_small_selector" />
</FrameLayout>
<!-- Username -->
<TextView
android:id="@+id/txtvUsernameSuggestion"
android:layout_
android:layout_
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_
android:layout_
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_
android:layout_>
<!-- Username -->
<TextView
android:id="@+id/txtvNameSuggestion"
android:layout_
android:layout_
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)
【问题讨论】:
SearchActivity 在哪里? @cricket_007:我已经编辑了,如果你现在能找到,请,否则我会放整个活动。 抱歉,SendPostReqAsyncTask 在哪里? 而第 153 行的任何代码行都会导致它,顺便说一句 @cricket_007;我已经在这里发布了代码,我也提到了行号 【参考方案1】:SearchActivity
中的setContentView
被注释掉了,因此没有可以通过findViewById
找到的小部件。这就是NPE
的原因。第二个错误是在您的适配器中实现getCount
。它不应该返回 0,而是返回数据集的大小。例如
@Override
public int getCount()
return suggestion == null ? 0 : suggestion.size();
【讨论】:
【参考方案2】:避免在除 onCreate 之外的任何地方加载您的 XML 布局。
此行返回 null,应移动(或者您在此活动布局中没有 list1 id)
list = (ListView) findViewById(R.id.list1);
您还应该至少在 BaseAdapter 中实现 getItem
和 getCount
或切换到已为您实现的 ArrayAdapter。
【讨论】:
感谢您的回复,我按照您的建议做了,但还是不走运。在我看来,基本适配器无法填充列表视图,但我无法找出它为什么这样做! 好吧,我相信 list 在那一点上是空的。没有看到您的 XML,我不知道还能告诉您什么。 BaseAdapter 应该可以工作,但我会使用 ArrayAdapter,真的 请看一下 XML 嗯,所以你确实有一个 list1 id。如果您注释掉所有这些 AsyncTask 内容并手动将一些项目添加到您的适配器会怎样。它会起作用吗?我认为不会,因为您还没有实现我在为您适配器的答案中提到的方法以上是关于基本适配器抛出空点警告的主要内容,如果未能解决你的问题,请参考以下文章
适配器抛出 java.lang.NullPointerException
“mfp push”在部署适配器时抛出 NullPointerException (MobileFirst Platform 7.1)
当调用 RecyclerView 适配器的“notifyDataSetChanged()”时,RecyclerView 抛出“java.lang.Throwable: addInArray”