[SOLVED] Cant Controlling Switch from android

i m not able to on/off my switch through android app.
please help me for it.

this is my activity_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <Switch
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="fill_horizontal"
        android:padding="30dp"
        android:id="@+id/switch2"
        android:checked="false"
        android:textOn="On"
        android:textOff="Off"
        android:onClick="onClick"
        android:text="Light_2"
        android:layout_below="@+id/switch1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Switch
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="fill_horizontal"
        android:padding="30dp"
        android:id="@+id/switch1"
        android:checked="false"
        android:textOn="On"
        android:textOff="Off"
        android:text="Light_1"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:onClick="onClick" />

    <Switch
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="fill_horizontal"
        android:padding="30dp"
        android:id="@+id/switch3"
        android:layout_below="@+id/switch2"
        android:layout_centerHorizontal="true"
        android:checked="false"
        android:textOn="On"
        android:textOff="Off"
        android:onClick="onClick"
        android:text="Light_3" />

</RelativeLayout>

this is MainActivity.java

package com.ubidotstrial;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Switch;

import com.ubidots.ApiClient;
import com.ubidots.Variable;

public class MainActivity extends AppCompatActivity
{
    public Switch switch1, switch2, switch3;

    public final String API_KEY ="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    public final String UBIDOTS_ID_FOR_LIGHT1 = "xxxxxxxxxxxxxxxxxxxxxxxx";
    public final String UBIDOTS_ID_FOR_LIGHT2 = "xxxxxxxxxxxxxxxxxxxxxxxx";
    public final String UBIDOTS_ID_FOR_LIGHT3 = "xxxxxxxxxxxxxxxxxxxxxxxx";

    public int mode;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        switch1 = (Switch) findViewById(R.id.switch1);
        switch2 = (Switch) findViewById(R.id.switch2);
        switch3 = (Switch) findViewById(R.id.switch3);
    }

    public void onClick(View v)
    {
        Switch s = (Switch)v;

        if(s.isChecked())
            mode = 1;
        else
            mode = 0;

        ApiClient apiClient = new ApiClient(API_KEY);
        switch (v.getId())
        {
            case R.id.switch1 :
                Variable light1 = apiClient.getVariable(UBIDOTS_ID_FOR_LIGHT1);
                light1.saveValue(mode);
                break;

            case R.id.switch2 :
                Variable light2 = apiClient.getVariable(UBIDOTS_ID_FOR_LIGHT2);
                light2.saveValue(mode);
                break;

            case R.id.switch3 :
                Variable light3 = apiClient.getVariable(UBIDOTS_ID_FOR_LIGHT3);
                light3.saveValue(mode);
                break;
        }
    }
}

Greetings dear user,

We advice you to learn how to send data using our standard library following the examples provided here, once you get how to do it adapt the methods to your certain app.

Regards

glad for response

i followed your link but not able to find bug in this shared code.

as compared to it…same way i m creating apiClient variable and saving variable value as per which switch is clicked in android ui.

can you please help me to find my bug.

when i clicked on any switch of ui app unfortunately stops.

following is error code.

