行中的空指针异常:
listView.setAdapter(sAdapter);
public class MyEmployeFragment extends Fragment {
MyTask task;
String employer_id;
String employer_name;
String str=null;
// имена атрибутов для Map
final String ATTRIBUTE_ID = "p_id";
final String ATTRIBUTE_NAME = "p_name";
ListView listView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//myPrefs = this.getActivity().getSharedPreferences("MYsettings", Context.MODE_PRIVATE);
task = new MyTask();
task.execute();
// Creating view correspoding to the fragment
View v = inflater.inflate(R.layout.my_employe, container, false);
// Updating the action bar title
getActivity().getActionBar();
String[] userId = {"1","2","3"};
String[] userName = {"Nadezhd","Vasya", "hardcore"};
ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>(
userId.length);
Map<String, Object> m;
for (int i = 0; i < userId.length; i++) {
m = new HashMap<String, Object>();
m.put(ATTRIBUTE_ID, userId[i]);
m.put(ATTRIBUTE_NAME, userName[i]);
data.add(m);
}
// массив имен атрибутов, из которых будут читаться данные
String[] from = {ATTRIBUTE_ID, ATTRIBUTE_NAME};
// массив ID View-компонентов, в которые будут вставлять данные
int[] to = {R.id.tw_employe_id, R.id.tw_employe_name};
// создаем адаптер
SimpleAdapter sAdapter = new SimpleAdapter(getActivity(), data, R.layout.list_item_employee,
from, to);
// определяем список и присваиваем ему адаптер
listView = (ListView) getActivity().findViewById(R.id.lv_employee_list);
// ListView listView = (ListView) getView();
listView.setAdapter(sAdapter);
return v;
}
class MyTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
String s = "5ACACEC6-752B-4EFF-AA50-EEBE58A52113";
// String user_guid = myPrefs.getString("guid", "");
HttpActivity _http = new HttpActivity("192.168.10.11", "80");
_http.set_addr_protocol("/WebSite/P/spr/spr.aspx/");
_http.add_param("query", "spr_employee_get");
// _http.add_param("p_guid", user_guid.toString().trim());
_http.add_param("p_guid", s);
_http.send();
employer_name = _http.getArrayParamValue("p_name");
employer_id = _http.getArrayParamValue("p_id");
// массивы данных
//String[] userId = {employer_id};
//String[] userName = {employer_name};
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
答案 0 :(得分:3)
从它的外观来看,您的listView
为空,而不是您的适配器。将它打印到logcat,看看你得到了什么。 :)
根据Egor的回答更新:
Activity
中的内容是Fragment
。因此,当您通过getActivity().findViewById()
查找列表视图时,Android会在ListView
中搜索Activity
,但由于ListView
位于Fragment
,因此无法找到findElementbyId()
{1}}。
因此,您需要使用片段的膨胀视图并使用ListView
并让您神秘难以捉摸{{1}}:)
答案 1 :(得分:3)
正如@Little Child提到的,您的ListView
是null
,问题是以下代码行:
listView = (ListView) getActivity().findViewById(R.id.lv_employee_list);
应该是:
listView = (ListView) v.findViewById(R.id.lv_employee_list);