Example usage for org.json JSONObject getJSONArray

List of usage examples for org.json JSONObject getJSONArray

Introduction

In this page you can find the example usage for org.json JSONObject getJSONArray.

Prototype

public JSONArray getJSONArray(String key) throws JSONException 

Source Link

Document

Get the JSONArray value associated with a key.

Usage

From source file:com.example.kylelehman.sunshine.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.//from   w w  w.ja  v  a 2  s . c  o m
 */
private void getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationSetting)
        throws JSONException {

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";
    final String OWM_COORD_LAT = "lat";
    final String OWM_COORD_LONG = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_DATETIME = "dt";
    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    JSONObject forecastJson = new JSONObject(forecastJsonStr);
    JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

    JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
    String cityName = cityJson.getString(OWM_CITY_NAME);
    JSONObject coordJSON = cityJson.getJSONObject(OWM_COORD);
    double cityLatitude = coordJSON.getLong(OWM_COORD_LAT);
    double cityLongitude = coordJSON.getLong(OWM_COORD_LONG);

    Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude);

    // Insert the location into the database.
    long locationID = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

    // Get and insert the new weather information into the database
    Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

    for (int i = 0; i < weatherArray.length(); i++) {
        // These are the values that will be collected.

        long dateTime;
        double pressure;
        int humidity;
        double windSpeed;
        double windDirection;

        double high;
        double low;

        String description;
        int weatherId;

        // Get the JSON object representing the day
        JSONObject dayForecast = weatherArray.getJSONObject(i);

        // The date/time is returned as a long.  We need to convert that
        // into something human-readable, since most people won't read "1400356800" as
        // "this saturday".
        dateTime = dayForecast.getLong(OWM_DATETIME);

        pressure = dayForecast.getDouble(OWM_PRESSURE);
        humidity = dayForecast.getInt(OWM_HUMIDITY);
        windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
        windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

        // Description is in a child array called "weather", which is 1 element long.
        // That element also contains a weather code.
        JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
        description = weatherObject.getString(OWM_DESCRIPTION);
        weatherId = weatherObject.getInt(OWM_WEATHER_ID);

        // Temperatures are in a child object called "temp".  Try not to name variables
        // "temp" when working with temperature.  It confuses everybody.
        JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
        high = temperatureObject.getDouble(OWM_MAX);
        low = temperatureObject.getDouble(OWM_MIN);

        ContentValues weatherValues = new ContentValues();

        weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationID);
        weatherValues.put(WeatherEntry.COLUMN_DATETEXT,
                WeatherContract.getDbDateString(new Date(dateTime * 1000L)));
        weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
        weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
        weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
        weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
        weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
        weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
        weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
        weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

        cVVector.add(weatherValues);
    }
    if (cVVector.size() > 0) {
        ContentValues[] cvArray = new ContentValues[cVVector.size()];
        cVVector.toArray(cvArray);
        mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
    }
}

From source file:com.example.jz.mysunshine.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 * <p/>/*from w  ww  .  j a  va 2s.  co  m*/
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }
        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        }
        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + inserted + "Inserted");
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
}

From source file:app.sunstreak.yourpisd.net.Student.java

public boolean hasClassGrade(int classIndex, int termIndex) throws JSONException {

    int termIndexOffset = 0;
    if (gradeSummary[classIndex][3] == CLASS_DISABLED_DURING_TERM)
        termIndexOffset = 4;//from  ww w  . j av a2s.c o  m

    termIndex -= termIndexOffset;

    if (classGrades.indexOfKey(classIndex) < 0)
        return false;

    JSONObject classGrade = classGrades.get(classIndex);
    JSONArray terms = classGrade.getJSONArray("terms");
    JSONObject term = terms.getJSONObject(termIndex);
    long lastUpdated = term.optLong("lastUpdated", -1);

    return lastUpdated != -1;
}

From source file:app.sunstreak.yourpisd.net.Student.java

