public class MainActivity extends AppCompatActivity {
private String url = "http://172.16.156.56";
private String url_file="/fetch.php";
private String sql_table = "products";
private ListView list;
ArrayList<String> rows;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list=(ListView) findViewById(R.id.listView);
rows = new ArrayList<String>();
new RetrieveSQLRecords().execute(url + url_file);
}
private class RetrieveSQLRecords extends AsyncTask<String, Void, Void> {
private String Content;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
Dialog.setMessage("Please wait..");
Dialog.show();
}
protected Void doInBackground(String... urls) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urls[0]);
try {
HttpResponse response = httpclient.execute(httppost);
Content = inputStreamToString(response.getEntity().getContent());
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
Dialog.dismiss();
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(Content);
JSONArray jsonMainNode = jsonResponse.optJSONArray(sql_table);
for(int i=0; i < jsonMainNode.length(); i++)
{
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String id = jsonChildNode.optString("id").toString();
String title = jsonChildNode.optString("title").toString();
String description = jsonChildNode.optString("description").toString();
String img_url = jsonChildNode.optString("img_url").toString();
rows.add(id + ". " + title + ", " + description + ", " + img_url);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, rows);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private String inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String strAns = "";
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
strAns = answer.toString();
}
catch (IOException e) {
e.printStackTrace();
}
return strAns;
}
这些是我的主要活动代码,但我无法连接到我在phpMyAdmin设置的数据库。当我直接从我的电脑浏览时,我可以,但不使用它,当我想启动我的应用程序时,应用程序崩溃。
答案 0 :(得分:0)
检查Mainfest.xml文件中的权限...... Internet权限和读写