我正在从带有json的api获取一些信息,并将其添加到一些变量上。问题是我不知道如何在其他类中使用它们,这是我的AsyncTask类
melt/dcast
例如,我将class TestJson extends AsyncTask<String,String,String> {
public static String aJsonString;
@Override
protected String doInBackground(String... strings) {
ArrayList<Geocode> geocodes = null;
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("https://developers.zomato.com/api/v2.1/geocode?lat=40.712776&lon=-74.005974");
httppost.setHeader("user-key", "mykey");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
JSONObject jObject = new JSONObject(result);
JSONObject jsonObject= (JSONObject) jObject.get("location");
//for nested json objects
String title=(String)jsonObject.get("city_name");
aJsonString = jObject.getString("link");
} catch (Exception e) {
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
try {
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
设为静态,但是如果我在其他任何地方调用它,则会使我为空。对此有任何想法吗?
答案 0 :(得分:0)
尝试将json数据存储到具有公共访问权限的静态变量(类级别/全局)中,然后在所需的任何地方共享(您可能需要一些if-else条件来检查有效数据和非null数据)。