-3

i am using simple asynctask function for getting values from mysql database through json.it was working fine with emulator but if i am trying from the mobile i am getting error. like Java.lang.NullPointerExceprtion:Attempt to invke virtual metho 'java.lang.string.java.lang.stringbuilder.toString() on a null object reference.

I tried with new project but result is same. this application is not working in all the devices except emulator. can you help me on this.

My Code is -

public class MainActivity extends AppCompatActivity {

    private static final String Latest_Products7 = "Questions";
    JSONArray productsArray7 = null;

    public static final int CONNECTION_TIMEOUT7=100000;
    public static final int READ_TIMEOUT7=150000;

    HashMap<String,ArrayList<WorldPopulation>> hasmap = new HashMap<String,ArrayList<WorldPopulation>>();
    ArrayList<WorldPopulation> arraylist7 = null;



    StringBuilder result7;

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

    new AsyncLogin7().execute();
}


private class AsyncLogin7 extends AsyncTask<String, String, StringBuilder> {
    ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
    HttpURLConnection conn7;
    URL url7 = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected StringBuilder doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides

            url7 = new URL("http:/Samplesite/****/somephp.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
        try {
            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn7 = (HttpURLConnection)url7.openConnection();
            conn7.setReadTimeout(READ_TIMEOUT7);
            conn7.setConnectTimeout(CONNECTION_TIMEOUT7);
            conn7.setRequestMethod("POST");

            // setDoInput and setDoOutput method depict handling of both send and receive
            conn7.setDoInput(true);
            conn7.setDoOutput(true);


            // Append parameters to URL
            Uri.Builder builder7 = new Uri.Builder().appendQueryParameter("reg_id", "hai") ;
            String query7 = builder7.build().getEncodedQuery();

            // Open connection for sending data
            OutputStream os7 = conn7.getOutputStream();
            BufferedWriter writer7 = new BufferedWriter(new OutputStreamWriter(os7, "UTF-8"));
            writer7.write(query7);
            writer7.flush();
            writer7.close();
            os7.close();
            conn7.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();

        }

        try {


            int response_code7 = conn7.getResponseCode();

            // Check if successful connection made
            if (response_code7 == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input7 = conn7.getInputStream();
                BufferedReader reader7 = new BufferedReader(new InputStreamReader(input7));
                result7 = new StringBuilder();
                String line7;
                while ((line7 = reader7.readLine()) != null) {

                    result7.append(line7);
                }


                // Pass data to onPostExecute method

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            conn7.disconnect();
        }

        return result7;
    }

    @Override
    protected void onPostExecute(StringBuilder result7) {
        super.onPostExecute(result7);

        Log.e("dai",result7.toString());

        Toast.makeText(MainActivity.this,result7.toString(),Toast.LENGTH_LONG).show();
        pdLoading.dismiss();

           /* Intent intnt = new Intent(Checklist_activity.this,Task_main.class);
            intnt.putExtra("task",hasmap);
            startActivity(intnt);*/

        }
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Karthick Anbazhagan
  • 353
  • 2
  • 9
  • 27
  • 1
    Whats unique about this? Its an NPE `Java.lang.NullPointerExceprtion`. – ADM May 14 '18 at 10:18
  • result7 is null.Debug on the `doInBackground()` and see the response. – Koustuv Ganguly May 14 '18 at 10:18
  • 1
    If some exception occures, 'result7' won't be initialized. You have probably another exception thrown just before that nullPointer one. Check logcat if there is any other exception – egoldx May 14 '18 at 10:18
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – ADM May 14 '18 at 10:19
  • it is working fine with emulator.but not in device.in emulator i am not getting any error – Karthick Anbazhagan May 14 '18 at 10:19
  • 1
    Debug your code . No one can debug it for you . – ADM May 14 '18 at 10:21
  • Try this: Log.e("dai",MainActivity.this.result7.toString()); Toast.makeText(MainActivity.this,MainActivity.this.result7.toString(),Toast.LENGTH_LONG).show(); – aman arora May 14 '18 at 10:40

2 Answers2

0

Change

try {


            int response_code7 = conn7.getResponseCode();

            // Check if successful connection made
            if (response_code7 == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input7 = conn7.getInputStream();
                BufferedReader reader7 = new BufferedReader(new InputStreamReader(input7));
                result7 = new StringBuilder();
                String line7;
                while ((line7 = reader7.readLine()) != null) {

                    result7.append(line7);
                }


                // Pass data to onPostExecute method

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            conn7.disconnect();
        }

        return result7;

To

try {


            int response_code7 = conn7.getResponseCode();
            result7 = new StringBuilder();
            // Check if successful connection made
            if (response_code7 == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input7 = conn7.getInputStream();
                BufferedReader reader7 = new BufferedReader(new InputStreamReader(input7));
                String line7;
                while ((line7 = reader7.readLine()) != null) {

                    result7.append(line7);
                }


                // Pass data to onPostExecute method

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            conn7.disconnect();
        }

        return result7;
Koustuv Ganguly
  • 897
  • 7
  • 21
0

Try something like this

Log.e("dai",MainActivity.this.result7.toString());

    Toast.makeText(MainActivity.this,MainActivity.this.result7.toString(),Toast.LENGTH_LONG).show();

OR

@Override
protected void onPostExecute(StringBuilder result) {
    super.onPostExecute(result);

    Log.e("dai",result.toString());

    Toast.makeText(MainActivity.this,result.toString(),Toast.LENGTH_LONG).show();
    pdLoading.dismiss();

       /* Intent intnt = new Intent(Checklist_activity.this,Task_main.class);
        intnt.putExtra("task",hasmap);
        startActivity(intnt);*/

    }
}
aman arora
  • 263
  • 5
  • 16
  • @Override protected void onPostExecute(StringBuilder result) { super.onPostExecute(result); Log.e("dai",result7.toString()); Toast.makeText(MainActivity.this,result7.toString(),Toast.LENGTH_LONG).show(); pdLoading.dismiss(); /* Intent intnt = new Intent(Checklist_activity.this,Task_main.class); intnt.putExtra("task",hasmap); startActivity(intnt);*/ } } – aman arora May 14 '18 at 11:52
  • Try this: if still issue occur share snippet you have tried – aman arora May 14 '18 at 11:53