Java Code Examples for com.android.volley.toolbox.JsonArrayRequest#setTag()

The following examples show how to use com.android.volley.toolbox.JsonArrayRequest#setTag() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReviewFragment.java    From watchlist with Apache License 2.0 4 votes vote down vote up
private void downloadMovieReviews() {
    if (adapter == null) {
        adapter = new ReviewAdapter(new ArrayList<Review>(), this);
        reviewList.setAdapter(adapter);
    }
    JsonArrayRequest request = new JsonArrayRequest(
            Request.Method.GET, ApiHelper.getMovieReviewsLink(movieId, pageToDownload), null,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray array) {
                    try {
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject review = array.getJSONObject(i);

                            String id = review.getString("id");
                            String comment = review.getString("comment");
                            boolean hasSpoiler = review.getBoolean("spoiler");

                            // Get date and format it
                            String inputTime = review.getString("created_at").substring(0, 10);
                            DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
                            Date date = inputFormat.parse(inputTime);
                            DateFormat outputFormat = new SimpleDateFormat("dd MMM yyyy");
                            String createdAt = outputFormat.format(date);

                            // Get user name
                            JSONObject user = review.getJSONObject("user");
                            String userName = user.getString("username");
                            if (!user.getBoolean("private")) {
                                String name = user.getString("name");
                                if (!TextUtil.isNullOrEmpty(name)) {
                                    userName = name;
                                }
                            }

                            adapter.reviewList.add(new Review(id, userName, comment, createdAt, hasSpoiler));
                        }

                        onDownloadSuccessful();

                    } catch (Exception ex) {
                        // Parsing error
                        onDownloadFailed();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    if (volleyError.networkResponse.statusCode == 404 || volleyError.networkResponse.statusCode == 405) {
                        // No such movie exists
                        onDownloadSuccessful();
                    } else {
                        // Network error, failed to load
                        onDownloadFailed();
                    }
                }
            }) {
                // Add Request Headers
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String>  params = new HashMap<>();
                    params.put("Content-type", "application/json");
                    params.put("trakt-api-key", ApiHelper.getTraktKey(getContext()));
                    params.put("trakt-api-version", "2");
                    return params;
                }
                // Get Response Headers
                @Override
                protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
                    pageToDownload = Integer.parseInt(response.headers.get("X-Pagination-Page")) + 1;
                    totalPages = Integer.parseInt(response.headers.get("X-Pagination-Page-Count"));
                    return super.parseNetworkResponse(response);
                }
            };
    isLoading = true;
    request.setTag(getClass().getName());
    VolleySingleton.getInstance().requestQueue.add(request);
}
 
Example 2
Source File: PowerNowDataLoader.java    From AndroidApp with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void run() {

    int wattFeedId = myElectricDataManager.getSettings().getPowerFeedId();
    int kWhFeedId = myElectricDataManager.getSettings().getUseFeedId();
    String url = String.format(context.getResources().getConfiguration().locale, FEED_URL, myElectricDataManager.getEmonCmsUrl() , myElectricDataManager.getEmoncmsApikey(), wattFeedId, kWhFeedId);
    Log.i("EMONCMS:URL", "mGetPowerRunner:" + url);
    JsonArrayRequest jsArrayRequest = new JsonArrayRequest
            (url, new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    String watt_value = "";
                    String kwh_value = "";

                    if (response.length() == 2) {
                        try {
                            watt_value = response.getString(0);
                            kwh_value = response.getString(1);

                            float powerNow = 0;
                            float totalPowerUsage = 0;

                            if (Utils.isNumeric(watt_value)) {
                                powerNow = Float.parseFloat(watt_value);
                            }

                            if (Utils.isNumeric(kwh_value)) {
                                totalPowerUsage = Float.parseFloat(kwh_value) * myElectricDataManager.getSettings().getPowerScaleAsFloat();
                            }

                            myElectricDataManager.setCurrentValues(powerNow, totalPowerUsage);
                            myElectricDataManager.clearMessage();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        myElectricDataManager.showMessage(R.string.invalid_number_of_responses);
                    }

                    if (!Utils.isNumeric(watt_value)) {
                        myElectricDataManager.showMessage(R.string.invalid_watt_feedid);
                    } else if (!Utils.isNumeric(kwh_value)) {
                        myElectricDataManager.showMessage(R.string.invalid_kwh_feedid);
                    } else {
                        if (!myElectricDataManager.loadUseHistory(0)) {
                            myElectricDataManager.loadPowerHistory(0);
                        }
                    }
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    myElectricDataManager.showMessage(R.string.connection_error);
                    myElectricDataManager.loadPowerNow(5000);
                }
            });

    jsArrayRequest.setTag(myElectricDataManager.getPageTag());
    HTTPClient.getInstance(context).addToRequestQueue(jsArrayRequest);
}
 
