Search code examples
javaandroidandroid-studionetbeanshttpurlconnection

Android: HttpUrlConnection returning empty output


So i'm trying to read a stream from URL and set the result in a text view. The problem is that the code Android studio is not returning any result on my device, while the same code on net beans returns the stream output. I don't understand where is the problem because i'm using the same code which was used in Android studio and Netbeans.Als The application on android studio is not crashing or throwing any errors.

Just to let you know I have opened the URL which is in the android studio code in my phone's browser and it's working. Also I added the internet permission in manifest. And I did put the function changeText in "onClick" attribute.

The following code was tested on NetBeans and Android Studio(on my galaxy S6).

Android Studio code:

       package com.example.mohammed.acc;

    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.TextView;

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

    public class MainActivity extends AppCompatActivity {

        public void changeText (View v){
            TextView t1 = (TextView)findViewById(R.id.t1);
            URL url;
            HttpURLConnection con;

            try{
                StringBuilder sb = new StringBuilder();
                url = new URL("http://192.168.1.104:8000/api");
                con = (HttpURLConnection) url.openConnection();
                BufferedInputStream in = new BufferedInputStream(con.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String Line = "";

                while((Line = reader.readLine()) != null){
                    sb.append(Line);
                }

                t1.append(sb.toString());
                in.close();




}
        catch (MalformedURLException ex) {
           t1.setText(ex.getMessage());
        }
        catch (IOException ex){
            t1.setText(ex.getMessage());
        } catch (Exception ex){
            t1.setText(ex.getMessage());
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }
}

NetBeans Code:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication21;


import java.io.BufferedInputStream;
import java.util.Stack;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class JavaApplication21 {


    public static void main(String[] args) {
         try{
            StringBuilder sb = new StringBuilder();
            URL url = new URL("http://127.0.0.1:8000/api");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            BufferedInputStream in = new BufferedInputStream(con.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String Line = "";

            while((Line = reader.readLine()) != null){
                sb.append(Line);
            }
            System.out.print(sb.toString());
            in.close();
        }
        catch (Exception ex){
            System.out.print(ex.getMessage());
        }

    }

}

NetBeans output: it's working as you can see. Netbeans output Android studio, my phone's output: enter image description here Logs snapshots This is after running and clicking the button. enter image description here


Solution

  • i see 2 problems:

    1: your http io is not performed in the worker thread;

    2: haven't asked for permission in runtime (your api level could be above 22);

    import android.annotation.TargetApi;
    import android.os.AsyncTask;
    import android.os.Build;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.example.root.myapplication.R;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    public class MainActivity extends AppCompatActivity {
    
    
        @TargetApi(23)
        protected void askPermissions() {
            String[] permissions = {
                    "android.permission.INTERNET"
            };
            int requestCode = 200;
            requestPermissions(permissions, requestCode);
        }
    
        public void changeText (View v){
    
            final TextView t1 = (TextView)findViewById(R.id.t1);
    
            new AsyncTask<Void,Void,Void>(){
                private Exception exception;
                private StringBuilder sb;
                @Override
                protected Void doInBackground(Void... voids) {
                    try{
                        sb = new StringBuilder();
                        URL url;
                        HttpURLConnection con;
                        url= new URL("http://peyvandha.ir");
                        con= (HttpURLConnection) url.openConnection();
                        BufferedInputStream in = new BufferedInputStream(con.getInputStream());
                        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                        String Line = "";
                        while((Line = reader.readLine()) != null){
                            sb.append(Line);
                        }
                        in.close();
                    }catch (Exception ex){
                        this.exception=ex;
                    }
                    return null;
                }
    
                @Override
                protected void onPostExecute(Void aVoid) {
                    if(sb!=null){
                        //do what you do;
                        t1.setText(sb.toString());
                    }else {
                        t1.setText(exception.getMessage());
                    }
                    super.onPostExecute(aVoid);
                }
            }.execute();
    
        }
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            if(Build.VERSION.SDK_INT>22)askPermissions();
    
        }
    }