Connect to php file Android

You tried to contact the php file But I can not get the required information

Link Php File: http://aristo.eb2a.com/hello.php

The result in my app:

enter image description here

Code:

public class MainActivity extends AppCompatActivity {
TextView msgHello;
Button getData;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    msgHello = (TextView) findViewById(R.id.txtHelloMsg);
    getData = (Button) findViewById(R.id.btngetdata);


    getData.setOnClickListener(new View.OnClickListener() {



        @Override
        public void onClick(View view) {

            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        URL urlMsgHello = new URL("http://aristo.eb2a.com/hello.php");
                        HttpURLConnection connection = (HttpURLConnection) urlMsgHello.openConnection();

                        InputStreamReader stream = new InputStreamReader(connection.getInputStream());
                        BufferedReader buf = new BufferedReader(stream);
                        final String Hello = buf.readLine();

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                msgHello.setText(Hello);
                            }
                        });


                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
            Thread thread = new Thread(runnable);
            thread.start();


        }
    });



}
}

It works without problems but does not return the required value

How can I solve this?

Answer

Did you used JSON (Javascript Object Notation) ?

Actually what you did is opened a Connection get to website and printed its result which is 100% correct.

But what you are expecting is “Hello” to be printed Why? because What you see on browser is parsed by browsers and displayed as UI

In real world applications People use JSON a language which fills the gap of communication b/w many languages Json is easy as nothing just matter of lines.

change your PHP script as

header('Content-type: application/json');
$data = ['Your data here']
echo json_encode($array);

and Also change the android java code.

JSON

https://www.tutorialspoint.com/json/

JSONParser

https://developer.android.com/reference/android/util/JsonReader.html

Php Json

https://www.w3schools.com/js/js_json_php.asp

Leave a Reply

Your email address will not be published. Required fields are marked *