0

I am making the application in android studio, in my application i add the feature, if the user click on button second time, then the button is disable and save the state of button in sharedprefernce and if the user closed the app and again open the app then the save button state are shown(if the button is disabled then the disable button is show, else shows enable state ). I put many codes of sharedprefences in my code, but every time the null object reference occurs. My code is given below and I put the shared preferences code on this button but how?

java:

 button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                counrClick = counrClick + 1;
                if (counrClick == 1) {

                    downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                    Uri uri = Uri.parse("Url");
                    DownloadManager.Request request = new DownloadManager.Request(uri);
                    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
                    request.setAllowedOverRoaming(false);
                    request.setTitle("" + "" + "");
                    request.setDescription("Downloading " + "" + "");
                    request.setVisibleInDownloadsUi(true);
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    Long reference = downloadManager.enqueue(request);
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/" + "filename");
                    refid = downloadManager.enqueue(request);
                    Log.e("OUT", "" + refid);
                    if (counrClick == 2) {
                        button.setEnabled(false);

                    }


                }
            }

        });
piet.t
  • 11,718
  • 21
  • 43
  • 52
  • can you post sharedpref code – akshay_shahane Jun 27 '19 at 07:20
  • 1
    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) – Vladyslav Matviienko Jun 27 '19 at 07:25
  • @VladyslavMatviienko, how can you say duplicate of the link provided you above? – Hari N Jha Jun 27 '19 at 07:35
  • I cannot see anything related to shared and also where have you used logic to check the condition and make the button enable or disable after the app is opened? It would be good to give you proper solution if you provide the related code snippet in detail. – Hari N Jha Jun 27 '19 at 07:37
  • SharedPreferences.Editor editor; SharedPreferences preferences; private static final String ADD = "ADD_KEY"; preferences = getSharedPreferences(ADD, Context.MODE_PRIVATE); SharedPreferences saveFavPrefs = getSharedPreferences(mydata, MODE_PRIVATE);; button.setClickable(saveFavPrefs.getBoolean("isclick", true)); – Hassan Ali Mughal Jun 27 '19 at 07:58
  • button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { counrClick = counrClick + 1; if (counrClick == 1) { //code// if (counrClick == 2) { button.setEnabled(false); SaveState(button.isEnable()); } – Hassan Ali Mughal Jun 27 '19 at 08:04
  • next step private void SaveState(boolean isChecked) { editor = preferences.edit(); editor.putBoolean(ADD, isChecked); editor.commit(); – Hassan Ali Mughal Jun 27 '19 at 08:05
  • lst step public boolean GetState() { return preferences.getBoolean(ADD, false ); – Hassan Ali Mughal Jun 27 '19 at 08:05
  • kindly give the sutable answer of this problm – Hassan Ali Mughal Jun 27 '19 at 08:05
  • @HassanAliMughal I think you are using impossible condition you said `if (counrClick == 1) { if(counrClick ==2)}}` second condition will not execute because you put it inside `if(counrClick ==1)` – Abdulkadir Ugas Jun 27 '19 at 08:19
  • 1
    @HariNJha by reading the question of course: `but every time the null object reference occurs.` – Vladyslav Matviienko Jun 27 '19 at 09:17

3 Answers3

1

Please refer the code below. and please remember you can use preference name ("MY_PREF") and key name ("DOWNLOAD_BUTTON_STATUS") to alter preference anywhere else in your application. You can even create a separate class for control all preferences in your application.

 private SharedPreferences sharedPreferences;
private Button btn_download_one, btn_download_two, btn_download_three, btn_download_four;
private final String DOWNLOAD_BUTTON_STATUS_KEY_ONE = "DOWNLOAD_BUTTON_STATUS_ONE";
private final String DOWNLOAD_BUTTON_STATUS_KEY_TWO = "DOWNLOAD_BUTTON_STATUS_TWO";
private final String DOWNLOAD_BUTTON_STATUS_KEY_THREE = "DOWNLOAD_BUTTON_STATUS_THREE";
private final String DOWNLOAD_BUTTON_STATUS_KEY_FOUR = "DOWNLOAD_BUTTON_STATUS_FOUR";
private int clickCountOne = 0, clickCountTwo = 0, clickCountThree = 0, clickCountFour = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn_download_one = findViewById(R.id.button1);
    btn_download_two = findViewById(R.id.button2);
    btn_download_three = findViewById(R.id.button3);
    btn_download_four = findViewById(R.id.button4);
    sharedPreferences = getSharedPreferences("MY_PREF", 0);
    btn_download_one.setEnabled(getDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_ONE));
    btn_download_two.setEnabled(getDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_TWO));
    btn_download_three.setEnabled(getDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_THREE));
    btn_download_four.setEnabled(getDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_FOUR));


    btn_download_one.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //... some code
            clickCountOne++;
            if (clickCountOne == 2)
                changeDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_ONE, false);

        }
    });
    btn_download_two.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //... some code
            clickCountTwo++;
            if (clickCountTwo == 2)
                changeDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_TWO, false);

        }
    });
    btn_download_three.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //... some code
            clickCountThree++;
            if (clickCountThree == 2)
                changeDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_THREE, false);

        }
    });
    btn_download_four.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //... some code
            clickCountFour++;
            if (clickCountFour == 2)
                changeDownloadButtonStatusPref(DOWNLOAD_BUTTON_STATUS_KEY_FOUR, false);

        }
    });

}

