I try to create button switch on Android for control switch ubidots.
How to get the new value real time? And i want to send value for turn on/off my switch Ubidots over android button. With condition if i click button on, it will send value 1 if i click button off it will send value 0
This is my code :
public View onCreateView(LayoutInflater inflater, ViewGroup Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_controller, container, false);
mSwitchStatus = (TextView) rootView.findViewById(R.id.statusSwitch);
ImageButton On = (ImageButton)rootView.findViewById(R.id.on);
ImageButton Off = (ImageButton)rootView.findViewById(R.id.off);
GetApiUbidots getApi = new GetApiUbidots();
getApi.execute();
if(mSwitchStatus.getText().equals("1.0"))
{
Off.setVisibility(View.INVISIBLE);
Off.setEnabled(false);
On.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(getActivity().getApplication(), "ON", Toast.LENGTH_SHORT).show();
SendApiUbidots sendApi = new SendApiUbidots();
sendApi.execute();
}
});
}
else
{
On.setVisibility(View.INVISIBLE);
On.setEnabled(false);
Off.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
Toast.makeText(getActivity().getApplication(), "OFF", Toast.LENGTH_SHORT).show();
SendApiUbidots sendApi = new SendApiUbidots();
sendApi.execute();
}
});
}
// Inflate the layout for this fragment
return rootView;
}
SendApi
public class SendApiUbidots extends AsyncTask<Integer, Void, Void>{
private final String API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private final String SWITCHID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
@Override
protected Void doInBackground(Integer... params) {
ApiClient apiClient = new ApiClient(API_KEY);
Variable switchVariable = apiClient.getVariable(SWITCHID);
switchVariable.saveValue(params[0]);
return null;
}}
GetApi
public class GetApiUbidots extends AsyncTask<Object, Object, Value[]> {
private final String API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private final String SWITCHID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
@Override
protected Value[] doInBackground(Object... params) {
ApiClient apiClient = new ApiClient(API_KEY);
Variable statusSwitch = apiClient.getVariable(SWITCHID);
Value[] variableValues = statusSwitch.getValues();
return variableValues;
}
@Override
protected void onPostExecute(Value[] variableValues) {
// Update your views here
mSwitchStatus.setText(Double.toString(variableValues[0].getValue()));
}
}
I need advice for that
Best Regards,
Redim