Search code examples
javaandroidcrash

Buttons in android : Visible, Invisible, Gone


I am working on android app and need to define custom buttons.

Initially, I am setting the button to Invisible.

I want to execute a particular method, and check for a String value. If it returns null value, then the button should be still invisible. If it returns some string value, I want to invoke the button and perform some task then.

This is what I tried, but failing.

My app is crashing when the code value returns Null, with error : "attempt to invoke virtual method"

 public String code = "";
 Button startbtn;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_retrieve_visits);

    startbtn = findViewById(R.id.videobutton);
    startbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //code
        }
    });
//more code here
}

public void parseData(String response)
{
 try {
        JSONObject json = new JSONObject(response);
        JSONArray data = json.getJSONArray("data");
        for (int i = 0; i < data.length(); i++) 
        {
            JSONObject child = data.getJSONObject(i);
            code = child.getString("code");
        }

        if(data.length()==0) ////check for empty array
            startbtn.setVisibility(View.INVISIBLE);

        else
            startbtn.setVisibility(View.VISIBLE);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

Solution

  • try the code below

     if (code != null && !code.equels("")
            {
                startbtn.setVisibility(View.VISIBLE);
            }
            else
            {
                startbtn.setVisibility(View.GONE);
            }
            startbtn.setOnClickListener(new View.OnClickListener() {
                //Required action
            }