如何创建仅在下载数据后出现的togglebutton?

时间:2018-02-12 08:54:16

标签: java android json class

我是Android编程的新手。

我已经为自己构建了一些代码,我想要做的是:

  1. 加载MainActivity时,请勿显示按钮。
  2. 当JSON成功加载时,显示toggleButton
  3. 根据JSON数据,toggleButton加载为ON或OFF
  4. 我不知道怎么做,所以我采用了以下策略。 在MainActivity.onCreate中,我声明了toggleButton toggleSugar

    下载JSON时,我将 toggleSugar 更新为VISIBLE或INVISIBLE。

    但是 toggleSugar 在方法onCreate中,而JSON活动在方法doInBackground中的子类中GetButtonState扩展ASyncClass()

    因此,当我尝试从JSON成功代码块更新 toggleSugar 时,它无法访问 toggleSugar 对象。

    第二个策略是在onCreate之前在MainActivity root下声明 toggleSugar 。这会让应用程序崩溃。

    我的代码如下:

    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();
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
           ToggleButton toggleSugar = (ToggleButton) findViewById(R.id.toggleButton);
            toggleSugar.setVisibility(View.INVISIBLE);
            new GetButtonState().execute();
    
            final TextView statusmsg = (TextView) findViewById(R.id.textView);
            boolean dataReceived=true;
    
            if (dataReceived==false) {
                toggleSugar.setVisibility(View.INVISIBLE);
            }
    
            toggleSugar.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        statusmsg.setText("ButtonisOn");
                    } else {
                        statusmsg.setText("ButtonisOff");
                        ;
                    }
                }
            });
    
        }
    
        void testfunction() {
            Log.e(TAG, "testfunction");
            toggleSugar.setVisibility(View.VISIBLE);
    
        }
    
        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);   
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                statusmsg.setText("Please wait. Connecting ...");
                Toast.makeText(MainActivity.this,"Trying to get JSON data",Toast.LENGTH_LONG).show();
    
            }
            @Override
            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; } });                        
                        dataReceived=false;    
    
                    } });
                    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);                                            
                        testfunction();
                    } 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 {
                 MESSAGE IS NULL : POSSIBLE SERVER PROBLEM - hosting
                    Log.e(TAG, "JSON is null.");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Couldn't get json from server. Check LogCat for possible errors!",
                                    Toast.LENGTH_LONG).show();
                            dataReceived=false;
                            statusmsg.setText("Please wait. Connecting ...");
    
    
                        }
                    });
                }
                return null;
            }
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                Log.e(TAG,"in onPostExecute function.");
    
            }
    
        }
    }
    

    我也尝试过:

    toggleSugar.setVisibility(View.VISIBLE);
    

    当JSON成功下载时,但它不起作用。

    我还尝试调用子类 testFunction()之外的函数来引用子类之外的 toggleSugar ,但这也没有工作

    请帮忙。

1 个答案:

答案 0 :(得分:0)

首先,您需要从onCreate方法移动ToggleButton的声明,并在类的开头声明它,如下所示:

public class MainActivity extends AppCompatActivity {

ToggleButton  toggleSugar ;

//......

}

然后获取onCreate方法内的切换按钮的参考:

toggleSugar = (ToggleButton) findViewById(R.id.toggleButton);

之后,您可以通过onPostExcute方法访问它,如下所示:

protected void onPostExecute(Void result) {

            super.onPostExecute(result);

            toggleSugar.setVisibility(View.VISIBLE);
        }