Example 3
Source File: UseByDayDataLoader.java    From AndroidApp with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void run() {
    int kWhFeedId = myElectricDataManager.getSettings().getUseFeedId();

    long end = (long) Math.floor(((Calendar.getInstance().getTimeInMillis() * 0.001) + timeZoneOffset) / INTERVAL) * INTERVAL;

    end -= timeZoneOffset;
    long start = end - (INTERVAL * daysToDisplay);

    final long chart2EndTime = end * 1000;
    final long chart2StartTime = start * 1000;

    String url = String.format(FEED_URL, myElectricDataManager.getEmonCmsUrl(), myElectricDataManager.getEmoncmsApikey(), kWhFeedId, chart2StartTime, chart2EndTime);
    Log.i("EMONCMS:URL", "mDaysofWeekRunner:" + url);

    JsonArrayRequest jsArrayRequest = new JsonArrayRequest
            (url, new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JSONArray response) {
                    List<Long> dates = new ArrayList<>();
                    List<Double> power = new ArrayList<>();
                    String dayOfWeekInitials[] = context.getResources().getStringArray(R.array.day_of_week_initials);
                    Calendar calendar = Calendar.getInstance();

                    for (int i = 0; i < response.length(); i++) {
                        JSONArray row;

                        try {
                            row = response.getJSONArray(i);
                            Long date = row.getLong(0);
                            if (date <= chart2EndTime) {
                                dates.add(date);
                                power.add(row.getDouble(1) *  myElectricDataManager.getSettings().getPowerScaleAsFloat());
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    dailyUsageBarChart.clearData();

                    int[] chart2_colors = new int[power.size()];

                    for (int i = 0; i < power.size() - 1; i++) {
                        calendar.setTimeInMillis(dates.get(i));

                        dailyUsageBarChart.addData(dayOfWeekInitials[calendar.get(Calendar.DAY_OF_WEEK) - 1],power.get(i + 1) - power.get(i));

                        if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ||
                                calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
                            chart2_colors[i] = ContextCompat.getColor(context, R.color.chartBlueDark);
                        else
                            chart2_colors[i] = ContextCompat.getColor(context, R.color.chartBlue);
                    }

                    if (power.size() > 0) {
                        double yesterdaysPowerUsage = power.get(power.size() - 1);
                        double powerToday = (myElectricDataManager.getTotalUsagekWh()) - yesterdaysPowerUsage;
                        myElectricDataManager.setUseToYesterday((float)yesterdaysPowerUsage);


                        calendar.setTimeInMillis(dates.get(dates.size() - 1));

                        dailyUsageBarChart.addData(dayOfWeekInitials[calendar.get(Calendar.DAY_OF_WEEK) - 1],powerToday);


                        if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ||
                                calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
                            chart2_colors[chart2_colors.length - 1] = ContextCompat.getColor(context, R.color.chartBlueDark);
                        } else {
                            chart2_colors[chart2_colors.length - 1] = ContextCompat.getColor(context, R.color.chartBlue);
                        }
                    }

                    dailyUsageBarChart.setBarColours(chart2_colors);
                    dailyUsageBarChart.refreshChart();

                   myElectricDataManager.clearMessage();
                   myElectricDataManager.loadPowerHistory(0);
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    myElectricDataManager.showMessage(R.string.connection_error);
                    myElectricDataManager.loadUseHistory(5000);

                }
            });

    jsArrayRequest.setTag(myElectricDataManager.getPageTag());
    HTTPClient.getInstance(context).addToRequestQueue(jsArrayRequest);
}
 
