Home How to create a togglebutton that only appears after data has downloaded?
Reply: 0

How to create a togglebutton that only appears after data has downloaded?

user6671 Published in June 23, 2018, 5:28 pm

I am new to android programming.

I have built myself some code, what I am trying to do is:

  1. When MainActivity is loaded, don't show a button.
  2. When JSON has successfully loaded, show a toggleButton
  3. Based on the JSON data, the toggleButton is loaded as ON or OFF

I don't know how to do this so I employed the following strategy. In MainActivity.onCreate, I declared toggleButton toggleSugar.

When JSON is downloaded, I update toggleSugar to VISIBLE or INVISIBLE.

But toggleSugar is in method onCreate, whereas JSON activity is in method doInBackground in subclass GetButtonState extends ASyncClass()

So when I try to update toggleSugar from JSON success code block, it can't access toggleSugar object.

Second strategy was to declare toggleSugar under MainActivity root, before onCreate. This makes the app crash.

My code is as follows:

package com.cyberialearning.aswitch;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    private String TAG=MainActivity.class.getSimpleName();

    public void onCreate(Bundle savedInstanceState) {

       ToggleButton toggleSugar = (ToggleButton) findViewById(R.id.toggleButton);
        new GetButtonState().execute();

        final TextView statusmsg = (TextView) findViewById(R.id.textView);
        boolean dataReceived=true;

        if (dataReceived==false) {

        toggleSugar.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                } else {


    void testfunction() {
        Log.e(TAG, "testfunction");


    private class GetButtonState extends AsyncTask<Void, Void, Void> {

        final TextView statusmsg = (TextView) findViewById(R.id.textView);
        boolean dataReceived=true;          
        ProgressBar bar = (ProgressBar) findViewById(R.id.progressBar2);   
        protected void onPreExecute() {
            statusmsg.setText("Please wait. Connecting ...");
            Toast.makeText(MainActivity.this,"Trying to get JSON data",Toast.LENGTH_LONG).show();

        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            String url = "http://www.nusantara.com.my/testjson.html";
            String jsonStr=null;
            try {
                jsonStr = sh.makeServiceCall(url);
                jsonStr = jsonStr.replace("callBackFunction(", "");
            } catch (Exception e) {

                System.out.println("Cannot Communicate With "+url);
                runOnUiThread(new Runnable() { @Override public void run() {
                    AlertDialog aDialog = new AlertDialog.Builder(MainActivity.this).setMessage("It is possible that the server is down temporarily.\n\nDoes this device have internet access?").setTitle("Cannot communicate with server.")
                            .setNeutralButton("Shutdown App", new AlertDialog.OnClickListener() { public void onClick(final DialogInterface dialog, final int which) { finish(); } }).create();
                    //disable the back button
                    aDialog.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { return true; } });                        

                } });
                return null;
            jsonStr = jsonStr.replace (");","");
            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    String currentStatus = jsonObj.getString("status");
                    Log.e(TAG, "received JSON status: " + currentStatus);                                            
                } catch (final JSONException e) {

                    Log.e(TAG, "Invalid JSON format (test with curiousconcepts) : " + e.getMessage()); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show(); }});
            } else {
                Log.e(TAG, "JSON is null.");
                runOnUiThread(new Runnable() {
                    public void run() {
                                "Couldn't get json from server. Check LogCat for possible errors!",
                        statusmsg.setText("Please wait. Connecting ...");

            return null;
        protected void onPostExecute(Void result) {
            Log.e(TAG,"in onPostExecute function.");



I have also tried to do :


when the JSON has successfully downloaded, but it doesn't work.

I've also tried to call a function that is outside the subclass testFunction() to refer to toggleSugar which is outside the subclass, but this also doesn't work.

Please help.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.31448 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO