使用Reddit API调用AsyncTask方法时获取错误消息

问题描述 投票:-1回答:1

我目前正在尝试制作RedditPost检索应用程序,并试图通过使用Reddit API https://www.reddit.com/r/android/hot.json?limit=10将json字符串返回给我的应用程序>

AsyncTask

public class DownloadAsyncTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls)
    {
        // Parameter comes from the execute() call: params[0] is the url.
        try
        {
            return downloadUrl(urls[0]);
        }
        catch (IOException e)
        {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }

    // When we've completed getting the web page we'll pass the contents
    // as a string to our MainActivity to set the text on the content TextView
    @Override
    protected void onPostExecute(String result)
    {
     PostListActivity.setPageContent(result);
    }


    // Method to read an InputStream, convert it into a String and return it
    public String readInputStream(InputStream stream, int len) throws IOException,
            UnsupportedEncodingException
    {
        Reader reader = new InputStreamReader(stream, "UTF-8");
        char[] buffer = new char[len];
        reader.read(buffer);
        return new String(buffer);
    }

    // Given a URL, establishes an HttpUrlConnection and retrieves
    // the web page content as a InputStream, which it returns as
    // a string.
    private String downloadUrl(String theURL) throws IOException
    {
        InputStream is = null;

        // Only display the first 500 characters of the retrieved web page content.
        int maxContentLength = 500;

        try {
            URL url = new URL(theURL);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // We'll wait up to 15 seconds to connect to the web page before timing out
            conn.setConnectTimeout(15000);

            // We'll wait up to 10 seconds for additional data from the web page before
            // timing out. That is: After connecting, if we don't receive data within 10
            // seconds, or the data transfer stalls for more than 10 seconds, then we're going
            // to consider that a timeout.
            conn.setReadTimeout(10000);

            // Specify that we'll call GET to obtain data (i.e. standard HTTP request method)
            conn.setRequestMethod("GET");

            // Specify that this connection accepts input
            conn.setDoInput(true);

            // Starts the query
            conn.connect();

            int response = conn.getResponseCode();
            System.out.println("Web page response is: " + response);

            // Get the input stream provided by the connection to the webpage
            is = conn.getInputStream();

            // Convert the InputStream into a string
            String contentAsString = readInputStream(is, maxContentLength);

            return contentAsString;

            // Makes sure that the InputStream is closed after the app is finished using it.
        }
        finally
        {
            if (is != null)
            {
                is.close();
            }
        }
    }
}

错误:按下列表视图项之一时发生此错误

    Process: au.edu.federation.itech3107.feduniredditclient30331863, PID: 8239
    java.lang.RuntimeException: Unable to start activity ComponentInfo{au.edu.federation.itech3107.feduniredditclient30331863/au.edu.federation.itech3107.feduniredditclient30331863.PostListActivity}: com.google.gson.JsonSyntaxException: Expected a com.google.gson.JsonObject but was com.google.gson.JsonPrimitive
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3344)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3488)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2049)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:216)
        at a

PostListActivity(在其中调用AyncTask的地方)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_list);

        final ListView lv = (ListView) findViewById(R.id.LV_Post_list);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            String myParam = extras.getString("paramPosition");

            // Get the URL from the UI's text field.
            String stringUrl = "https://www.reddit.com/r/" + myParam + "/hot.json?limit=10";

            // Get access to the connectivity service...
            ConnectivityManager cm =
                    (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

            // ...which we'll use to find out if we have an active network connection.
            NetworkInfo networkInfo = null;
            if (cm != null) {
                networkInfo = cm.getActiveNetworkInfo();
            }

            // If so...
            if ( (networkInfo != null) && ( networkInfo.isConnected() ) ) {
                // Fetch the webpage using an instance of our DownloadWebpageTask class
                new DownloadAsyncTask().execute(stringUrl);
                String jsonFromReddit = String.valueOf(new DownloadAsyncTask().execute(stringUrl));
                ArrayList<RedditPost> posts = RedditPostHelper.getRedditPostsFromJSON(jsonFromReddit);
                for (int i = 0; i < posts.size(); i++) {
                    Posts_Array_List.add(String.valueOf(posts.get(i)));
                }
            }
            else // No luck?
            {
                Toast.makeText(getApplicationContext(),"No network connection available.",Toast.LENGTH_SHORT).show();
            }
        }


Sorry if this looks awful I am new to Java :( 

我目前正在尝试制作RedditPost检索应用程序,并试图通过使用Reddit API https://www.reddit.com/r/android/hot.json?limit=将json字符串返回给我的应用程序10 AsyncTask ...

java android android-studio
1个回答
0
投票

您缺少互联网许可将其放在清单上方的应用程序标签上方

© www.soinside.com 2019 - 2024. All rights reserved.