public JSONObject getClassGrade(int classIndex, int termIndex) throws JSONException {

    String html = "";

    int classId = gradeSummary[classIndex][0];
    int termIndexOffset = 0;
    if (gradeSummary[classIndex][3] == CLASS_DISABLED_DURING_TERM)
        termIndexOffset = 4;//from  w  ww.ja v a  2s  .  c  o m

    termIndex -= termIndexOffset;

    if (hasClassGrade(classIndex, termIndex + termIndexOffset))
        return classGrades.get(classIndex).optJSONArray("terms").optJSONObject(termIndex);

    try {

        int termId = getTermIds(classId)[termIndex];

        html = getDetailedReport(classId, termId, studentId);

    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    // Parse the teacher name if not already there.
    try {
        classList.getJSONObject(classIndex).getString("teacher");
    } catch (JSONException e) {
        // Teacher was not found.
        String[] teacher = Parser.teacher(html);
        try {
            classList.getJSONObject(classIndex).put("teacher", teacher[0]);
            classList.getJSONObject(classIndex).put("teacherEmail", teacher[1]);
        } catch (JSONException f) {
            e.printStackTrace();
        }
    }

    JSONObject classGrade;

    try {
        classGrade = new JSONObject(classList.getJSONObject(getClassMatch()[classIndex]).toString());

        JSONArray termGrades = Parser.detailedReport(html);
        Object[] termCategory = Parser.termCategoryGrades(html);

        JSONArray termCategoryGrades = (JSONArray) termCategory[0];
        if ((Integer) termCategory[1] != -1)
            classGrade.getJSONArray("terms").getJSONObject(termIndex).put("average", termCategory[1]);

        classGrade.getJSONArray("terms").getJSONObject(termIndex).put("grades", termGrades);
        classGrade.getJSONArray("terms").getJSONObject(termIndex).put("categoryGrades", termCategoryGrades);

        Instant in = new Instant();
        // String time = in.toString();
        // System.out.println(time);
        classGrade.getJSONArray("terms").getJSONObject(termIndex).put("lastUpdated", in.getMillis());
        // classGrade.getJSONArray("terms").getJSONObject(termIndex).put("lastUpdated",
        // "0");

        // System.out.println("cg= " + classGrade);

        if (classGrades.indexOfKey(classIndex) < 0)
            classGrades.put(classIndex, classGrade);

        return classGrade.getJSONArray("terms").getJSONObject(termIndex);

    } catch (JSONException e) {
        System.err.println("Error: Class index = " + classIndex + "; JSON index = "
                + getClassMatch()[classIndex] + "; Term index = " + termIndex + ".");
        e.printStackTrace();
        return null;
    }

}

From source file:com.henry.ecdemo.ui.chatting.model.DescriptionRxRow.java

@Override
public void buildChattingData(final Context context, BaseHolder baseHolder, ECMessage detail, int position) {

    DescriptionViewHolder holder = (DescriptionViewHolder) baseHolder;
    ECMessage message = detail;/*from w w  w.  jav a2  s  .  c o  m*/
    if (message != null) {
        if (message.getType() == ECMessage.Type.TXT) {
            String msgType = "";
            JSONArray jsonArray = null;
            if (!TextUtils.isEmpty(message.getUserData()))
                try {
                    JSONObject jsonObject = new JSONObject(message.getUserData());
                    msgType = jsonObject.getString(CCPChattingFooter2.TXT_MSGTYPE);
                    jsonArray = jsonObject.getJSONArray(CCPChattingFooter2.MSG_DATA);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            if (TextUtils.equals(msgType, CCPChattingFooter2.FACETYPE)) {
                holder.getDescTextView().setBackgroundResource(0);
            } else {
                holder.getDescTextView().setBackgroundResource(R.drawable.chat_from_bg_normal);
            }
            ECTextMessageBody textBody = (ECTextMessageBody) message.getBody();
            String msgTextString = textBody.getMessage();
            holder.getDescTextView().showMessage(message.getId() + "", msgTextString, msgType, jsonArray);
            holder.getDescTextView().setMovementMethod(LinkMovementMethod.getInstance());
            View.OnClickListener onClickListener = ((ChattingActivity) context).mChattingFragment
                    .getChattingAdapter().getOnClickListener();
            ViewHolderTag holderTag = ViewHolderTag.createTag(message, ViewHolderTag.TagType.TAG_IM_TEXT,
                    position);
            holder.getDescTextView().setTag(holderTag);
            holder.getDescTextView().setOnClickListener(onClickListener);
        } else if (message.getType() == ECMessage.Type.CALL) {
            ECCallMessageBody textBody = (ECCallMessageBody) message.getBody();
            holder.getDescTextView().setText(textBody.getCallText());
            holder.getDescTextView().setMovementMethod(LinkMovementMethod.getInstance());
        }
    }
}

From source file:com.creationgroundmedia.popularmovies.trailers.TrailerLoader.java

private List<TrailerItem> getTrailersFromJSON(String trailersJsonStr) throws JSONException {

    if (trailersJsonStr == null) {
        return null;
    }//from w  ww  . j a  va2  s  .  c o m

    JSONObject movieJSON = new JSONObject(trailersJsonStr);
    JSONArray trailersList = movieJSON.getJSONArray(mContext.getString(R.string.jsonresults));
    mTrailers = new ArrayList<>();

    for (int i = 0; i < trailersList.length(); i++) {
        JSONObject titleJSON = trailersList.getJSONObject(i);
        if (titleJSON.getString(mContext.getString(R.string.jsonsite)).equalsIgnoreCase("YouTube")) {
            TrailerItem t = new TrailerItem(titleJSON.getString(mContext.getString(R.string.jsonname)),
                    titleJSON.getString(mContext.getString(R.string.jsonkey)));
            mTrailers.add(t);
        }
    }
    return mTrailers;
}

From source file:de.btobastian.javacord.utils.handler.message.MessageBulkDeleteHandler.java

@Override
public void handle(JSONObject packet) {
    JSONArray messageIds = packet.getJSONArray("ids");
    for (int i = 0; i < messageIds.length(); i++) {
        String messageId = messageIds.getString(i);
        final Message message = api.getMessageById(messageId);
        if (message == null) {
            return; // no cached version available
        }/* w  w w.  ja v  a2  s  .  c o  m*/
        listenerExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                List<MessageDeleteListener> listeners = api.getListeners(MessageDeleteListener.class);
                synchronized (listeners) {
                    for (MessageDeleteListener listener : listeners) {
                        try {
                            listener.onMessageDelete(api, message);
                        } catch (Throwable t) {
                            logger.warn("Uncaught exception in MessageDeleteListener!", t);
                        }
                    }
                }
            }
        });
    }
}

