我正在尝试开发我的第一个应用程序,其中包含一个导航抽屉。我目前正在尝试从mysql数据库(在xampp上运行)读取数据并将其显示在ListView中。我已阅读了很多教程,但由于我的.java类正在扩展Fragment(由于NavigationDrawer),我无法找到可行的解决方案。经过几个小时的阅读和测试,我想出了以下内容(我知道这不是最高贵的方式,但无论如何......)。不幸的是,在模拟器中尝试时,应用程序会一直停止。在我看来,方法getData()必须有问题。任何人都知道为什么?非常感谢你的帮助! 干杯, keja
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();
}
}
}
答案 0 :(得分:0)
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");
}
//here u pass data to arrayadapter and load to list view..
} catch (Exception e) {
e.printStackTrace();
}
答案 1 :(得分:0)
我找到了解决方案!问题是&#34;服务器&#34;地址。模拟器似乎不喜欢&#34; localhost&#34;或&#34; 127.0.0.1&#34;,所以我不得不将其更改为我的动态IP地址。 : - )