gpt4 book ai didi

java - Loader onCreateLoader 不返回 String

转载 作者:行者123 更新时间:2023-12-02 12:34:47 28 4
gpt4 key购买 nike

我想解析对普通 StringJSON 响应,但是当我尝试返回 jsonString 时,我收到以下消息:

Incompatible types:
Required:
android.content.Loader
<java.lang.String>
Found:
java.lang.String

你能向我解释一下我做错了什么吗?

package com.example.entropy.booklist;

import android.app.LoaderManager;
import android.content.Loader;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import static android.R.attr.data;

/**
* Created by entropy on 18/07/17.
*/

public class AllInOne extends AppCompatActivity implements LoaderManager.LoaderCallbacks<String> {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_in_one);
getLoaderManager().initLoader(0, null, this);

}

String jsonStr ;

@Override
public Loader<String> onCreateLoader(int id, Bundle args) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;

String line;
try {
URL url = new URL("https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2012-01-01&endtime=2012-12-01&minmagnitude=6");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null)
{return null;}

reader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = reader.readLine()) != null) buffer.append(line);
if (buffer.length() == 0)
{return null;}

jsonStr = buffer.toString();



} catch (IOException e) {
return null;

} finally {
if (urlConnection != null) urlConnection.disconnect();
if (reader != null) {
try {
reader.close();

} catch (final IOException e) {
Log.e("MainActivity", "Error closing stream", e);
}
}
}
return jsonStr;
}

最佳答案

首先,您的错误消息绝对正确“不兼容的类型:必需:android.content.Loader 找到:java.lang.String”,因为您正在返回 String但方法想要 Loader<String> .

其次,您使用加载器的方式是错误的。数据加载不应该在 onCreateLoader() 。检查此链接以获取正确的信息,在继续任何实现之前阅读此文档。 https://developer.android.com/guide/components/loaders.html

另外,请查看AsyncTaskLoader在同一个文档中。这将实现您从服务器加载数据的目的。

关于java - Loader<String> onCreateLoader 不返回 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45173458/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com