0

I'm not able to display the data from my server in textfield. I have collected the data from the server using JSON and I converted into the string and integer variable, I'm not able to access this variable from outside of the class, I'm using PHP MySQL server database. The main problem I'm facing:

When I am running that app on my android phone the data from my server need to be displayed in the "text field" and was not displaying, my laptop & mobile is on the same network.

I'm not able display the String i.e read from json to textfield And anyone knows how to initialize view in this code

This is java file

     package com.sun.user.demophp;

        import android.os.AsyncTask;
        import android.support.v4.app.FragmentActivity;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.Button;
        import android.widget.TextView;
        import android.widget.Toast;




   import com.google.android.gms.maps.CameraUpdateFactory;
        import com.google.android.gms.maps.GoogleMap;
        import com.google.android.gms.maps.OnMapReadyCallback;
        import com.google.android.gms.maps.SupportMapFragment;
        import com.google.android.gms.maps.model.LatLng;
        import com.google.android.gms.maps.model.MarkerOptions;

        import org.json.JSONArray;
        import org.json.JSONObject;

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

        public class MapsActivity extends FragmentActivity implements 
        OnMapReadyCallback {

            private GoogleMap mMap;
            TextView textView ;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.merge);
                // Obtain the SupportMapFragment and get notified when the map is 
                 ready to be used.
                SupportMapFragment mapFragment = (SupportMapFragment) 
                getSupportFragmentManager()
                        .findFragmentById(R.id.map);
                mapFragment.getMapAsync(this);
                 textView = findViewById(R.id.tvdata);


                }


           public void buclick(View view){


              String url;
                url =  "http://192.168.43.58:10080/androidDemo/create.php?
                District=\"Mysore\"";
                new MyAsyncTaskgetNews().execute(url);
               switch (view.getId()) {
                   case R.id.bu2:
                       district = "Mysore";

                     url="http://192.168.43.58:10080/androidDemo/create.php?
                District=district ";
        //               Toast.makeText(getApplicationContext(), district, 
           Toast.LENGTH_LONG).show();
         //               break;
        //           default:
        //              
        //       }
           }

            public void onMapReady(GoogleMap googleMap) {
                mMap = googleMap;

                // Add a marker in Sydney and move the camera
                LatLng sydney = new LatLng(-34, 151);
                mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in 
                   Sydney"));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
            }


            // get news from server
            public class MyAsyncTaskgetNews extends AsyncTask<String, String, 
       String> {
                @Override
                protected void onPreExecute() {
                    //before works
                }
                @Override
                protected String  doInBackground(String... params) {
                    // TODO Auto-generated method stub
                    try {
                        String NewsData;
                        //define the url we have to connect with
                        URL url = new URL(params[0]);
                        //make connect with url and send request
                        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                        //waiting for 7000ms for response
                        urlConnection.setConnectTimeout(7000);//set timeout to 5 seconds

                        try {
                            //getting the response data
                            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                            //convert the stream to string
                            NewsData = ConvertInputToStringNoChange(in);
                            //send to display data
                            publishProgress(NewsData);
                        } finally {
                            //end connection
                            urlConnection.disconnect();
                        }

                    }catch (Exception ex){}
                    return null;
                }
                protected void onProgressUpdate(String... progress) {

                    try {
                        JSONObject json = new JSONObject(progress[0]);
                        String districts;
                        int afected_people ;
                        int total_people ;

                        districts = json.getString("District");
                        afected_people = json.getInt("DA");
                        total_people = json.getInt("people");
                       textView.setText(district);


        //Toast.makeText(getApplicationContext(),district,Toast.LENGTH_LONG).show();


     //Toast.makeText(getText(getApplicationContext(),district,Toast.LENGTH_LONG)).show();
                        calculate(districts,afected_people,total_people);


                    } catch (Exception ex) {
                    }


                }

                protected void onPostExecute(String  result2){


                }




            }

            private void calculate(String dis, int afected_people, int total_people) {
                        textView.setText(dis);
            }

            // this method convert any stream to string
            public static String ConvertInputToStringNoChange(InputStream inputStream) {

                BufferedReader bureader=new BufferedReader( new InputStreamReader(inputStream));
                String line ;
                String linereultcal="";

                try{
                    while((line=bureader.readLine())!=null) {

                        linereultcal+=line;

                    }
                    inputStream.close();


                }catch (Exception ex){}

                return linereultcal;
            }
        }

enter image description here

Dharman
  • 30,962
  • 25
  • 85
  • 135
Suresh N
  • 29
  • 6
  • You may also need to use `childFragmentManager()` instead of `getSupportFragmentManager()` - https://stackoverflow.com/a/25749277/469080 – Michael Dodd Mar 22 '18 at 11:57

1 Answers1

0

This is a null pointer exception. you are initializing the Editext after calling the Asyntask. initialize the views before executing Asyntask. ie: rearrange the code:

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

            textView = findViewById(R.id.tvdata);

........

            new MyAsyncTaskgetNews().execute(url);
            }
Liya
  • 568
  • 7
  • 28
  • thanks for your suggestion, but I'm a beginner(Student) so... I don't know it is NullPointerException – Suresh N Mar 24 '18 at 06:03
  • @SureshN NullPointerException is thrown when an application attempts to use an object reference that has the null value . In your case you are instantiating the textview AFTER executing asyntask. You have to instantiate the textview BEFORE executing the asyntask. please refer my answer. that is not a suggestion , this is the answer. read it carefully – Liya Mar 26 '18 at 05:26
  • Thank you for your **ANSWER**..... Sorry I will correct my words and `THANKS` – Suresh N Mar 26 '18 at 08:32
  • 1
    @SureshN If this answer has helped you, please accept it by clicking the ✔ icon underneath the score. – Michael Dodd Mar 26 '18 at 21:43