从JSON URL设置TextView的文本?

时间:2018-04-08 14:44:37

标签: android json textview

您好我正在制作一个应用程序,从网址获取json数据,我想获得"积分"从json设置到textView7。我有一些代码,但我不知道它是否正确。我希望能够从网址https://www.lurkinator.net/api/data?username=bobtheshoplifter_

中拉出2个不同点

"积分":3,  "用户名":" bobtheshoplifter _"

我想在textView&#39s中设置它们

以下是我的文本视图的外观Image用户名和点都是单独的,用户名的字符串是@ string / userid和points @ string / points

    public class AddProfile extends Activity {
        // All xml labels

        TextView txtPoints;


        // Progress Dialog
        private ProgressDialog pDialog;

        // Profile json object
        JSONArray points;
        JSONObject hay;
        // Profile JSON url
        private static final String POINTS_URL = "https://www.lurkinator.net/api/data?username=bobtheshoplifter_";

        // ALL JSON node names
        private static final String TAG_POINTS = "points";


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

            txtPoints = (TextView) findViewById(R.id.textView7);

1 个答案:

答案 0 :(得分:0)

对链接的调用是异步的,一旦打开活动,数据就不会立即可用,因此一旦从网络调用中检索到数据,就必须确保有机制在textview上调用setText。

  1. Volley(或任何其他等效管理网络请求)
  2. 在获取数据后,回调活动以在textview中设置检索到的文本。
  3. 排球 - 转到此link以了解有关排球以及如何进行排球的更多信息。

    回调 - 创建一个界面Callback,如下所示。一旦从网络调用中检索数据,就应该调用updateData方法。

    public interface Callback{
        public void updateData(String data);
    }
    

    现在在Activity

    中实现如下界面
    public class AddProfile extends Activity implements Callback{
    

    现在你必须在updateData

    中实现方法AddProfile
    public void updateData(String data){
          txtPoints.setText(data);
    }
    

    现在你必须添加代码来调用url,解析数据并调用回调来设置点。

    AddProfile课程中添加代码:

    txtPoints = (TextView) findViewById(R.id.textView7);
    StringRequest request = new StringRequest(Request.Method.GET, POINTS_URL, new Response.Listener<String>(){
    
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    String data=object.getString(TAG_POINTS);
                    this.updateData(data);
                }catch (JSONException e){
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //add any error handling
            }
        });
    
    Volley.newRequestQueue(getApplicationContext()).add(request);
    

    上面的代码调用url并解析JSON并检索点。检索点后,它会调用方法updateData,您可以在其中使用代码在textview中设置数据。

    建议阅读教程here,以便在Android中使用JSON。

相关问题