From source file:com.github.koraktor.steamcondenser.community.GameInventory.java

/**
 * Updates the contents of the backpack using Steam Web API
 *
 * @throws WebApiException on Web API errors
 *//*w w w.  j  av a 2 s  . c o  m*/
public void fetch() throws SteamCondenserException {
    try {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("SteamID", this.steamId64);
        JSONObject result = WebApi.getJSONData("IEconItems_" + this.getAppId(), "GetPlayerItems", 1, params);

        this.items = new HashMap<Integer, GameItem>();
        this.preliminaryItems = new ArrayList<GameItem>();
        JSONArray itemsData = result.getJSONArray("items");
        for (int i = 0; i < itemsData.length(); i++) {
            JSONObject itemData = itemsData.getJSONObject(i);
            if (itemData != null) {
                try {
                    GameItem item = this.getItemClass().getConstructor(this.getClass(), JSONObject.class)
                            .newInstance(this, itemData);
                    if (item.isPreliminary()) {
                        this.preliminaryItems.add(item);
                    } else {
                        this.items.put(item.getBackpackPosition() - 1, item);
                    }
                } catch (IllegalAccessException e) {
                } catch (InstantiationException e) {
                } catch (InvocationTargetException e) {
                    if (e.getCause() instanceof SteamCondenserException) {
                        throw (SteamCondenserException) e.getCause();
                    } else {
                        throw (RuntimeException) e.getCause();
                    }
                } catch (NoSuchMethodException e) {
                }
            }
        }
    } catch (JSONException e) {
        throw new WebApiException("Could not parse JSON data.", e);
    }

    this.fetchDate = new Date();
}

