Как я могу автоматически (без какой-либо кнопки) обновлять свое текстовое представление каждый раз, когда сервер отправляет новый объект JSON, используя Android Volley или любую другую библиотеку? Это простая программа, имеющая только один вид текста. Я вставил оба файла. Я получаю файл JSON каждый раз, когда вводю текст со стороны сервера и хочу, чтобы он сразу отображался в текстовом представлении.
mainactivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
// Will show the string "data" that holds the results
TextView results;
// URL of object to be parsed
String JsonURL = "url_link";
// This string will hold the results
String data = "";
// Defining the Volley request queue that handles the URL request concurrently
RequestQueue requestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creates the Volley request queue
requestQueue = Volley.newRequestQueue(this);
// Casts results into the TextView found within the main layout XML with id jsonData
results = (TextView) findViewById(R.id.jsonData);
JSONObject jsonObj = new JSONObject();
// Creating the JsonObjectRequest class called obreq, passing required parameters:
//GET is used to fetch data from the server, JsonURL is the URL to be fetched from.
JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, JsonURL, jsonObj, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = response.getJSONObject("colorObject");
String color = obj.getString("colorName");
// String desc = obj.getString("description");
data += "Color Name: " + color;
// Adds the data string to the TextView "results"
results.setText(data);
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON object request "obreq" to the request queue
requestQueue.add(obreq);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:textSize="20sp"
android:textStyle="bold"
android:id="@+id/jsonData"
android:textColor="#000000" />
</ScrollView>