private void changeDownloadButtonStatusPref(String key, boolean status) {
    sharedPreferences.edit().putBoolean(key, status).apply();
    switch (key) {
        case DOWNLOAD_BUTTON_STATUS_KEY_ONE:
            btn_download_one.setEnabled(status);
            clickCountOne = 0;
            break;
        case DOWNLOAD_BUTTON_STATUS_KEY_TWO:
            btn_download_two.setEnabled(status);
            clickCountTwo = 0;
            break;
        case DOWNLOAD_BUTTON_STATUS_KEY_THREE:
            btn_download_three.setEnabled(status);
            clickCountThree = 0;
            break;
        case DOWNLOAD_BUTTON_STATUS_KEY_FOUR:
            btn_download_four.setEnabled(status);
            clickCountFour = 0;
            break;
    }
}

private boolean getDownloadButtonStatusPref(String key) {
    return sharedPreferences.getBoolean(key, true);
}
Geo
  • 746
  • 6
  • 14
  • i phase one more problem i use your code in my app but only on one button these code are working but not on mutliple buttton. when i put 4 buttons in app if i click on one button and clsed the app when i open the app then button state are apply on 4 button not on one,want when i open the ap then only one button is disble not next 3 buttons – Hassan Ali Mughal Jun 28 '19 at 11:37
  • Check now, and you can use the same approach to support more buttons. If you put some time into reviewing and refactoring the code, you can reduce boilerplate code. – Geo Jul 01 '19 at 05:10
0

//Add this code on button click

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.edit().putString("enabled", "").apply();

//Add this code in OnCreate/OncreateView Method

  String statusLocked1 =  prefs.getString("enabled","");
    if(statusLocked1.equals("enabled")){
        //enable the button 
    }else{
        //disbale the button 
    }
NikhilReddy
  • 6,904
  • 11
  • 38
  • 58
  • The error is Occured Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference – Hassan Ali Mughal just now – Hassan Ali Mughal Jun 27 '19 at 09:36
0

Try this it will disable button next time you run your activity if it was previously clicked twice;

Button button;
SharedPreferences preferences;
boolean firstclick = true;

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

    // SharePrefs
    preferences = getSharedPreferences("yourprefsname", 0);
    firstclick = preferences.getBoolean("countclick", false);
    button = findViewById(R.id.yourbutton);

    //disables if it is clicked twice 
    if (!firstclick){
        button.setEnabled(false);
    }


    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (firstclick) {

                downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                Uri uri = Uri.parse("Url");
                DownloadManager.Request request = new DownloadManager.Request(uri);
                request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
                request.setAllowedOverRoaming(false);
                request.setTitle("" + "" + "");
                request.setDescription("Downloading " + "" + "");
                request.setVisibleInDownloadsUi(true);
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                Long reference = downloadManager.enqueue(request);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/" + "filename");
                refid = downloadManager.enqueue(request);
                Log.e("OUT", "" + refid);
                else{
                    //edit prefs                   
             preferences.edit().putBoolean("countclick",firstclick).apply();
                    button.setEnabled(false);

                }


            }
        }
    });
}
Kishan Thakkar
  • 429
  • 4
  • 11
  • The error is Occured Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference – Hassan Ali Mughal Jun 27 '19 at 09:23
  • The above code is not working it not save the buton state on application closed – Hassan Ali Mughal Jun 28 '19 at 11:30
  • i phase one more problem when i put 4 buttons in app if i click on one button and clsed the app when i open the app then button state are apply on 4 button not on one,want when i open the ap then only one button is disble not next 3 buttons – Hassan Ali Mughal Jun 28 '19 at 11:31