如何将 java Json 数据获取类转换为方法?



我得到了一个从Web服务获取数据的方法,所以我正在寻找一种将其调用为方法的方法。 如何将此代码转换为方法?或者我可以在方法中调用类吗?因为它有一个受保护的方法并从类扩展而来,但是如果我实现了扩展类AsyncTask到类,我需要使用 Json 获取受保护的方法,doInBackground它说"此处扩展了接口"。 这是我的代码,我需要将其转换为方法或将其添加到我要在其中使用它的类的方法:

注意:我已经将AppCompatActivity扩展到了我想在其中调用doInBackground的类,因此我无法扩展FetchData类。

非常感谢:D

package com.example.wordspuzzlejsontest;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
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.MalformedURLException;
import java.net.URL;


public class FetchData extends AsyncTask<Void, Void, Void> {
final String update = "4";
String data = "";
int currentLevel;
Context context;
FetchData(Context context) {
this.context = context;
}
@Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://api.jsonbin.io/b/5e42776dd18e4016617690ce/" + update);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
SharedPreferences sharedPreferences = context.getSharedPreferences("SHARED_PREFS", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
currentLevel = sharedPreferences.getInt("currentLevel", 0);
for (int i = 0; i < JA.length();) {
i = currentLevel;
JSONObject JO = (JSONObject) JA.get(i);

String id = (String) JO.get("id");
String img = (String) JO.get("img");
String w1 = (String) JO.get("w1");
String w2 = (String) JO.get("w2");
String w3 = (String) JO.get("w3");
String w4 = (String) JO.get("w4");
editor.putString("id" + i, id);
editor.putString("img" + i, img);
editor.putString("w1" + i, w1);
editor.putString("w2" + i, w2);
editor.putString("w3" + i, w3);
editor.putString("w4" + i, w4);
editor.apply();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}

```

总结我的评论:

创建一个名为NewClass.java的新类

class NewClass extends FetchData{
public Void fetchData(Void... voids){ return this.doInBackground(voids);}
}

由于doInBackground受保护的方法,因此您将在NewClass.java内部具有私有访问权限

最新更新