I am new to android programming.
I have built myself some code, what I am trying to do is:
- When MainActivity is loaded, don't show a button.
- When JSON has successfully loaded, show a toggleButton
- 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();
@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.");
}
}
}
I have also tried to do :
toggleSugar.setVisibility(View.VISIBLE);
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.
first , you need to move the declaration of the ToggleButton from the onCreate method and declare it at the beginning of the class like this :
then get the refrence to the toggle button inside the onCreate method :
after that you can access it from your onPostExcute method as follows :