gpt4 book ai didi

java - 具有异步任务的 fragment 中的 ListView

转载 作者:行者123 更新时间:2023-12-01 20:13:27 28 4
gpt4 key购买 nike

my error log我尝试在 fragment 中加载 ListView 。但是我的应用程序在单击按钮填充 ListView 时崩溃。我不知道我犯了什么错误。任何帮助将不胜感激。我已经尝试了大部分与此相关的东西..但没有什么效果很好。(我删除了一些代码以避免看起来笨拙)

这是我的 fragment 代码:

public class Func extends Fragment {

ArrayList<Flowers> flowersList = new ArrayList<Flowers>();

String url ="http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";

@Override
public android.view.View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab2, container, false);

FlowerAdapter adapter=new FlowerAdapter(getActivity().getApplicationContext(),R.layout.flower_list_xml,flowersList);
ListView listView=(ListView)rootView.findViewById(R.id.listView);
listView.setAdapter(adapter);

return rootView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
Button b = (Button)getView().findViewById(R.id.button);

b.setOnClickListener( new View.OnClickListener() {

@Override

public void onClick(View view) {

new BackTask().execute(url);

}

});

}

//我的异步任务从这里开始

 public class BackTask extends AsyncTask<String, Void, String> {

@Override
protected void onPreExecute(){
super.onPreExecute();
}
@Override
protected String doInBackground(String... strings) {
String result = null;
BufferedReader reader = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Log.d("testhtt2", "test");
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.d("test44", sb.toString());
return sb.toString();

} catch (Exception e) {
e.printStackTrace();
return null;

} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;

}
}

return result;
}
}
@Override
protected void onPostExecute(String s){
try {
JSONArray ar =new JSONArray(s);
for (int i = 0; i < ar.length(); i++){
JSONObject jsonObject=ar.getJSONObject(i);
Flowers flowers= new Flowers();
flowers.setName(jsonObject.getString("NAME"));
flowersList.add(flowers);
}
} catch (JSONException e) {
e.printStackTrace();
}

最佳答案

您在 doInBackground 中返回 null,然后尝试在 OnPostExecute 中将其解析为 JSONArray。从 doInBackground 方法返回正确的字符串,看看是否有帮助。

关于java - 具有异步任务的 fragment 中的 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46296864/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com