我有从外部JSON数组接收变量的代码
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.Toast;
public class ListviewActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String json_str = getJsonData();
try{
JSONArray jArray = new JSONArray(json_str);
JSONObject json = null;
json = jArray.getJSONObject(0);
String date=json.getString("data");
Toast.makeText(getBaseContext(), date, Toast.LENGTH_SHORT).show();
} catch ( JSONException e) {
e.printStackTrace();
}
}
private String getJsonData(){
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("url_php_file_with_JSON");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//comparison variable (from String date=json.getString("data")) with an other static variable
如何正确显示变量String date = json.getString(“data”)以便在其他函数中进行比较?
虽然它在使用Toast.makeText接收变量的函数中显示,但我必须在java文件的其他区域中使用它
答案 0 :(得分:0)
您需要将String设为全局变量,如下所示:
public class ListviewActivity extends Activity {
private String date;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String json_str = getJsonData();
try{
JSONArray jArray = new JSONArray(json_str);
JSONObject json = null;
json = jArray.getJSONObject(0);
date=json.getString("data");
Toast.makeText(getBaseContext(), date, Toast.LENGTH_SHORT).show();
} catch ( JSONException e) {
e.printStackTrace();
}
}
// The rest of your code
}
这样,您可以在班级的任何地方自由使用它。