【发布时间】:2018-07-07 15:44:04
【问题描述】:
我正在尝试开发我的第一个应用程序,其中包含一个导航抽屉。我目前正在尝试从 mysql 数据库(在 xampp 上运行)读取数据并将其显示在 ListView 中。我已经阅读了很多教程,但是由于我的 .java 类正在扩展 Fragment(由于 NavigationDrawer),我无法找到一个可行的解决方案。经过数小时的阅读和测试,我想出了以下方法(我知道这不是最崇高的方式,但无论如何......)。不幸的是,在模拟器中尝试时,应用程序不断停止。在我看来,getData() 方法一定有问题。有人知道为什么吗?非常感谢你的帮助! 干杯, 凯亚
public class newsFragment extends Fragment{
View myView;
ListView lv;
String address = "http://127.0.0.1/android/words.php";
InputStream is = null;
String line = null;
String result = null;
String[] data;
JSONObject jo = null;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.news_layout,container,false);
lv = (ListView)myView.findViewById(R.id.lv);
StrictMode.setThreadPolicy((new StrictMode.ThreadPolicy.Builder().permitNetwork().build()));
getData();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,data);
lv.setAdapter(adapter);
return myView;
}
private void getData(){
try {
URL url = new URL(address);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
is = new BufferedInputStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
//READ IS CONTENT INTO A STRING
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
while((line=br.readLine())!=null){
sb.append(line).append(" \n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
//PARSE JSON DATA
try{
JSONArray ja = new JSONArray(result);
data = new String[ja.length()];
for(int i=0;i<ja.length();i++){
jo=ja.getJSONObject(i);
data[i]=jo.getString("name");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
【问题讨论】:
标签: android mysql json listview android-fragments