0

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

6
  • @JeelVankhede That's supposed to be a button click handler. So no, he didn't. Commented Sep 26, 2018 at 19:42
  • I mentioned that I did call the function. Commented Sep 26, 2018 at 19:49
  • Also I used the same function to change the textView to "Hello World" and it worked. Commented Sep 26, 2018 at 20:05
  • t1.append(sb.toString()) did you mean setText() here in try block after while loop? Commented Sep 26, 2018 at 20:13
  • It was t1.setText(). But I forgot to change it back before posting the code here. Commented Sep 26, 2018 at 20:26

2 Answers 2

1

Your code should be causing a NetworkOnMainThreadException if its being called (you can't make a network call on the main thread). So most likely it isn't being called at all, and your button handling code is broke.

Actually, I see you're catching Exception. So yeah, it would be throwing a NetworkOnMainThreadException, and you're catching and ignoring it. Which even basic stepping through in a debugger or reading the logs would tell you, if you had bothered to print the exceptions to log. If you don't print exceptions somewhere, don't be surprised if you see no errors yet nothing occurs.

Also- not a bug, but running findViewById in an event handler is considered a bad practice. These should be run once in onCreate and the result cached.

Sign up to request clarification or add additional context in comments.

3 Comments

It's not causing the exception which you have mentioned.
@Mick2160 Then its not being called. That function as you have written it will not work. Either the networking will fail, or the writing to the text view will fail, as one cannot be done on the main thread and the other must be done on the main thread. And click handlers are run on the main thread.
What should I do now? @Gabe Sechan
0

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();

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.