Android fetch data from mySql

I need to get some data from MySQL database on server. I have the following code. But the application starts when I launch it. I also get permission denied (INTERNET permission missing?) In my Logcat even though I have specified Internet access permission in my android manifest. Any idea what might be wrong here?

Java file

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {

    TextView text;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        connect();
    }
    private void connect() {
        String data;
        List<String> r = new ArrayList<String>();
        ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
        ListView list=(ListView)findViewById(R.id.listView1);
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet("http://xxxxx/data.php");
            HttpResponse response = client.execute(request);
            HttpEntity entity=response.getEntity();
            data=EntityUtils.toString(entity);
            Log.e("STRING", data);

            try {

                JSONArray json=new JSONArray(data);
                for(int i=0;i<json.length(); i++)
                {
                    JSONObject obj=json.getJSONObject(i);
                    String name=obj.getString("name");
                    String desc=obj.getString("description");
                   // String lat=obj.getString("lat");
                    Log.e("STRING", name);
                    r.add(name);
                    r.add(desc);
                  //  r.add(lat);
                    list.setAdapter(adapter);

                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } catch (ClientProtocolException e) {
            Log.d("HTTPCLIENT", e.getLocalizedMessage());
        } catch (IOException e) {
            Log.d("HTTPCLIENT", e.getLocalizedMessage());
        }


    }

      

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.diana.menu" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <uses-permission android:name="android.permission.INTERNET"/>
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

      

data.php

<?php
$conn=mysql_connect('localhost', 'xxxx', 'xxxxx','u199776286_pois');

if(!$conn )
{
  die('Could not connect: ' . mysql_error());
}

$sql = 'SELECT name, description FROM pois';

mysql_select_db('u199776286_pois');
$retval = mysql_query( $sql, $conn );

if(! $retval )
{
  die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
    echo "NAME : {$row['name']} <br> ".
         "DESCRIPTION : {$row['description']} <br> ".
         "--------------------------------<br>";
} 
echo "Fetched data successfully\n";
mysql_close($conn);


?>

      

my logarithm enter image description here

+3


source to share


5 answers


This is because you are connecting to the MySQL server from the main UI thread. create an additional thread (or asynchronous task) to connect and get results.



+2


source


StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

      

Writing the above code is not at all the best way to get rid of the NetworkOnMainThreadException . You should use any background thread for networking in android above api 11 like Asynch Task , Intent Service , etc.

How to fix android.os.NetworkOnMainThreadException?



You can also use Executors for network task

Executors.newSingleThreadExecutor().submit(new Runnable() { 
    @Override
    public void run() {
        //You can performed your task here.
    }
});

      

+1


source


Use Async Task to get data from your database.

+1


source


Add internet permission to AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />

      

Use Asynck Task like

 List<String> r = new ArrayList<String>();

      

Must be declared from connect ();

from Oncreate

 new LongOperation().execute("");

      

now create

 private class LongOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
             connect();
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
          ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
         ListView list=(ListView)findViewById(R.id.listView1);
         list.setAdapter(adapter);
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }

      

// need to remove the Ui control from connect();

and require a value bind it toonPostExecute

+1


source


use Async. For more help check this

+1


source







All Articles