如何在 Android 中处理 NullPointerException?
Posted
技术标签:
【中文标题】如何在 Android 中处理 NullPointerException?【英文标题】:How to Handle NullPointerException in android? 【发布时间】:2014-02-07 11:23:39 【问题描述】:01-18 02:08:05.271: E/androidRuntime(24688): FATAL EXCEPTION: main
01-18 02:08:05.271: E/AndroidRuntime(24688): java.lang.NullPointerException
01-18 02:08:05.271: E/AndroidRuntime(24688): at com.example.tava.EchangingMessage$LoadData.onPostExecute(EchangingMessage.java:178)
01-18 02:08:05.271: E/AndroidRuntime(24688): at com.example.tava.EchangingMessage$LoadData.onPostExecute(EchangingMessage.java:1)
01-18 02:08:05.271: E/AndroidRuntime(24688): at android.os.AsyncTask.finish(AsyncTask.java:602)
01-18 02:08:05.271: E/AndroidRuntime(24688): at android.os.AsyncTask.access$600(AsyncTask.java:156)
01-18 02:08:05.271: E/AndroidRuntime(24688): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
01-18 02:08:05.271: E/AndroidRuntime(24688): at android.os.Handler.dispatchMessage(Handler.java:99)
01-18 02:08:05.271: E/AndroidRuntime(24688): at android.os.Looper.loop(Looper.java:154)
01-18 02:08:05.271: E/AndroidRuntime(24688): at android.app.ActivityThread.main(ActivityThread.java:4945)
01-18 02:08:05.271: E/AndroidRuntime(24688): at java.lang.reflect.Method.invokeNative(Native Method)
01-18 02:08:05.271: E/AndroidRuntime(24688): at java.lang.reflect.Method.invoke(Method.java:511)
01-18 02:08:05.271: E/AndroidRuntime(24688): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-18 02:08:05.271: E/AndroidRuntime(24688): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-18 02:08:05.271: E/AndroidRuntime(24688): at dalvik.system.NativeStart.main(Native Method)
这是我的代码活动代码:
public class EchangingMessage extends Activity implements OnClickListener
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> DaftarRS;
EditText textToSend;
ArrayList<HashMap<String, String>> arraylist;
private static String url_daftar_rs = "http://192.168.137.1/www/Android_Login_Secure/detailMessage.php";
private static String url_daftar_rs1 = "http://192.168.137.1/www/Android_Login_Secure/myFriends.php";
public static final String TAG_SUCCESS = "success";
public static final String TAG_DAFTAR_RS = "daftar_rs";
public static final String TAG_ID_RS = "id_rs";
public static final String TAG_NAMA_RS = "username";
public static final String TAG_LINK_IMAGE_RS = "image";
public static final String TAG_MESSAGE_RS = "messageText";
public static final String TAG_TIME_RS = "sendAt";
public static final String TAG_SEEN_RS = "readStatus";
JSONArray daftar_rs = null;
ListAdapterUserOnile adapterFirends;
ImageView showOnline;
@Override
protected void onCreate(Bundle savedInstanceState)
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.exchange_message);
arraylist = new ArrayList<HashMap<String, String>>();
@Override
public void onClick(View v)
// TODO Auto-generated method stub
switch (v.getId())
case R.id.userOnline:
userOnlineWindow();
break;
private void userOnlineWindow()
// TODO Auto-generated method stub
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(popupView,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button btnDismiss = (Button) popupView.findViewById(R.id.dismiss);
btnDismiss.setOnClickListener(new Button.OnClickListener()
@Override
public void onClick(View v)
// TODO Auto-generated method stub
popupWindow.dismiss();
);
popupWindow.showAsDropDown(showOnline, -190, -90);
new LoadData().execute();
popupWindow.setFocusable(true);
popupWindow.update();
class LoadData extends AsyncTask<String, String, String>
@Override
protected void onPreExecute()
super.onPreExecute();
pDialog = new ProgressDialog(EchangingMessage.this);
pDialog.setMessage("Loading Information...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
@Override
protected String doInBackground(String... arg0)
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("me", "52"));
JSONObject json = jParser.makeHttpRequest(url_daftar_rs1, "POST",
params1);
try
int success = json.getInt(TAG_SUCCESS);
Log.i("success :", "" + success);
if (success == 1)
daftar_rs = json.getJSONArray(TAG_DAFTAR_RS);
for (int i = 0; i < daftar_rs.length(); i++)
JSONObject c = daftar_rs.getJSONObject(i);
String id_rs = c.getString(TAG_ID_RS);
String nama_rs = c.getString(TAG_NAMA_RS);
String link_image_rs = c.getString(TAG_LINK_IMAGE_RS);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID_RS, id_rs);
map.put(TAG_NAMA_RS, nama_rs);
map.put(TAG_LINK_IMAGE_RS,
"http://192.168.137.1/www/Android_Login_Secure/Images/upload/big/"
+ link_image_rs);
arraylist.add(map);
else
catch (Exception e)
Log.e("Error", "COnnection:" + e.toString());
return null;
protected void onPostExecute(String file_url)
pDialog.dismiss();
ListView listUserOnline = (ListView) findViewById(R.id.listOfUserOnline);
adapterFirends = new ListAdapterUserOnile(EchangingMessage.this,
arraylist);
listUserOnline.setAdapter(adapterFirends);
我创建了这个应用程序,但是当我单击顶部按钮时出现此错误 这是弹出窗口,这是连接php
请问这个错误怎么处理?
这是我的 EchangeMesssage.xml 文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:background="@drawable/backgroudnformain"
android:orientation="vertical" >
<LinearLayout
android:layout_
android:layout_
android:background="#99cc00"
android:gravity="center"
>
<ImageView
android:id="@+id/userOnline"
android:layout_
android:layout_
android:layout_gravity="center"
android:src="@drawable/userimages" />
</LinearLayout>
<LinearLayout
android:id="@+id/bottom_write_bar"
android:layout_
android:layout_
android:layout_alignParentBottom="true"
android:background="@drawable/message_bar" >
<EditText
android:id="@+id/messageToSend"
android:layout_
android:layout_
android:layout_margin="5sp"
android:layout_weight="1"
android:background="@drawable/message_field"
android:hint="Write here"
android:padding="5sp"
android:textColor="@color/textFieldColor" />
<Button
android:id="@+id/sendButton"
android:layout_
android:layout_
android:layout_margin="5sp"
android:background="@drawable/send_button"
android:onClick="sendMessage"
android:paddingBottom="5sp"
android:paddingLeft="15sp"
android:paddingRight="15sp"
android:paddingTop="5sp"
android:text="Send"
android:textColor="#FFF" />
</LinearLayout>
<ListView
android:id="@+id/listSend"
android:layout_
android:layout_
android:layout_marginTop="40dp"
android:layout_above="@id/bottom_write_bar"
android:layout_alignParentTop="true"
android:cacheColorHint="#00000000"
android:divider="#00000000"
android:stackFromBottom="true"
android:clickable="false"
android:scrollbars="none"
android:transcriptMode="alwaysScroll"
android:listSelector="#00000000" >
</ListView>
<TextView
android:id="@+id/you_id"
android:layout_
android:layout_
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:visibility="gone" />
<TextView
android:id="@+id/me_id"
android:layout_
android:layout_
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:visibility="gone" />
</RelativeLayout>
这是我的 popup.xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:background="@drawable/windowwww"
android:orientation="vertical" >
<Button
android:id="@+id/dismiss"
android:layout_
android:layout_
android:layout_marginLeft="240dp"
android:layout_marginTop="60dp"
android:text="EXIT" />
<ListView
android:id="@+id/listOfUserOnline"
android:layout_
android:layout_
android:layout_marginTop="30dp" >
</ListView>
</LinearLayout>
这是我的 ListAdapter 类:
public class ListAdapterUserOnile extends BaseAdapter
public String POST_TEXT;
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public final static String you_id=null;
int count = 0;
public ListAdapterUserOnile(Activity a, ArrayList<HashMap<String, String>> d)
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
public int getCount()
// TODO Auto-generated method stub
return data.size();
public Object getItem(int position)
return position;
public long getItemId(int position)
return position;
public View getView(int position, View convertView, ViewGroup parent)
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.item_list_friends, null);
TextView name_rs = (TextView) vi.findViewById(R.id.myFriendUsername);
ImageView thumb_image = (ImageView) vi
.findViewById(R.id.myFriendImage);
TextView status = (TextView) vi.findViewById(R.id.status);
ImageView on=(ImageView) vi.findViewById(R.id.online);
ImageView off=(ImageView) vi.findViewById(R.id.offline);
HashMap<String, String> daftar_rs = new HashMap<String, String>();
daftar_rs = data.get(position);
final int getPosition = position;
name_rs.setText(daftar_rs.get(EchangingMessage.TAG_NAMA_RS));
Log.e("IMage", daftar_rs.get(EchangingMessage.TAG_LINK_IMAGE_RS));
imageLoader.DisplayImage(daftar_rs.get(EchangingMessage.TAG_LINK_IMAGE_RS),
thumb_image);
if (status.getText().toString().equals("1"))
off.setVisibility(View.INVISIBLE);
on.setVisibility(View.VISIBLE);
status.setVisibility(View.INVISIBLE);
else
off.setVisibility(View.VISIBLE);
on.setVisibility(View.INVISIBLE);
status.setVisibility(View.INVISIBLE);
vi.setOnClickListener(new OnClickListener()
@Override
public void onClick(View arg0)
// TODO Auto-generated method stub
Toast.makeText(
activity,
" You click"
+ data.get(getPosition)
.get(MyFriends.TAG_ID_RS).toString(),
Toast.LENGTH_SHORT).show();
Intent i=new Intent(activity,EchangingMessage.class);
i.putExtra(you_id, data.get(getPosition)
.get(MyFriends.TAG_ID_RS).toString());
activity.startActivity(i);
);
return vi;
【问题讨论】:
第178行对应哪一行? 您确定变量 listUserOnline 不为空吗?如果您的 id 在 R.java 中找不到给定的 id,findViewByID 可以返回 null。 是的,你是对的,我删除了一些代码现在看看这个 ***.com/q/640884/2874005 用于启用行号 listUserOnline.setAdapter(adapterFirends);我认为:( 【参考方案1】:当您使用setContentView(R.layout.exchange_message)
时,布局R.layout.exchange_message
将膨胀并与您的活动相关联。如果要从该布局中检索视图,只需调用 findViewById(R.id.MyId);
。
但是如果你的 View 不在布局内,你将会有一个 NPException。
要从另一个布局中检索视图,您必须先对其进行膨胀,然后调用myView.findViewById(R.id.MyId)
。
例如,根据您的情况,如果您想使用popup.xml
布局文件中的ListView
:
View popupView = layoutInflater.inflate(R.layout.popup, null);
ListView list = popupView.findViewById(R.id.listOfUserOnline);
【讨论】:
【参考方案2】:你需要学习阅读日志来解决你的错误,比如 NPE。 java.lang.NullPointerException at com.example.tava.EchangMessage$LoadData.onPostExecute*(EchangMessage.java:178)*
您的错误很可能出现在这一行。 要在 Eclipse 中显示行号,请右键单击左侧边缘并选择“显示行号”此外,键盘命令 Ctrl+L 将让您跳转到特定行.
改为在您的 popupWindow 上调用 findViewById。将变量提取到类级别或将其传递给 AsyncTask,以便对其进行引用。
popupWindow.findViewById();
【讨论】:
listUserOnline.setAdapter(adapterFirends);这是我的错误点 你给了他/她一个很好的建议,但你没有帮助他/她太多。他/她给出了行号和代码,该 NPE 的原因应该是什么?回答这个问题可能会帮助他/她更好... 那你的 findViewById(R.id.listOfUserOnline) 失败了,你确定id是正确的吗?是有这种观点的活动吗?如果视图属于另一个组件,则必须调用 .findViewById 来代替。例如,如果它属于一个对话框,您需要在对话框上调用它,从而使其成为 dialog.findViewById()以上是关于如何在 Android 中处理 NullPointerException?的主要内容,如果未能解决你的问题,请参考以下文章
尝试打开 Android XML 文件时如何修复 Eclipse 中出现的空指针异常?
doFilter() 重写方法 httpRequest.getUserPrincipal() 总是返回 NullPoint 异常
An internal error occurred during: "Map/Reducelocation status updater".java.lang.NullPoint
解决报错Failed to start bean ‘documentationPluginsBootstrapper‘; nested exception is java.lang.NullPoint