06-21 12:13:43.816 1733-1733/? E/AndroidRuntime: FATAL EXCEPTION: main
                                             Process: com.ubidotstrial, PID: 1733
                                             java.lang.IllegalStateException: Could not execute method for android:onClick
                                                 at android.view.View$DeclaredOnClickListener.onClick(View.java:4764)
                                                 at android.view.View.performClick(View.java:5721)
                                                 at android.widget.TextView.performClick(TextView.java:10931)
                                                 at android.widget.CompoundButton.performClick(CompoundButton.java:125)
                                                 at android.view.View$PerformClick.run(View.java:22620)
                                                 at android.os.Handler.handleCallback(Handler.java:739)
                                                 at android.os.Handler.dispatchMessage(Handler.java:95)
                                                 at android.os.Looper.loop(Looper.java:148)
                                                 at android.app.ActivityThread.main(ActivityThread.java:7409)
                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                              Caused by: java.lang.reflect.InvocationTargetException
                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                 at android.view.View$DeclaredOnClickListener.onClick(View.java:4759)
                                                 at android.view.View.performClick(View.java:5721) 
                                                 at android.widget.TextView.performClick(TextView.java:10931) 
                                                 at android.widget.CompoundButton.performClick(CompoundButton.java:125) 
                                                 at android.view.View$PerformClick.run(View.java:22620) 
                                                 at android.os.Handler.handleCallback(Handler.java:739) 
                                                 at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                 at android.os.Looper.loop(Looper.java:148) 
                                                 at android.app.ActivityThread.main(ActivityThread.java:7409) 
                                                 at java.lang.reflect.Method.invoke(Native Method) 
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
                                              Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.Map.get(java.lang.Object)' on a null object reference
                                                 at com.ubidots.ServerBridge.recieveToken(ServerBridge.java:72)
                                                 at com.ubidots.ServerBridge.initialize(ServerBridge.java:67)
                                                 at com.ubidots.ServerBridge.<init>(ServerBridge.java:54)
                                                 at com.ubidots.ServerBridge.<init>(ServerBridge.java:43)
                                                 at com.ubidots.ApiClient.<init>(ApiClient.java:16)
                                                 at com.ubidotstrial.MainActivity.onClick(MainActivity.java:44)
                                                 at java.lang.reflect.Method.invoke(Native Method) 
                                                 at android.view.View$DeclaredOnClickListener.onClick(View.java:4759) 
                                                 at android.view.View.performClick(View.java:5721) 
                                                 at android.widget.TextView.performClick(TextView.java:10931) 
                                                 at android.widget.CompoundButton.performClick(CompoundButton.java:125) 
                                                 at android.view.View$PerformClick.run(View.java:22620) 
                                                 at android.os.Handler.handleCallback(Handler.java:739) 
                                                 at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                 at android.os.Looper.loop(Looper.java:148) 
                                                 at android.app.ActivityThread.main(ActivityThread.java:7409) 
                                                 at java.lang.reflect.Method.invoke(Native Method) 
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 

plzz help me to find my bug.
waiting for response…thanks in advance…

Greetings dear user,

As I advised you previously, you should learn to send properly one value, without any thread or virtual switch, only an infinite loop that repeats every x seconds, for that you can follow one of our tutorials. Once you learn how to use properly the library, you may include it inside your code.

Unfortunately we solve customized code issues as a service only for users with a business license, if you have a business license please provide us your userid through the direct support channels to give you assistance faster. Anyway, I’ll notify to our development to give you assistance here too but keep in mind that we can help you depending on the availability of our engineers, we try our best for all our users and that is why we have to direct properly our resources to assist you properly.

I’ll ask to one of our engineers from our team will take a look to your code to give you some hints to solve your issue as soon as possible.

Regards

For what I see in your code is that you’re creating the instance in your onClick method and immediately calling the saveValue method of it.

This could be causing the NullPointerException as the actions inside the getVariable method are not yet finished (is an HTTP request, so it’s async).

What I recommend you is to make the APIClient and the Variables a member of the class instead of being a member of the method and initialize them on the start. That way, when your software executes the onClick method you will be sure that you now have a Variable instance.

Thank You so much Sir…glad to receive help.
I am getting your point…i tried that way…

changes in MainActivity.java :

package com.ubidotstrial;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Switch;

import com.ubidots.ApiClient;
import com.ubidots.DataSource;
import com.ubidots.Variable;

public class MainActivity extends AppCompatActivity
{
    public Switch switch1, switch2, switch3;
    public ApiClient apiClient;
    public Variable light1, light2, light3;

    public final String API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    public final String UBIDOTS_ID_FOR_LIGHT1 = "xxxxxxxxxxxxxxxxxxxxxxxx";
    public final String UBIDOTS_ID_FOR_LIGHT2 = "xxxxxxxxxxxxxxxxxxxxxxxx";
    public final String UBIDOTS_ID_FOR_LIGHT3 = "xxxxxxxxxxxxxxxxxxxxxxxx";

