[SOLVED] Printing Ubidots data inside Android


#1

Azlan wrote,

I’m try to access Ubidot server through my ubidots account for my variable(battery level) but what received were bunch of string which I got no idea what it is.

Below is the android code snippet:

public class ApiUbidots extends AsyncTask<Integer, Void, Value[]> {
        private final String API_KEY = "xxxxxxxx";
        private final String VARIABLE_ID = "57047de57625420b17c72ad1";

        @Override
        protected Value[] doInBackground(Integer... params) {
            ApiClient apiClient = new ApiClient(API_KEY);
            Variable batteryLevel = apiClient.getVariable(VARIABLE_ID);
            Value[] variableValues = batteryLevel.getValues();

            return variableValues;
        }
        @Override
        protected void onProgressUpdate(Void... params) {

            mBatteryLevel.setText("Waiting for the data");
        }


        @Override
        protected void onPostExecute(Value[] variableValues) {
            // Update your views here
            mBatteryLevel.setText(variableValues + "%");
        }
    }

and the sample result:

[Lcom.ubidots.Value;@123da9c2%

Please advise

Rgds,

Azlan


#2

Hi Azlan,

You’re getting that String [Lcom.ubidots.Value;@123da9c2% because you’re actually printing the Array object not the values contained on it. The Java toString() method for arrays prints the class name (i.e. com.ubidots.Value) and a HashCode (i.e. 123da9c2).

As you may want to print the last value, you could do this in your onPostExecute() method.

@Override
protected void onPostExecute(Value[] variableValues) {
    // Update your views here
    mBatteryLevel.setText(variableValues[0].getValue() + "%");
}

Notice the [0] after variableValues, this is how you access an specific condition in your array.

Hope this help you

Regards


#3

i am working on the same stuff… i actually was able to reach till mBatteryLevel.setText(variableValues[0]); but i was getting error… so i just wanted to ask why we are supposed to concatenate “%” with value as it removes the error.


#4

Nice question @shahzadb13,

When you concatenate a Double value (variablesValues[0]) with a String ("%"), Java will create a new String object with those variables concatenated. In the case that you doesn’t concatenate with “%”, you’re sending a Double value alone to the setText() method, and that method doesn’t receive a Double but a String.

You can fix that by sending setText() the value converted to String, that is:

mBatteryLevel.setText(Double.toString(variablesValues[0].getValue()))

Important: I’ve edited both answers and added the .getValue() method in the variableValues[0] object.