1

Here Im trying to parsing read from url and trying to print in console.Im using Asynctask as we cant have network connection on main thread

package com.example.parse;

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

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Button create =(Button) findViewById(R.id.button1);
    create.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click

            EditText et1 = (EditText) findViewById(R.id.editText1);
            String url = et1.getText().toString();
            new ParseString().execute(url);

        }
    });
}

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

}

  class ParseString extends AsyncTask<String, Void, BufferedReader>{

@Override
protected BufferedReader doInBackground(String... urls) {
    // TODO Auto-generated method stub

    BufferedReader in = null;
    URL url = null;
    try {
        url = new URL(urls[0]);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
            in = new BufferedReader(
                new InputStreamReader(
                url.openStream()));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return in;
}

protected void onPostExecute(BufferedReader buf){

    String inputLine;

    try {
        while ((inputLine = buf.readLine()) != null)
            System.out.println(inputLine);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        buf.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}
} 

This is the log cat error message

12-13 01:33:58.404: E/AndroidRuntime(1058): FATAL EXCEPTION: AsyncTask #2
12-13 01:33:58.404: E/AndroidRuntime(1058): Process: com.example.parse, PID: 1058
12-13 01:33:58.404: E/AndroidRuntime(1058): java.lang.RuntimeException: An error occured while executing     doInBackground()
12-13 01:33:58.404: E/AndroidRuntime(1058):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
12-13 01:33:58.404: E/AndroidRuntime(1058):     at     java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
12-13 01:33:58.404: E/AndroidRuntime(1058):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
12-13 01:33:58.404: E/AndroidRuntime(1058):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
12-13 01:33:58.404: E/AndroidRuntime(1058):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
12-13 01:33:58.404: E/AndroidRuntime(1058):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
12-13 01:33:58.404: E/AndroidRuntime(1058):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
12-13 01:33:58.404: E/AndroidRuntime(1058):     at java.lang.Thread.run(Thread.java:841)
12-13 01:33:58.404: E/AndroidRuntime(1058): Caused by: java.lang.NullPointerException
12-13 01:33:58.404: E/AndroidRuntime(1058):     at com.example.parse.ParseString.doInBackground(MainActivity.java:62)
12-13 01:33:58.404: E/AndroidRuntime(1058):     at com.example.parse.ParseString.doInBackground(MainActivity.java:1)
12-13 01:33:58.404: E/AndroidRuntime(1058):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
12-13 01:33:58.404: E/AndroidRuntime(1058):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-13 01:33:58.404: E/AndroidRuntime(1058):     ... 4 more

P.S I have added network permission in manifest.xml

Abhishek
  • 47
  • 6

3 Answers3

0

Use this in your asynctask :-

import java.net.*;
public class DemoConvertURItoURL {

    public static void main(String[] args) {
        URI uri = null;
        URL url = null;
        String uriString = "http://www.google.co.in/"; // In your case "urls[0]" 
        //without the quotes

        // Create a URI object
        try {
            uri = new URI(uriString);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        // Convert the absolute URI to a URL object
        try {
            url = uri.toURL();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
         // Write your BufferedReader code here
        //print the URI and URL 
        System.out.println("Original URI  : " + uri);
        System.out.println("Converted URL : " + url);

    }

}
Rahul Gupta
  • 5,275
  • 8
  • 35
  • 66
0
class testsTask extends AsyncTask<String, Integer, Integer> {


            @Override
            protected void onPreExecute() 
            {
                h=new Handler();

                pd = ProgressDialog.show(ctx, "", "Please Wait.");
                pd.setCancelable(false);
                pd.setCanceledOnTouchOutside(false);
            }

            String response;


            protected Integer doInBackground(String... urls) {
                int webresponse=-1;
                try {
                    response = httpClient.SendHttpPost(urls[0].toString(), jsonObjAuth);
                    if (response.equalsIgnoreCase("")) {
                        webresponse= 1;
                    } else {
                        webresponse= 0;
                    }
                } catch (IOException e) {


                    e.printStackTrace();
                }
                return webresponse;
            }

            protected void onPostExecute(Integer result) 
            {
                if (result == 0) 
                {

                    strResponse = response;
                    Log.i("resp", strResponse);

                    pd.dismiss();

                }
            }
        }

I hope its useful to you....

dipali
  • 10,966
  • 5
  • 25
  • 51
  • it was useful and i even got another solution http://stackoverflow.com/questions/17271147/android-get-content-from-url – Abhishek Dec 15 '13 at 07:13
0

first check internet permission in android menifest file

and then

try this

URL url = null;
    try {
        url = new URL(url);//u use urls[0]
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
The Ray of Hope
  • 738
  • 1
  • 6
  • 16