    public int mode;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        switch1 = (Switch) findViewById(R.id.switch1);
        switch2 = (Switch) findViewById(R.id.switch2);
        switch3 = (Switch) findViewById(R.id.switch3);

        apiClient = new ApiClient(API_KEY);
        light1 = apiClient.getVariable(UBIDOTS_ID_FOR_LIGHT1);
        light2 = apiClient.getVariable(UBIDOTS_ID_FOR_LIGHT2);
        light3 = apiClient.getVariable(UBIDOTS_ID_FOR_LIGHT3);
    }

    public void onClick(View v)
    {
        Switch s = (Switch)v;

        if(s.isChecked())
            mode = 1;
        else
            mode = 0;

        switch (v.getId())
        {
            case R.id.switch1 :
                light1.saveValue(mode);
                break;

            case R.id.switch2 :
                light2.saveValue(mode);
                break;

            case R.id.switch3 :
                light3.saveValue(mode);
                break;
        }
    }
}

still this is not working sir…same error repeats in oncreate…even before app starts it crash…
i will wait for response again…truly in need of your help…thanks in advance…

You should create an AsyncTask to make all the calls to the API as said in the tutorial that @jotathebest sent you. That’s why your application is crashing, Android does not permit to make an HTTP call in the main thread.

Thank you so much for help, I followed that tutorial.

Sorry but still I am not able to solve.

doInBackGround() isn’t completing its task for initializing Variables.

Following is my Updated MainActivity.java Code.

package com.ubidotstrial;

    import android.os.AsyncTask;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Switch;

    import com.ubidots.ApiClient;
    import com.ubidots.DataSource;
    import com.ubidots.Variable;

    public class MainActivity extends AppCompatActivity
    {
        public Variable light1, light2, light3;
        public Switch switch1, switch2, switch3;
        public int mode;

        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            switch1 = (Switch) findViewById(R.id.switch1);
            switch2 = (Switch) findViewById(R.id.switch2);
            switch3 = (Switch) findViewById(R.id.switch3);

            Log.v("conn", "starts");
            new ConnectUbidots().execute();
            Log.v("conn", "returned");
        }

        public void onClick(View v)
        {
            Log.v("onclick", "starts");
            Switch s = (Switch)v;

            if(s.isChecked())
                mode = 1;
            else
                mode = 0;

            switch (v.getId())
            {
                case R.id.switch1 :
                    Log.v("on", "light1");
                    light1.saveValue(mode);
                    break;

                case R.id.switch2 :
                    light2.saveValue(mode);
                    break;

                case R.id.switch3 :
                    light3.saveValue(mode);
                    break;
            }
        }

        class ConnectUbidots extends AsyncTask
        {
            private final String API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
            private final String UBIDOTS_ID_FOR_LIGHT1 = "xxxxxxxxxxxxxxxxxxxxxxxx";
            private final String UBIDOTS_ID_FOR_LIGHT2 = "xxxxxxxxxxxxxxxxxxxxxxxx";
            private final String UBIDOTS_ID_FOR_LIGHT3 = "xxxxxxxxxxxxxxxxxxxxxxxx";

            @Override
            protected Object doInBackground(Object[] params)
            {
                Log.v("doInBackground", "starts");

                ApiClient apiClient = new ApiClient(API_KEY);
                light1 = apiClient.getVariable(UBIDOTS_ID_FOR_LIGHT1);
                light2 = apiClient.getVariable(UBIDOTS_ID_FOR_LIGHT2);
                light3 = apiClient.getVariable(UBIDOTS_ID_FOR_LIGHT3);

                Log.v("doInBackground", "completed");

                return null;
            }
        }
    }           

Same error on onClick()…as execution doesn’t reach to Log.v("doInBackground", "completed");

You’re having that problem because of the async nature of the HTTP Requests, you’re trying to call the saveValues method on a NULL instance. Those variables doesn’t have yet the Variable instance.

I just made a simple fix in the UI, add an indeterminate ProgressBar and show the layout that have the switches when the load has been completed.

