作者:手机用户2502901613 | 来源:互联网 | 2023-05-19 08:54
I am a beginner in Android. I want to get a JSON response in a list and show it in a ListView . How to do this?
Here is my code for JSON post.
我是Android的初学者。我想在列表中获取JSON响应并在ListView中显示它。这个怎么做?这是我的JSON帖子的代码。
public class NewTest extends AppCompatActivity { TextView
txtJson;
Button btnOkay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_test);
txtJson= (TextView) findViewById(R.id.txtJson);
assert (findViewById(R.id.btnOkay)) != null;
(findViewById(R.id.btnOkay)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { new TaskPostWebService("written url here").execute(((TextView)
findViewById(R.id.txtJson)).getText().toString());
}
}); }
private class TaskPostWebService extends AsyncTask {
private String url;
private ProgressDialog progressDialog;
private JSONParser jsonParser;
public TaskPostWebService(String url ){
this.url = url;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(NewTest.this,"","");
}
@Override
protected String doInBackground(String... params) {
String fact = "";
try {
final MediaType JSON = MediaType.parse("application/json");
android.util.Log.e("charset", "charset - " + JSON.charset());
OkHttpClient client = new OkHttpClient();
//Create a JSONObject with the data to be sent to the server
final JSONObject dataToSend = new JSONObject()
.put("nonce", "G9Ivek")
.put("iUserId", "477");
android.util.Log.e("data - ", "data - " + dataToSend.toString());
//Create request object
Request request = new Request.Builder()
.url("written url here")
.post(RequestBody.create(JSON, dataToSend.toString().getBytes(Charset.forName("UTF-8"))))
.addHeader("Content-Type", "application/json")
.build();
android.util.Log.e("request - ", "request - " + request.toString());
android.util.Log.e("headers - ", "headers - " + request.headers().toString());
android.util.Log.e("body - ", "body - " + request.body().toString());
//Make the request
Response respOnse= client.newCall(request).execute();
android.util.Log.e("response", " " + response.body().string()); //Convert the response to String
String respOnseData= response.body().string();
//Construct JSONObject of the response string
JSONObject dataReceived = new JSONObject(responseData);
//See the response from the server
Log.i("response data", dataReceived.toString());
}
catch (Exception e){
e.printStackTrace();
}
return fact;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView text = (TextView) findViewById(R.id.txtJson);
text.setText(s);
progressDialog.dismiss();
}
}
So, how can I get a response in a list and show it in a ListView?
那么,我如何在列表中获得响应并在ListView中显示它?
2 个解决方案