Diana
Diana

Reputation: 1437

Android fetch data from mySql

I have to get some data from a MySQL database on server. I have the following code.but the app crashes when I run it. I also get the Permission denied (missing INTERNET permission?) in my Logcat even though I specified the internet 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 logcat enter image description here

Upvotes: 3

Views: 1423

Answers (5)

Nasir Iqbal
Nasir Iqbal

Reputation: 53

use Async. For more help check this

Upvotes: 1

Ankitkumar Makwana
Ankitkumar Makwana

Reputation: 3485

Add Internet Permission in your AndroidManifest.xml

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

Use Asynck Task like

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

Need to declare out of connect();

with 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 Ui control from connect(); and that require value bind it on onPostExecute

Upvotes: 1

Anoop M Maddasseri
Anoop M Maddasseri

Reputation: 10529

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

Writing the above code is not at all a better way to get rid from NetworkOnMainThreadException . You have to use any background thread for doing network operation in android above api 11 such as Asynch Task , Intent Service etc.

How to fix android.os.NetworkOnMainThreadException?

You can also use Executors for network task's

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

Upvotes: 1

HassanUsman
HassanUsman

Reputation: 1973

Use Async Task to get the data from your database..

Upvotes: 1

Buda Gavril
Buda Gavril

Reputation: 21627

This happens because you're connecting to your MySQL server from the main UI thread. create a secondary thread (or async task) to connect and to get the results.

Upvotes: 2

Related Questions