简体   繁体   中英

Couldn't Connect to Database with Android

I am trying to execute the following code for retrieving data from database using web services:

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getData();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}


public void getData(){
    TextView resultView = (TextView) findViewById(R.id.textView1);
    String result = "";
    InputStream isr = null;
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://HOSTNAME/FILENAME.php");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        isr = entity.getContent();
    }
    catch(Exception e){
        Log.e("log_tag","Error in http connection"+e.toString());
        resultView.setText("Couldnt connect to database");
    }
    //converting to string
    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null){
            sb.append(line + "\n");
        }
        isr.close();
        result = sb.toString();
    }
    catch(Exception e){
        Log.e("log_tag", "Error converting result"+ e.toString());
    }

    //parse data
    try{
        String s = "";
        JSONArray jArray = new JSONArray(result);
        for(int i = 0;i<jArray.length();i++){
            JSONObject json = jArray.getJSONObject(i);
            s = s + "St.ID" + json.getString("StId") + "\n " +json.getString("StName") + "\n" + json.getString("StMail");

        }
        resultView.setText(s);
    }
    catch(Exception e){
        Log.e("Log_tage", "Error Parsing Data"+e.toString());
    }
}

But an error returns : Couldn't connect to database.

And here's the output LogCat:

11-14 20:10:35.057: E/log_tag(5323): Error in http connectionandroid.os.NetworkOnMainThreadException

11-14 20:10:35.057: E/log_tag(5323): Error converting resultjava.lang.NullPointerException: lock == null

11-14 20:10:35.057: E/Log_tage(5323): Error Parsing Dataorg.json.JSONException: End of input at character 0

I've added a php file on some web service and it's working well, but i think it's about the HttpPost URL, is there a specific format for the HttpPost URL or is it just the same URL as given in the web service ?

PHP file:

   <?php 
$con = mysql_connect("HOST","USERNAME","PASSWORD");
if (!$con)
    {
    die('Could not Connect:'. mysql_error());
    }
mysql_select_db("database_name",$con);

$result = mysql_query("SELECT * FROM table_name");

while($row = mysql_fetch_assoc($result))
    {
       $output[]=$row;
    }

print(json_encode($output));
mysql_close($con);
?>

Please help with that.

There is no specific format for the HttpPost URL, it is just the same URL as given in the web service.

You must use AsyncTask to solve the "Couldn't connect to database" error.

Here is your code using AsynTask, also you have to set the text of the TextView in the onPostExecute method, like shown:

RetrievingDataFromDatabase retrievingTask;
TextView resultView;
String s;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    retrievingTask = new RetrievingDataFromDatabase();
    retrievingTask.execute((Void) null);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public void getData(){
    resultView = (TextView) findViewById(R.id.textView1);
    String result = "";
    InputStream isr = null;
    try { 
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://HOSTNAME/FILENAME.php");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        isr = entity.getContent();
    } catch(Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
        resultView.setText("Couldnt connect to database");
    }
    //converting to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(isr, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        isr.close();
        result = sb.toString();
    } catch(Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    //parse data
    try {
        s = "";
        JSONArray jArray = new JSONArray(result);
        for(int i = 0; i < jArray.length(); i++){
            JSONObject json = jArray.getJSONObject(i);
            s = s + "St. ID" + json.getString("StId") + "\n " + json.getString("StName") + "\n" + json.getString("StMail");
        }
    }
    catch(Exception e) {
        Log.e("Log_tage", "Error Parsing Data" + e.toString());
    }
}

class RetrievingDataFromDatabase extends AsyncTask<Void, Void, Boolean> {

    @Override
    protected Boolean doInBackground(Void... params) {
        getData();
        return null;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        resultView.setText(s);
    }
}

Problem solved and data retrieved by using @Carlo 's code and editing the following line of code:

HttpPost httppost = new HttpPost("http://HOSTNAME/FILENAME.php");

to:

HttpGet httppost = new HttpGet("http://HOSTNAME/FILENAME.php");

as mentioned in my code, i wanted to retrieve data from the URL not posting data.

HttpPost > used for submitting data to a specified resource. HttpGet > used for retrieving data from a specified resource.

Thanks all for your help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM