gpt4 book ai didi

java - 来自响应的 TextView

转载 作者:太空宇宙 更新时间:2023-11-04 10:05:36 25 4
gpt4 key购买 nike

我正在尝试从此 API 获取带有 URL 的地理位置 JSON 数据 http://ip-api.com/json/?fields=query,country,city并向我的 TextView 布局显示 IP 地址、城市、国家/地区

回应:

{"city":"Bandung","country":"Indonesia","query":"127.0.0.1"}

MainActivity.java:

public class MainActivity extends AppCompatActivity {

Button start;
TextView textView;
RequestQueue requestQueue;

public static TextView data;

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

start = (Button) findViewById(R.id.lokasi);
textView = (TextView) findViewById(R.id.textViewLok);
requestQueue = Volley.newRequestQueue(this);

start.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View ){

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://ip-api.com/json/?fields=query,country,city",
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {

JSONObject jsonObject = new JSONObject(response);
String city = jsonObject.getString("city");
String country= jsonObject.getString("country");
String ip = jsonObject.getString("query");

}
},

new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY","ERROR");
}
}


)
}
}
}
}

最佳答案

您需要将响应(从 api 获得)放入 JSONObject 中。

JSONObject jsonObject = new JSONObject(myResponse);

之后就可以解析jsonObject了。

String city = jsonObject.getString("city");
String country= jsonObject.getString("country");
String ip = jsonObject.getString("query");

然后只需将字符串放入 TextView 中即可。

更新:

只需将 onResponse 更改为此即可。

@Override
public void onResponse(JSONObject response) {
String city = response.getString("city");
String country= response.getString("country");
String ip = response.getString("query");
}

关于java - 来自响应的 TextView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52967555/

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