0

I am trying to close app if there is no Internet Connection Available. I know there is a question which I already exist but I did exactly same and it seems that my app works fine before registration but after I edit text in nickname field it throws null pointer error, if I do this on opening again after editing text Here take a look :

I have registered on my app and in drawer I have nickname which is editable so I did like this :

pname = (EditText) findViewById(R.id.pname);

        profimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show();
            }
        });

        pname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pname.setInputType(0x0000006);
                pname.setCursorVisible(true);

            }
        });
        pname.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    pname.setCursorVisible(false);
                }
                else{
                    pname.setCursorVisible(false);
                }
            }
        });

        pname.setOnEditorActionListener(new EditText.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event!=null && event.getKeyCode() != KeyEvent.KEYCODE_ENTER || actionId != EditorInfo.IME_ACTION_DONE ) {
                    return false;
                }
                else if(actionId==EditorInfo.IME_ACTION_DONE || event==null || event.getKeyCode() == KeyEvent.KEYCODE_ENTER){

                    pname.setCursorVisible(false);
                    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(pname.getWindowToken(), 0);
                    return false;
                }
                return false;
            }
        });

 pname.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                sp.edit().remove("personName").apply();
                name= s.toString();
                sp.edit().putString("personName",name).apply();
                try {
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("nickname", name));
                    params.add(new BasicNameValuePair("mobile", callNo));
                    JSONObject json = jsonParser.makeHttpRequest(Config.URL_Info, "POST",
                            params);
                    int success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        Log.d("Status Updated", json.getString(TAG_MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
        if(path1) {
            String value = sp.getString("personName", name);
            pname.setText(value);
        }

The error is where I am setting the text. I am checking for connection availability at the starting after setcontentview(layout) and the function is just after onCreate method.

Error Log :

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONObject.getInt(java.lang.String)' on a null object reference                                                                            
                                                                             at .afterTextChanged(PlaceCallActivity.java:206)
                                                                             at android.widget.TextView.sendAfterTextChanged(TextView.java:7942)
                                                                             at android.widget.TextView.setText(TextView.java:4079)
                                                                             at android.widget.TextView.setText(TextView.java:3928)
                                                                             at
W4R10CK
  • 5,502
  • 2
  • 19
  • 30
SamH67
  • 319
  • 1
  • 4
  • 14

4 Answers4

2

It is because jsonParser.makeHttpRequest(Config.URL_Info, "POST",params); is returning null!

hence,

int success = json.getInt(TAG_SUCCESS);

is giving java.lang.NullPointerException:

Tulsi
  • 719
  • 7
  • 15
  • More code added take a look and yes but how to resolve it :( – SamH67 Jan 03 '17 at 07:55
  • If it gives you null it means no internet connection hence you can close the application but do not json.getInt(TAG_SUCCESS) as json is null! – Tulsi Jan 03 '17 at 07:58
1

Looks like your json object is null

Check if it is not null before using it

if(json != null){
   int success = json.getInt(TAG_SUCCESS);
}
else{
   Log.d("JSON", "NULL");
}
Vygintas B
  • 1,624
  • 13
  • 31
  • Thanks it Worked these small things irritate me. I'll accept your answer in 3 minutes :) – SamH67 Jan 03 '17 at 07:59
  • Thanks for helping :) – SamH67 Jan 03 '17 at 08:02
  • Happy to help :) Check this to get more insight of this problem [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Vygintas B Jan 03 '17 at 08:03
1

you need to check whether json variable is null or not

only if json variable is not null proceed the further steps

 @Override
        public void afterTextChanged(Editable s) {
            sp.edit().remove("personName").apply();
            name= s.toString();
            sp.edit().putString("personName",name).apply();
            try {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("nickname", name));
                params.add(new BasicNameValuePair("mobile", callNo));
                JSONObject json = jsonParser.makeHttpRequest(Config.URL_Info, "POST",
                        params);
                if(json!=null){
                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("Status Updated", json.getString(TAG_MESSAGE));
                }
              }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    });
Jayanth
  • 5,954
  • 3
  • 21
  • 38
1

you should check whether network is available before making a call to httprequest

try this;

public static boolean isNetworkAvailable(Activity activity) {
    int[] networkTypes = {ConnectivityManager.TYPE_MOBILE,
            ConnectivityManager.TYPE_WIFI};
    try {
        ConnectivityManager connectivityManager =
                (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        for (int networkType : networkTypes) {
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            if (activeNetworkInfo != null &&
                    activeNetworkInfo.getType() == networkType)
                return true;
        }
    } catch (Exception e) {
        return false;
    }
    return false;
}

check internet before:

if(isNetworkAvailable(Mainactivity.this)
    JSONObject json = jParser.makeHttpRequest(Config.URL_Info, "POST",
                        params);

                try {
                    // Checking for SUCCESS TAG
                    if(json!=null){
                    Log.d("RESPONSE ", json.toString());
                    int success = json.getInt(TAG_SUCCESS);

                    if (success == 1) {

                    } else {

                    }
                }else{


                } catch (JSONException e) {
                    e.printStackTrace();
                }
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
  • Yeah this also right but json check there will do the working. Thanks everyone is posting correct answer :)o – SamH67 Jan 03 '17 at 08:09
  • if there is no network connection...there is no point to call httprequest..though – rafsanahmad007 Jan 03 '17 at 08:14
  • Yeah I know but there is no internet connection so no call will be made though your answer looks more appropriate i'll use yours but I have already accepted an answer. Thanks alot for better approach :) – SamH67 Jan 03 '17 at 08:16
  • Yeah I got your solution using your answer only. Thanks bud :) – SamH67 Jan 03 '17 at 08:33
  • you can still upvate and accept my answer if it fullfills your requirements..thnkx – rafsanahmad007 Jan 03 '17 at 08:34
  • Sorry I can't accept your answer because I already have I have upvoted your answer :) – SamH67 Jan 03 '17 at 08:36