0

I am trying to make a simple GET request to my local NodeJS server to get some JSON objects. I changed the request so it happens as an AsyncTask rather than in the UI thread. But I am still not able to get it to work. Does this code look correct? Sorry, not great with Java yet.

    package com.dd.relay;

import com.dd.relay.HttpRequest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ListActivity {
    public final static String EXTRA_MESSAGE = "com.dd.relay.MESSAGE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);

             // We'll define a custom screen layout here (the one shown above), but
             // typically, you could just use the standard ListActivity layout.
             setContentView(R.layout.activity_main);


          // Make a GET request for data
             String url = "http://localhost.com/contacts";
             String res = null;
             try {
                HttpRequest request = new HttpRequest();
                request.execute(new URL(url));

                Log.v(EXTRA_MESSAGE, res);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

             TextView textView = (TextView) findViewById(R.id.textv);
             Context context = this.getApplicationContext();
             Toast mytoast = Toast.makeText(context,  res, Toast.LENGTH_LONG);
             mytoast.show();
             textView.setText(res);
            // Create list for contacts
            /* List<Map<String, RelayContact>> data = null;


             // Now create a new list adapter bound to the cursor.
             // SimpleListAdapter is designed for binding to a Cursor.
             ListAdapter adapter = new SimpleAdapter(this, data, 0, new String[] {"First", "Number"}, new int[] {android.R.id.text1, android.R.id.text2});  // Parallel array of which template objects to bind to those columns.

             // Bind to our new adapter.
             this.setListAdapter(adapter);*/
}

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




}

And here is my custom HttpRequest AsyncTask class

package com.dd.relay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.AsyncTask;

public class HttpRequest extends AsyncTask<URL, Void, Void> {

    protected String doInBackground(URL url) throws Exception {

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


          if (conn.getResponseCode() != 200) {
            throw new IOException(conn.getResponseMessage());
          }

          // Buffer the result into a string
          BufferedReader rd = new BufferedReader(
              new InputStreamReader(conn.getInputStream()));
          StringBuilder sb = new StringBuilder();
          String line;
          while ((line = rd.readLine()) != null) {
            sb.append(line);
          }
          rd.close();

          conn.disconnect();
        return sb.toString();


    }

    protected void onProgressUpdate(Integer progress) {

    }

    protected void onPostExecute(String result) {
      System.out.println(result);
    }

    @Override
    protected Void doInBackground(URL... arg0) {
        // TODO Auto-generated method stub
        return null;
    }


}
Matt Hintzke
  • 7,744
  • 16
  • 55
  • 113

2 Answers2

2

Android does not allow network communication to be done on the UI thread. Android provides a class called AsyncTask that is intended for such interactions. See this link for details and one option for a solution (This is probably what you want):

How to fix android.os.NetworkOnMainThreadException?

or you can also create a custom class that extends Thread or implements Runnable that posts to the UI thread using a Handler

Community
  • 1
  • 1
Scott
  • 1,652
  • 1
  • 13
  • 10
  • Ok thanks alot. That exception is exactly what was being thrown – Matt Hintzke Jul 20 '13 at 19:03
  • @Matt, I am not sure about over loading the `doInBackgorund()` method. If it is working for you that's fine Otherwise just define one. Secondly, The purpose of the `AsyncTask` is to do long processes (eg, networking) and then have an easy way to get information back to the UI thread - this is what `onPostExecute()` does (The return statement of doInBackground gets passed to the onPostExecute() method). After considering the above, if things are still not working update you question with a specific crash or exception thrown – Scott Jul 21 '13 at 04:52
  • I forgot to explicitly mention that onPostExecute() gets run on the UI thread – Scott Jul 21 '13 at 05:01
0

try this link hope use full to you :-

Verifying login details via http get : Android

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

        @Override
        protected String doInBackground(String... params) {
               // call function 
                login(userName, password);
                return null;
        }        

        @Override
        protected void onPostExecute(String result) {             
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }
Community
  • 1
  • 1
duggu
  • 37,851
  • 12
  • 116
  • 113