de.egore911.drilog.tasks.LoadChannelsTask.java Source code

Java tutorial

Introduction

Here is the source code for de.egore911.drilog.tasks.LoadChannelsTask.java

Source

/* @(#)LoadChannelsTask.java
 *
 * Copyright (C) 2011-2014 Christoph Brill
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package de.egore911.drilog.tasks;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.util.Pair;
import de.egore911.drilog.ShowActivity;
import de.egore911.drilog.util.HttpUtil;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;
import java.net.URL;

/**
 * Load the available channels from the server
 *
 * @author Christoph Brill <egore911@gmail.com>
 * @since 0.7
 */
public class LoadChannelsTask extends AsyncTask<String, Void, String[]> {

    private final Activity callingActivity;

    public LoadChannelsTask(Activity callingActivity) {
        this.callingActivity = callingActivity;
    }

    @Override
    protected String[] doInBackground(String... params) {
        String url = params[0];
        try {
            Pair<String, URL> json = HttpUtil.getPlainTextFromUrl(url);
            JSONArray jsonArray = new JSONArray(json.first);
            String[] result = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                result[i] = jsonArray.getString(i);
            }
            return result;
        } catch (JSONException | IOException e) {
            Log.e(getClass().getSimpleName(), e.getMessage(), e);
            return null;
        }
    }

    @Override
    protected void onPostExecute(String[] channels) {
        if (channels == null) {
            channels = new String[] { "dri-devel", "radeon", "nouveau" };
        }
        Intent intent = new Intent(callingActivity, ShowActivity.class);
        intent.putExtra("channels", channels);
        callingActivity.startActivity(intent);
    }
}