Android 从dialogfragment发布新数据后更新Listview
在我从Android 从dialogfragment发布新数据后更新Listview,android,listview,android-listview,android-asynctask,android-dialogfragment,Android,Listview,Android Listview,Android Asynctask,Android Dialogfragment,在我从DialogFragment提交新数据后,我正试图直接更新我的列表视图。 但是当我调用notifyDataSetChanged()时,它会给我一个NullPointerException,我的应用程序就关闭了 这就是我想要的场景 这是我的代码 我用于从服务器获取数据的此活动 public class LayoutActivity extends Fragment { private ListView listview; private ListItemAdapter t
DialogFragment
提交新数据后,我正试图直接更新我的列表视图。
但是当我调用notifyDataSetChanged()
时,它会给我一个NullPointerException
,我的应用程序就关闭了
这就是我想要的场景
这是我的代码
我用于从服务器获取数据的此活动
public class LayoutActivity extends Fragment {
private ListView listview;
private ListItemAdapter theAdapter;
String URL = "http://localhost/api/question/get_newest_except/0/0/15";
ProgressDialog pDialog;
NodeList nodelist;
public LayoutActivity() {
super();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.layout_main, container,false);
DownloadXML a = new DownloadXML(this);
a.execute(URL);
listview = (ListView) rootview.findViewById(R.id.list01);
return rootview;
}
public class DownloadXML extends AsyncTask<String, Void, Void>{
private LayoutActivity aku;
ArrayList<ListItemObject> data;
public DownloadXML(LayoutActivity aku) {
super();
this.aku = aku;
}
@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.show();
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
data = new ArrayList<ListItemObject>();
ListItemObject itemData;
try{
for (int temp = 0; temp < nodelist.getLength(); temp++) {
Node nNode = nodelist.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
itemData = new ListItemObject();
itemData.setId(getNode("pb__question__id",eElement));
itemData.setOwner(getNode("pb__question__consumer__id",eElement));
if(!getNode("pb__question__consumer__id",eElement).equalsIgnoreCase("0")){
itemData.setName(getNode("pb__question__consumer__name",eElement));
itemData.setJob(getNode("pb__question__consumer__occupation", eElement));
itemData.setProfilePic(getNode("pb__question__consumer__pp",eElement));
}
itemData.setStatus(getNode("pb__question__title",eElement));
itemData.setExtras(getNode("pb__question__topic__name", eElement));
if(!getNode("att__pict",eElement).isEmpty()){
itemData.setImage(getNode("att__pict", eElement));
}
if(getNode("pb__question__type", eElement).equalsIgnoreCase("1")){
itemData.setOpini(getNode("pb__question__total__opini", eElement));
}else if(getNode("pb__question__type", eElement).equalsIgnoreCase("2") || getNode("pb__question__type", eElement).equalsIgnoreCase("3")){
itemData.setOpini(getNode("pb__question__total__polling", eElement));
}else if(getNode("pb__question__type", eElement).equalsIgnoreCase("4")){
itemData.setOpini(getNode("pb__question__total__rating", eElement));
}
itemData.setTipe(getNode("pb__question__type", eElement));
itemData.setIkuti(getNode("pb__question__total__follow", eElement));
itemData.setSebarkan(getNode("pb__question__total__share", eElement));
data.add(itemData);
}
}
theAdapter = new ListItemAdapter(aku.getActivity(),data);
listview.setAdapter(theAdapter);
}catch(Exception e){
Toast.makeText(getActivity(), "Koneksi dengan server gagal", Toast.LENGTH_SHORT).show();
}
pDialog.dismiss();
}
@Override
protected Void doInBackground(String... Url) {
// TODO Auto-generated method stub
try {
URL url = new URL(Url[0]);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
nodelist = doc.getElementsByTagName("pb__question");
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
}
private static String getNode(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
String result = "";
if(nValue!=null){
result = nValue.getNodeValue();
}
return result;
}
}
这是对话框片段
public class DialogAddOpini extends DialogFragment{
ListItemAdapter theAdapter;
String question_id,owner_id;
EditText question_field;
ProgressDialog pDialog;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.addopini, null);
Bundle mArgs = getArguments();
question_id = mArgs.getString("question");
owner_id = mArgs.getString("owner");
builder.setTitle("Tambahkan Opini");
builder.setView(dialogView)
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
question_field = (EditText) dialogView.findViewById(R.id.content);
SendComment send = new SendComment();
send.execute(question_field.getText().toString());
}
});
Dialog dialog = builder.create();
return dialog;
}
private class SendComment extends AsyncTask<String, Void, Void>{
public SendComment() {
super();
}
@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Submitting...");
pDialog.setIndeterminate(false);
pDialog.show();
}
@Override
protected Void doInBackground(String... params) {
String content = params[0];
postData(content);
return null;
}
@Override
protected void onPostExecute(Void result) {
theAdapter.notifyDataSetChanged();
pDialog.dismiss();
}
}
public void postData(String content) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/api/opini/add");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("pb_question_id", question_id));
nameValuePairs.add(new BasicNameValuePair("owner_id", owner_id));
nameValuePairs.add(new BasicNameValuePair("opini_text", content));
nameValuePairs.add(new BasicNameValuePair("is_anonym", "1"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httppost);
Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
公共类DialogAddOpini扩展DialogFragment{
列表项适配器适配器;
字符串问题\u id,所有者\u id;
编辑文本问题_字段;
ProgressDialog;
@凌驾
创建对话框上的公共对话框(Bundle savedInstanceState){
AlertDialog.Builder=新建AlertDialog.Builder(getActivity());
LayoutFlater充气机=getActivity().GetLayoutFlater();
最终视图对话框视图=充气机。充气(R.layout.addopini,null);
Bundle mArgs=getArguments();
问题id=mArgs.getString(“问题”);
所有者id=mArgs.getString(“所有者”);
建筑商名称(“Tambahkan Opini”);
builder.setView(dialogView)
.setNegativeButton(R.string.cancel,新建DialogInterface.OnClickListener(){
@凌驾
public void onClick(DialogInterface dialog,int which){
}
})
.setPositiveButton(R.string.okay,新的DialogInterface.OnClickListener(){
@凌驾
public void onClick(DialogInterface dialog,int which){
问题\字段=(EditText)dialogView.findViewById(R.id.content);
SendComment send=新建SendComment();
send.execute(question_field.getText().toString());
}
});
Dialog=builder.create();
返回对话框;
}
私有类SendComment扩展了异步任务{
公共评论(){
超级();
}
@凌驾
受保护的void onPreExecute(){
pDialog=newprogressdialog(getActivity());
pDialog.setMessage(“提交…”);
pDialog.setUndeterminate(假);
pDialog.show();
}
@凌驾
受保护的Void doInBackground(字符串…参数){
字符串内容=参数[0];
postData(内容);
返回null;
}
@凌驾
受保护的void onPostExecute(void结果){
theAdapter.notifyDataSetChanged();
pDialog.disclose();
}
}
公共void postData(字符串内容){
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://localhost/api/opini/add");
List nameValuePairs=新的ArrayList(2);
添加(新的BasicNameValuePair(“问题id”,问题id));
添加(新的BasicNameValuePair(“所有者id”,所有者id));
添加(新的BasicNameValuePair(“opini_文本”,内容));
添加(新的BasicNameValuePair(“is_Anonyman”,“1”);
试一试{
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
}捕获(不支持的编码异常e){
e、 printStackTrace();
}
试一试{
HttpResponse response=httpclient.execute(httppost);
Log.d(“Http响应:,Response.toString());
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
我在DialogFragment
中调用notifyDataSetChanged()
insideonPostExecute
insideDialogFragment
,但它给我NullPointerException
。
有人能帮我吗
这是日志
谢谢
在类对话框addopini
中未初始化适配器
,您需要先初始化它,然后才能在OnPostExecute中使用它
我更愿意使用Listener从DialogFragment
返回数据,并仅在适配器中更新列表
public class DialogAddOpini extends DialogFragment {
private Listener mListener;
public void setListener(Listener listener) {
mListener = listener;
}
static interface Listener {
void returnData();
}
创建对话框时设置侦听器:
public void AddKomentar(View v,int pos){
FragmentActivity activity = (FragmentActivity)(mContext);
FragmentManager fm = activity.getSupportFragmentManager();
ListItemObject item = itemCards.get(pos);
DialogAddOpini dialog = new DialogAddOpini();
Bundle args = new Bundle();
args.putString("question",item.getId());
args.putString("owner",item.getOwner());
dialog.setArguments(args);
dialog.setListener(this);
dialog.show(fm, "Dialog");
}
并返回如下数据:
@Override
protected void onPostExecute(Void result) {
if (mListener != null) {
mListener.returnData();
}
pDialog.dismiss();
}
并覆盖适配器中的返回数据并更新列表:
public class ListItemAdapter extends BaseAdapter implements DialogAddOpini.Listener {
@Override
public void returnData() {
notifyDataSetChanged();
}
}
更新:
您必须传递数据并将其设置在适配器的Arraylist中以反映更改。
显示对话框时跟踪位置:
Integer selected_position =-1 ;
public void AddKomentar(View v,int pos){
FragmentActivity activity = (FragmentActivity)(mContext);
FragmentManager fm = activity.getSupportFragmentManager();
ListItemObject item = itemCards.get(pos);
DialogAddOpini dialog = new DialogAddOpini();
Bundle args = new Bundle();
args.putString("question",item.getId());
args.putString("owner",item.getOwner());
dialog.setArguments(args);
selected_position = pos;
dialog.setListener(this);
dialog.show(fm, "Dialog");
}
@Override
public void returnData( String counter) {
itemCards.get(selected_position).setOpini(counter);
notifyDataSetChanged();
selected_position=-1;
}
希望能有帮助ツ 因为,您的适配器将为空..您需要使用ListItemAdapter
类的同一对象来调用notifyDataSetChanged()
从您在layoutativity
中使用的DialogAddOpini
中,在公共类对话框addopini extensed DialogFragment
中初始化适配器。谢谢,因为它解决了NullPointerException。但是我在适配器中覆盖的NotifyDataSetChange并没有更新listview。您在适配器中的ArrayList itemCards
中设置了数据吗?哇,太好了,很好,非常感谢您的帮助:D
Integer selected_position =-1 ;
public void AddKomentar(View v,int pos){
FragmentActivity activity = (FragmentActivity)(mContext);
FragmentManager fm = activity.getSupportFragmentManager();
ListItemObject item = itemCards.get(pos);
DialogAddOpini dialog = new DialogAddOpini();
Bundle args = new Bundle();
args.putString("question",item.getId());
args.putString("owner",item.getOwner());
dialog.setArguments(args);
selected_position = pos;
dialog.setListener(this);
dialog.show(fm, "Dialog");
}
@Override
public void returnData( String counter) {
itemCards.get(selected_position).setOpini(counter);
notifyDataSetChanged();
selected_position=-1;
}