Java file:

package com.ubidotstrial;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Switch;

import com.ubidots.ApiClient;
import com.ubidots.Variable;

public class MainActivity extends AppCompatActivity
{
    public Variable light1, light2, light3;
    public Switch switch1, switch2, switch3;
    public int mode;

    // Getting the views from the layout
    public RelativeLayout mSwitchLayout;
    public ProgressBar mProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Instantiate them
        mSwitchLayout = (RelativeLayout) findViewById(R.id.switch_layout);
        mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);

        switch1 = (Switch) findViewById(R.id.switch1);
        switch2 = (Switch) findViewById(R.id.switch2);
        switch3 = (Switch) findViewById(R.id.switch3);

        Log.v("conn", "starts");
        new ConnectUbidots().execute();
        Log.v("conn", "returned");
    }

    public void onClick(View v)
    {
        Log.v("onclick", "starts");
        Switch s = (Switch)v;

        if(s.isChecked())
            mode = 1;
        else
            mode = 0;

        switch (v.getId())
        {
            case R.id.switch1 :
                Log.v("on", "light1");
                light1.saveValue(mode);
                break;

            case R.id.switch2 :
                light2.saveValue(mode);
                break;

            case R.id.switch3 :
                light3.saveValue(mode);
                break;
        }
    }

    class ConnectUbidots extends AsyncTask
    {
        private final String API_KEY = "XXXXXX";
        private final String UBIDOTS_ID_FOR_LIGHT1 = "XXXXX";
        private final String UBIDOTS_ID_FOR_LIGHT2 = "XXXXX";
        private final String UBIDOTS_ID_FOR_LIGHT3 = "XXXXX";

        @Override
        protected Object doInBackground(Object[] params)
        {
            Log.v("doInBackground", "starts");

            ApiClient apiClient = new ApiClient(API_KEY);
            light1 = apiClient.getVariable(UBIDOTS_ID_FOR_LIGHT1);
            light2 = apiClient.getVariable(UBIDOTS_ID_FOR_LIGHT2);
            light3 = apiClient.getVariable(UBIDOTS_ID_FOR_LIGHT3);

            Log.v("doInBackground", "completed");

            return null;
        }

        /**
         * When the doInBackground finishes executing
         * we will change the visibility of the views.
         */
        @Override
        protected void onPostExecute(Object o) {
            mSwitchLayout.setVisibility(View.VISIBLE);
            mProgressBar.setVisibility(View.GONE);
        }
    }
}

XML Layout file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    tools:context=".MainActivity">

    <ProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <RelativeLayout
        android:id="@+id/switch_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="invisible">
        <Switch
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="fill_horizontal"
            android:padding="30dp"
            android:id="@+id/switch2"
            android:checked="false"
            android:textOn="On"
            android:textOff="Off"
            android:onClick="onClick"
            android:text="Light_2"
            android:layout_below="@+id/switch1"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />

        <Switch
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="fill_horizontal"
            android:padding="30dp"
            android:id="@+id/switch1"
            android:checked="false"
            android:textOn="On"
            android:textOff="Off"
            android:text="Light_1"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:onClick="onClick" />

        <Switch
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="fill_horizontal"
            android:padding="30dp"
            android:id="@+id/switch3"
            android:layout_below="@+id/switch2"
            android:layout_centerHorizontal="true"
            android:checked="false"
            android:textOn="On"
            android:textOff="Off"
            android:onClick="onClick"
            android:text="Light_3" />
    </RelativeLayout>

</RelativeLayout>
1 Like

Thank youuu so much sirr…glad for response.

But Sir,
problem remains same…
Continuously that progressbar is going on…doInBackground isnt getting over any long.
I wait for more than 10-15 minutes.

Hope for help…will wait for response…

Have you checked that your application have permissions to access to the network?

Yeah sure sir…internet permission is there in my manifest file…and net is enable too.

I’ve made the test and is working OK.

Please check your settings, that’s the most I can help you unfortunately.

Thanks for this answer, got the same prob too