Example 4
Source File: PowerChartDataLoader.java    From AndroidApp with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void run() {

    int wattFeedId = myElectricDataManager.getSettings().getPowerFeedId();

    final long lastEntry;

    if (powerChart.requiresReset()) {
        powerChart.clearData();
    }

    if (powerChart.getLabels().size() > 0) {
        lastEntry = Long.parseLong(powerChart.getLabels().get(powerChart.getLabels().size() - 1));
    } else {
        lastEntry = 0;
    }

    Calendar cal = Calendar.getInstance();
    long endTime = cal.getTimeInMillis();
    cal.add(Calendar.HOUR, powerChart.getChartLength());
    long startTime = cal.getTimeInMillis();

    int npoints = 1500;
    final int interval = Math.round(((endTime - startTime) / 1000) / npoints);

    if (lastEntry > startTime)
        startTime = lastEntry;

    String url = String.format(context.getResources().getConfiguration().locale, FEED_URL, myElectricDataManager.getEmonCmsUrl(), myElectricDataManager.getEmoncmsApikey(), wattFeedId, startTime, endTime, interval);
    Log.i("EMONCMS:URL", "mGetPowerHistoryRunner:" + url);
    JsonArrayRequest jsArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {

            for (int i = 0; i < response.length(); i++) {
                JSONArray row;
                try {
                    row = response.getJSONArray(i);
                    long time = Long.parseLong(row.getString(0));

                    if (lastEntry == 0) {
                        powerChart.addData(row.getString(0), row.getDouble(1));
                    } else if (time >= (lastEntry + (interval * 1000))) {
                        powerChart.removeFirstPoint();
                        powerChart.addData(row.getString(0), row.getDouble(1));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            powerChart.refreshChart();
            myElectricDataManager.clearMessage();
            myElectricDataManager.loadPowerNow(10000);
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            myElectricDataManager.showMessage(R.string.connection_error);
            myElectricDataManager.loadPowerHistory(5000);
        }
    });

    jsArrayRequest.setTag(myElectricDataManager.getPageTag());

    if (endTime > lastEntry + (interval * 1000)) {
        HTTPClient.getInstance(context).addToRequestQueue(jsArrayRequest);
    } else {
        myElectricDataManager.loadPowerNow(10000);
    }
}
 
Example 5
Source File: FeedDataLoader.java    From AndroidApp with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void run() {
    String url = String.format(context.getResources().getConfiguration().locale, FEED_URL, myElectricDataManager.getEmonCmsUrl(), myElectricDataManager.getEmoncmsApikey());
    Log.i("EMONCMS:URL", "mGetFeedsRunner:" + url);

    JsonArrayRequest jsArrayRequest = new JsonArrayRequest
            (url, new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {

                    int wattFeedId = -1;
                    int kWhFeelId = -1;

                    for (int i = 0; i < response.length(); i++) {
                        JSONObject row;

                        try {
                            row = response.getJSONObject(i);

                            if (watt_default_feed_name.equals(row.getString("name"))) {
                                wattFeedId = row.getInt("id");
                            }

                            if (kwh_default_feed_name.equals(row.getString("name"))) {
                                kWhFeelId = row.getInt("id");
                            }

                            if (wattFeedId >= 0 && kWhFeelId >= 0) {
                                myElectricDataManager.setFeedIds(wattFeedId, kWhFeelId);
                                myElectricDataManager.loadPowerNow(0);
                                return;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    myElectricDataManager.showMessage(R.string.me_not_configured_text);
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    myElectricDataManager.showMessage(R.string.feed_download_error_message);
                    myElectricDataManager.loadFeeds(5000);
                }
            });
    jsArrayRequest.setTag(myElectricDataManager.getPageTag());
    HTTPClient.getInstance(context).addToRequestQueue(jsArrayRequest);
}
 
Example 6
Source File: MyElectricSettingsFragment.java    From AndroidApp with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void run() {
    String url = String.format("%s%s/feed/list.json?apikey=%s", emoncmsProtocol, emoncmsURL, emoncmsAPIKEY);

    JsonArrayRequest jsArrayRequest = new JsonArrayRequest
            (url, new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {

                    List<String> powerEntryList = new ArrayList<>();
                    List<Integer> powerEntryValueList = new ArrayList<>();

                    powerEntryList.add("AUTO");
                    powerEntryValueList.add(-1);

                    List<String> kwhFeedEntryList = new ArrayList<>();
                    List<Integer> kwhFeedEntryValueList = new ArrayList<>();

                    kwhFeedEntryList.add("AUTO");
                    kwhFeedEntryValueList.add(-1);

                    for (int i = 0; i < response.length(); i++) {
                        JSONObject row;
                        try {
                            row = response.getJSONObject(i);

                            int id = row.getInt("id");
                            String name = row.getString("name");
                            int engineType = row.getInt("engine");


                            if (engineType == 2 ||
                                    engineType == 5 ||
                                    engineType == 6) {
                                powerEntryList.add(name);
                                powerEntryValueList.add(id);
                                kwhFeedEntryList.add(name);
                                kwhFeedEntryValueList.add(id);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    FeedSpinnerAdapter powerSpinnerAdapter = new FeedSpinnerAdapter(getActivity(),R.layout.support_simple_spinner_dropdown_item,powerEntryValueList,powerEntryList);
                    powerFeedPreference.setAdapter(powerSpinnerAdapter);
                    powerFeedPreference.setEnabled(true);
                    powerFeedPreference.setSelection(powerEntryValueList.indexOf(settings.getPowerFeedId()));

                    FeedSpinnerAdapter useSpinnerAdapter = new FeedSpinnerAdapter(getActivity(),R.layout.support_simple_spinner_dropdown_item,kwhFeedEntryValueList,kwhFeedEntryList);
                    kWhFeedPreference.setAdapter(useSpinnerAdapter);

                    kWhFeedPreference.setEnabled(true);
                    kWhFeedPreference.setSelection(kwhFeedEntryValueList.indexOf(settings.getUseFeedId()));


                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    powerFeedPreference.setEnabled(false);
                    kWhFeedPreference.setEnabled(false);

                    new AlertDialog.Builder(getActivity())
                            .setTitle(R.string.error)
                            .setMessage(R.string.feed_download_error_message)
                            .setPositiveButton(android.R.string.ok, null)
                            .setIcon(android.R.drawable.ic_dialog_alert)
                            .show();
                }
            });
    jsArrayRequest.setTag(TAG);
    HTTPClient.getInstance(getActivity()).addToRequestQueue(jsArrayRequest);
}
 
Example 7
Source File: MySolarMainFragement.java    From AndroidApp with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
        public void run()
        {
            String url = String.format("%s%s/feed/list.json?apikey=%s", emoncmsProtocol, emoncmsURL, emoncmsAPIKEY);
            Log.i("EMONCMS:URL", "mGetFeedsRunner:" + url);
            JsonArrayRequest jsArrayRequest = new JsonArrayRequest
                    (url, new Response.Listener<JSONArray>()
                    {

                        @Override
                        public void onResponse(JSONArray response)
                        {
                            for (int i = 0; i < response.length(); i++)
                            {
                                JSONObject row;
                                try
                                {
                                    row = response.getJSONObject(i);
                                    int id = row.getInt("id");
                                    if (id == wattFeedId)
                                    {
                                        powerNow = Float.parseFloat(row.getString("value"));
                                        updateTextFields();
                                    }
                                    else if (id == kWhFeelId)
                                    {
                                        totalPowerUsage = ((Double) row.getDouble("value")).floatValue() * powerScale;
                                    }

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

                            if (blnDebugOnShow)
                            {
                                blnDebugOnShow = false;
                                txtDebug.setVisibility(View.GONE);
                            }
/*
                            if (Calendar.getInstance().getTimeInMillis() > nextDailyChartUpdate)
                            {
                                nextDailyChartUpdate = Calendar.getInstance().getTimeInMillis() + dailyChartUpdateInterval;
                                mHandler.post(mDaysofWeekRunner);
                            }
                            else
                            {
                                mHandler.post(mGetPowerHistoryRunner);
                            }

*/
                            mHandler.postDelayed(mGetFeedsRunner, 10000);
                        }
                    }, new Response.ErrorListener()
                    {

                        @Override
                        public void onErrorResponse(VolleyError error)
                        {
                            blnDebugOnShow = true;
                            txtDebug.setVisibility(View.VISIBLE);
                            mHandler.postDelayed(mGetFeedsRunner, 5000);
                        }
                    });

            jsArrayRequest.setTag(TAG);
            HTTPClient.getInstance(getActivity()).addToRequestQueue(jsArrayRequest);
        }
 
Example 8
Source File: MySolarSettingsFragment.java    From AndroidApp with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void run()
{
    String url = String.format("%s%s/feed/list.json?apikey=%s", emoncmsProtocol, emoncmsURL, emoncmsAPIKEY);

    JsonArrayRequest jsArrayRequest = new JsonArrayRequest
            (url, new Response.Listener<JSONArray>()
            {
                @Override
                public void onResponse(JSONArray response)
                {
                    CharSequence entries[] = new String[response.length()];
                    CharSequence entryValues[] = new String[response.length()];
                    for (int i = 0; i < response.length(); i++)
                    {
                        JSONObject row;
                        try
                        {
                            row = response.getJSONObject(i);

                            String id = row.getString("id");
                            String name = row.getString("name");
                            entries[i] = name;
                            entryValues[i] = id;
                        }
                        catch (JSONException e)
                        {
                            e.printStackTrace();
                        }
                    }
                    if (entries.length > 0 && entryValues.length > 0)
                    {
                        powerFeedPreference.setEntries(entries);
                        powerFeedPreference.setEntryValues(entryValues);
                        powerFeedPreference.setEnabled(true);
                        //kWhFeedPreference.setEntries(entries);
                        //kWhFeedPreference.setEntryValues(entryValues);
                        //kWhFeedPreference.setEnabled(true);
                    }
                }
            }, new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error)
                {
                    powerFeedPreference.setEnabled(false);
                    //kWhFeedPreference.setEnabled(false);

                    new AlertDialog.Builder(getActivity())
                            .setTitle(R.string.error)
                            .setMessage(R.string.feed_download_error_message)
                            .setPositiveButton(android.R.string.ok, null)
                            .setIcon(android.R.drawable.ic_dialog_alert)
                            .show();
                }
            });
    jsArrayRequest.setTag(TAG);
    HTTPClient.getInstance(getActivity()).addToRequestQueue(jsArrayRequest);
}