Wenhan Xiao Wenhan Xiao -4 years ago 100
Android Question

Cannot connect to myPHPadmin database

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;
}


this are my codes for Main activity , but i cannot connect to the Database i set up at phpMyAdmin . when i browse directly from my computer i can , but not using this , when i want to launch my app , the app crashes

Answer Source

check permission in your Mainfest.xml file......Internet permission and read write

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download