本人Android新手在看第一行代碼,最后一個大程序的時候出現(xiàn)了NullPointerException,希望大家能夠幫忙解決一下,謝謝
代碼如下:
ChooseAreaActivity.java
package com.example.asuka.coolweather.activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.asuka.coolweather.R;
import com.example.asuka.coolweather.db.CoolWeatherDB;
import com.example.asuka.coolweather.model.City;
import com.example.asuka.coolweather.model.County;
import com.example.asuka.coolweather.model.Province;
import com.example.asuka.coolweather.util.HttpCallbackListener;
import com.example.asuka.coolweather.util.HttpUtil;
import com.example.asuka.coolweather.util.Utility;
import java.util.ArrayList;
import java.util.List;
/**
* Created by asuka on 15-10-7.
*/
public class ChooseAreaActivity extends Activity {
public static final int LEVEL_PROVINCE = 0;
public static final int LEVEL_CITY = 1;
public static final int LEVEL_COUNTY = 2;
private ProgressDialog progressDialog;
private TextView titleText;
private ListView listView;
private ArrayAdapter<String> adapter;
private CoolWeatherDB coolWeatherDB;
private List<String> dataList = new ArrayList<String>();
/**
* 省列表
*/
private List<Province> provinceList;
/**
* 市列表
*/
private List<City> cityList;
/**
* 縣列表
*/
private List<County> countyList;
/**
* 選中的省份
*/
private Province selectedProvince;
/**
* 選中的城市
*/
private City selectedCity;
/**
* 當前選中的級別
*/
private int currentLevel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choose_area);
listView = (ListView) findViewById(R.id.list_view);
titleText = (TextView) findViewById(R.id.title_text);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
coolWeatherDB = CoolWeatherDB.getInstance(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?>arg0, View view, int index, long arg3) {
if (currentLevel == LEVEL_PROVINCE) {
selectedProvince = provinceList.get(index);
queryCities();
} else if (currentLevel == LEVEL_CITY) {
selectedCity = cityList.get(index);
queryCounties();
}
}
});
queryProvinces();
}
/**
* 查詢?nèi)珖械氖。瑑?yōu)先從數(shù)據(jù)庫查詢,如果沒有查詢到再去服務(wù)器上查詢
*/
private void queryProvinces() {
provinceList = coolWeatherDB.loadProvinces();
if (provinceList.size() > 0) {
dataList.clear();
for (Province province : provinceList) {
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText("China");
currentLevel = LEVEL_PROVINCE;
} else {
queryFromServer(null, "province");
}
}
/**
* 查詢選中省所內(nèi)所有的市,優(yōu)先從數(shù)據(jù)庫查詢,如果沒有查詢到再去服務(wù)器上查詢
*/
private void queryCities() {
cityList = coolWeatherDB.loadCities(selectedProvince.getId());
if (cityList.size() > 0) {
dataList.clear();
for (City city : cityList) {
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText(selectedProvince.getProvinceName());
currentLevel = LEVEL_CITY;
} else {
queryFromServer(selectedProvince.getProvinceCode(), "city");
}
}
/**
* 查詢選中市內(nèi)所有的縣,有先從數(shù)據(jù)庫查詢,如果沒有查詢到再去服務(wù)器上查詢
*/
private void queryCounties() {
countyList = coolWeatherDB.loadCounties(selectedCity.getId());
if (countyList.size() > 0) {
dataList.clear();
for (County county : countyList) {
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText(selectedCity.getCityName());
currentLevel = LEVEL_COUNTY;
} else {
queryFromServer(selectedCity.getCityCode(), "county");
}
}
/**
* 根據(jù)傳入的代號和類型服務(wù)器上查詢省市縣數(shù)據(jù)
*/
private void queryFromServer(final String code, final String type) {
String address;
if (!TextUtils.isEmpty(code)) {
address = "http://www.weather.com.cn/data/list3/city" + code + ".xml";
} else {
address = "http://www.weather.com.cn/data/list3/city.xml";
}
showProgressDialog();
HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
boolean result = false;
if ("province".equals(type)) {
result = Utility.handleProvinceResponse(coolWeatherDB, response);
} else if ("city".equals(type)) {
result = Utility.handleCitiesResponse(coolWeatherDB, response, selectedCity.getId());
} else if ("county".equals(type)) {
result = Utility.handleCountiesResponse(coolWeatherDB, response, selectedCity.getId());
}
if (result) {
//通過runOnUiThread方法回到主線程邏輯處理
runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
if ("province".equals(type)) {
queryProvinces();
} else if ("city".equals(type)) {
queryCities();
}
}
});
}
}
@Override
public void onError(Exception e) {
//通過runOnUiThread()方法回到主線程處理邏輯
runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(ChooseAreaActivity.this, "加載失敗", Toast.LENGTH_SHORT).show();
}
});
}
});
}
/**
* 顯示進度對話框
*/
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("正在加載..");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
/**
* 關(guān)閉進度對話框
*/
private void closeProgressDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
/**
* 捕獲Back按鍵,根據(jù)當前的級別來判斷,此時應(yīng)該返回市列表、省列表、還是直接退出
*/
@Override
public void onBackPressed() {
if (currentLevel == LEVEL_COUNTY) {
queryCities();
} else if (currentLevel == LEVEL_CITY) {
queryProvinces();
} else {
finish();
}
}
}
choose_area.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#484E61">
<TextView
android:id="@+id/title_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#fff"
android:textSize="24sp"/>
</RelativeLayout>
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
logcat提示的錯誤信息
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:401)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)
at android.widget.AbsListView.obtainView(AbsListView.java:2346)
at android.widget.ListView.makeAndAddView(ListView.java:1875)
at android.widget.ListView.fillSpecific(ListView.java:1354)
at android.widget.ListView.layoutChildren(ListView.java:1674)
at android.widget.AbsListView.onLayout(AbsListView.java:2148)
at android.view.View.layout(View.java:16630)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
at android.view.View.layout(View.java:16630)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at android.view.View.layout(View.java:16630)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
at android.view.View.layout(View.java:16630)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:2678)
at android.view.View.layout(View.java:16630)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2171)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1931)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:606)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
歡迎選擇我的課程,讓我們一起見證您的進步~~
錯誤提示信息告訴你問題出在這:
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)
你需要了解默認的getView方法的實現(xiàn):
在adapter的構(gòu)造方法中指定的布局(android.R.layout.simple_list_item_1)是Android SDK 提供的預(yù)定義布局資源。該布局擁有一個TextView根元素。
而默認的ArrayAdapter.getView(...)實現(xiàn)方法依賴于toString()方法。它首先生成布局視圖,然后找到指定位置的對象并對其調(diào)用toString()方法,最后得到字符串信息并傳遞給TextView。
《Android權(quán)威編程指南 P157,158》
所以,我猜問題應(yīng)該是你傳給Adapter的dataList包含null對象。
你應(yīng)該著重檢查更改adapter數(shù)據(jù)的代碼,比如:
dataList.add(); // 確定添加的不是null嗎?
adapter.notifyDataSetChanged();
手動還原了一下你出現(xiàn)的情況,
List<String> list = new ArrayList<String>();
String a = null;
list.add(a);
打印出的錯誤日志和你出現(xiàn)的問題是一樣的,也就是說dataList里面出現(xiàn)的null值
應(yīng)該是后面的數(shù)據(jù)庫和服務(wù)器拉取數(shù)據(jù)時有null值被加進去了,建議加一個數(shù)據(jù)檢測
判斷一下取回的數(shù)據(jù)是否為null值,如果是的話賦一個缺省值或者"".
我也出現(xiàn)一樣的問題。我的具體情況是,可以選擇省,選擇市,到縣的時候閃退。錯誤原因在于API放回的關(guān)于縣的數(shù)據(jù)中解析不對,一行代碼寫錯了。應(yīng)該是county.setCountyName(array[1]);
寫成了county.setCountyCode(array[1]);
。
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號