From source file:com.fsa.en.dron.activity.MainActivity.java

private void fetchImages() {

    pDialog.setMessage("Levantando vuelo...");
    pDialog.setCanceledOnTouchOutside(false);
    pDialog.show();//ww  w.j  ava  2 s.  c om

    JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, endpoint, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());
                    pDialog.hide();
                    JSONArray array = null;

                    try {
                        JSONObject user = response.getJSONObject("photos");
                        array = user.getJSONArray("photo");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    images.clear();
                    for (int i = 0; i < array.length(); i++) {
                        try {
                            JSONObject object = array.getJSONObject(i);
                            Image image = new Image();

                            image.setSmall("https://farm2.staticflickr.com/" + object.getString("server") + "/"
                                    + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            image.setMedium("https://farm2.staticflickr.com/" + object.getString("server") + "/"
                                    + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            image.setLarge("https://farm2.staticflickr.com/" + object.getString("server") + "/"
                                    + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            image.setUrl("https://farm2.staticflickr.com/" + object.getString("server") + "/"
                                    + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            image.setId(object.getString("id"));
                            Log.i("uuu", "" + "https://farm2.staticflickr.com/" + object.getString("server")
                                    + "/" + object.getString("id") + "_" + object.getString("secret") + ".jpg");
                            images.add(image);

                        } catch (JSONException e) {
                            Log.e(TAG, "Json parsing error: " + e.getMessage());
                        }
                    }

                    mAdapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(TAG, "Error: " + error.getMessage());
                    pDialog.hide();
                }
            });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(req);
}

From source file:widgets.Graphical_List.java

@SuppressLint("HandlerLeak")
public Graphical_List(tracerengine Trac, Activity context, int id, int dev_id, String name, String type,
        String address, final String state_key, String url, final String usage, int period, int update,
        int widgetSize, int session_type, final String parameters, String model_id, int place_id,
        String place_type, SharedPreferences params) {
    super(context, Trac, id, name, "", usage, widgetSize, session_type, place_id, place_type, mytag, container);
    this.Tracer = Trac;
    this.context = context;
    this.dev_id = dev_id;
    this.id = id;
    this.usage = usage;
    this.address = address;
    //this.type = type;
    this.state_key = state_key;
    this.update = update;
    this.wname = name;
    this.url = url;
    String[] model = model_id.split("\\.");
    this.type = model[0];
    this.place_id = place_id;
    this.place_type = place_type;
    this.params = params;
    packageName = context.getPackageName();
    this.myself = this;
    this.session_type = session_type;
    this.parameters = parameters;
    setOnLongClickListener(this);
    setOnClickListener(this);

    mytag = "Graphical_List (" + dev_id + ")";
    login = params.getString("http_auth_username", null);
    password = params.getString("http_auth_password", null);

    //state key/*ww w. j  av  a  2 s .  com*/
    state_key_view = new TextView(context);
    state_key_view.setText(state_key);
    state_key_view.setTextColor(Color.parseColor("#333333"));

    //value
    value = new TextView(context);
    value.setTextSize(28);
    value.setTextColor(Color.BLACK);
    animation = new AlphaAnimation(0.0f, 1.0f);
    animation.setDuration(1000);

    if (with_list) {
        //Exploit parameters
        JSONObject jparam = null;
        String command;
        JSONArray commandValues = null;
        try {
            jparam = new JSONObject(parameters.replaceAll("&quot;", "\""));
            command = jparam.getString("command");
            commandValues = jparam.getJSONArray("commandValues");
            Tracer.e(mytag, "Json command :" + commandValues);
        } catch (Exception e) {
            command = "";
            commandValues = null;
            Tracer.e(mytag, "Json command error " + e.toString());

        }
        if (commandValues != null) {
            if (commandValues.length() > 0) {
                if (known_values != null)
                    known_values = null;

                known_values = new String[commandValues.length()];
                for (int i = 0; i < commandValues.length(); i++) {
                    try {
                        known_values[i] = commandValues.getString(i);
                    } catch (Exception e) {
                        known_values[i] = "???";
                    }
                }
            }

        }
        //list of choices
        listeChoices = new ListView(context);

        listItem = new ArrayList<HashMap<String, String>>();
        list_usable_choices = new Vector<String>();
        for (int i = 0; i < known_values.length; i++) {
            list_usable_choices.add(getStringResourceByName(known_values[i]));
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("choice", getStringResourceByName(known_values[i]));
            map.put("cmd_to_send", known_values[i]);
            listItem.add(map);

        }

        SimpleAdapter adapter_map = new SimpleAdapter(getContext(), listItem, R.layout.item_choice,
                new String[] { "choice", "cmd_to_send" }, new int[] { R.id.choice, R.id.cmd_to_send });
        listeChoices.setAdapter(adapter_map);
        listeChoices.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if ((position < listItem.size()) && (position > -1)) {
                    //process selected command
                    HashMap<String, String> map = new HashMap<String, String>();
                    map = listItem.get(position);
                    cmd_requested = map.get("cmd_to_send");
                    Tracer.d(mytag,
                            "command selected at Position = " + position + "  Commande = " + cmd_requested);
                    new CommandeThread().execute();
                }
            }
        });

        listeChoices.setScrollingCacheEnabled(false);
        //feature panel 2 which will contain list of selectable choices
        featurePan2 = new LinearLayout(context);
        featurePan2.setLayoutParams(
                new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        featurePan2.setGravity(Gravity.CENTER_VERTICAL);
        featurePan2.setPadding(5, 10, 5, 10);
        featurePan2.addView(listeChoices);

    }

    LL_featurePan.addView(value);

    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 2) {
                Toast.makeText(getContext(), "Command Failed", Toast.LENGTH_SHORT).show();

            } else if (msg.what == 9999) {

                //Message from cache engine
                //state_engine send us a signal to notify value changed
                if (session == null)
                    return;

                String loc_Value = session.getValue();
                Tracer.d(mytag, "Handler receives a new value <" + loc_Value + ">");
                value.setText(getStringResourceByName(loc_Value));
                //To have the icon colored as it has no state
                IV_img.setBackgroundResource(Graphics_Manager.Icones_Agent(usage, 2));

            } else if (msg.what == 9998) {
                // state_engine send us a signal to notify it'll die !
                Tracer.d(mytag, "cache engine disappeared ===> Harakiri !");
                session = null;
                realtime = false;
                removeView(LL_background);
                myself.setVisibility(GONE);
                if (container != null) {
                    container.removeView(myself);
                    container.recomputeViewAttributes(myself);
                }
                try {
                    finalize();
                } catch (Throwable t) {
                } //kill the handler thread itself
            }
        }

    }; //End of handler

    //================================================================================
    /*
     * New mechanism to be notified by widgetupdate engine when our value is changed
     * 
     */
    WidgetUpdate cache_engine = WidgetUpdate.getInstance();
    if (cache_engine != null) {
        session = new Entity_client(dev_id, state_key, mytag, handler, session_type);
        if (tracerengine.get_engine().subscribe(session)) {
            realtime = true; //we're connected to engine
            //each time our value change, the engine will call handler
            handler.sendEmptyMessage(9999); //Force to consider current value in session
        }

    }
    //================================================================================
    //updateTimer();   //Don't use anymore cyclic refresh....   

}