Android AsyncTask未在后台线程中执行

时间:2017-02-06 10:44:35

标签: java android json multithreading android-asynctask

我正在尝试从网址中获取一些JSON,但即使我使用AsyncTask在不同的线程上运行代码,我也无法打开流。我从来没有进入“流成功打开”的打印声明。我在堆栈溢出时可以找到的这个问题的其他类似示例是hereherehere,但我仍然无法弄明白。任何帮助将不胜感激!

JSON Grabbing& amp;的信用Here处理代码。

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.Reader;



public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button = (Button) findViewById(R.id.button);
    System.out.println("Set Bustton");

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("Made it to On click");
            new JSONGod().doInBackground();
        }

    });
}


private class JSONGod extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        try {

            System.out.println("Made it to doInBackground");

            URL url = new URL("Url Here");
            InputStream is = url.openStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            System.out.println("Stream Successfully Opened");
            try {
                String jsonText = readAll(rd);
                System.out.println("Made it past read all");
                JSONObject json = new JSONObject(jsonText);
                //Do things with JSON here
            } finally {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String readAll(Reader rd) throws IOException {
        System.out.println("Made it to read all");
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }
}
}

0 个答案:

没有答案