0

I'm new to android and LAMP. I have some data on the MySQL server, and I'm trying to write an app in order to access that data.
Meanwhile, all I want to do is to press a button and get specific information (the URL is hard-coded). When I type in the url in chrome (running on my android phone) I get exactly what I'm looking for, but when I try getting the same info through the app, the app crashes. this is the code:

    public void getInfo(View view) throws Exception {

    try {
        URL url = new URL("http://192.168.1.57:80/TOTSphp/getAllUsersInfo.php");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("GET");
        conn.setRequestProperty("User-Agent", "TOTS");
        //int responseCode = conn.getResponseCode();

        BufferedReader in;
        conn.setDoOutput(true);
        conn.setDoInput(true);
        try {
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String inputLine;

            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
                in.close();
            }
        } finally {
            conn.disconnect();
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The code appears right after the onCreate() method and is called through a button with android:onClick="getInfo".

While trying to find an answer, I added:

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

to AndroidManifest.xml, but that didn't seem to work....

Thanks a lot!!!!

activesince93
  • 1,716
  • 17
  • 37
M W
  • 29
  • 1
  • 4

4 Answers4

1

You have to define AsyncTask for make connection..

Call below AsyncTask in your button click.

new AsyncTaskGetData().execute();

Example

private class AsyncTaskGetData extends AsyncTask<String, String, String> {

    ProgressDialog pDialog;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(signInScreen);
        pDialog.setMessage(getString(R.string.please_wait));
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... arg0) {
        try {
            URL url = new URL("http://192.168.1.57:80/TOTSphp/getAllUsersInfo.php");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("GET");
            conn.setRequestProperty("User-Agent", "TOTS");
            //int responseCode = conn.getResponseCode();

            BufferedReader in;
            conn.setDoOutput(true);
            conn.setDoInput(true);
            try {
                in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String inputLine;

                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                    in.close();
                }
            } finally {
                conn.disconnect();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 

    }

    @Override
    protected void onPostExecute(String email) {
        // Dismiss the progress dialog
        if(pDialog.isShowing()) {
            pDialog.dismiss();
        }

    }
}
Chirag Savsani
  • 6,020
  • 4
  • 38
  • 74
1

As an addition to former answers, certainly you have to use AsyncTask or Thread. Android Services is a simpler tool to execute an AsyncTask. IntentService is my favourite. You can look Services and IntentService.

Basically, you should place your getInfo() method in your IntentService. In my case, it is better to make String the return type of getInfo().Because my response from the server is just text.

When you call your service:

    MyService.startAction(this);

Your service code should be like this:

    public class MyService extends IntentService {

            public MyService(){ super("MyService");}

            public static void startAction(Context context){
                    Intent intent = new Intent(context,MyService.class);
                    context.startService(intent);
            }

            @Override
            protected void onHandleIntent(Intent intent) {
                     Intent broadcastIntent = new Intent("ACTION_COMPLETED");//In manifest should be defined as intent filter's action
                     broadcastIntent.putExtra("RESPONSE",getInfo());
                     sendBroadcast(broadcastIntent);
            }

            public String getInfo(){ /*Implemented here*/}

    }

After sending the broadcast, you should receive the response in a BroadcastReceiver and parse if necessary.

Anıl
  • 136
  • 5
0

Android does not allow you to call network Operation on main UI Thread, hence you are getting NetworkOnMainThread Exception.

You have to use a thread or AsyncTask for network Operation. Refer this answer : AsyncTask for Network Operation

Community
  • 1
  • 1
Akshay Bhat 'AB'
  • 2,690
  • 3
  • 20
  • 32
0

Because of you cannot do networking operations in the main thread. According to Android developer, below link use AsyncTask. http://developer.android.com/reference/android/os/AsyncTask.html

for Example link : http://androidexample.com/AsyncroTask_Example_To_Get_Server_Data_-_Android_Example/index.php?view=article_discription&aid=59&aaid=84

Mayur Sakhiya
  • 326
  • 2
  • 14