为什么此Java页面会显示我的数据中的JSON?

发布于 2025-02-08 23:48:04 字数 7826 浏览 1 评论 0原文

大家好,我在项目中收到了大问题。我使我收到服务器的响应的OKHTTP请求是完美的。问题是为什么我无法显示数据,我在XML和ListView中制作了一个模型项目(这是所需的视图),当我加速时,页面为空白。

谁能帮助我解决这个问题?

页面代码如下:

package com.example.socceraplication;

import static android.content.ContentValues.TAG;

import androidx.appcompat.app.AppCompatActivity;
import androidx.annotation.NonNull;

import android.os.AsyncTask;
import android.os.Bundle;

import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.Toast;


import com.google.gson.Gson;

import java.util.ArrayList;

import java.util.HashMap;


import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import java.util.ArrayList;

public class TeamInfo extends AppCompatActivity {
    private ListView lv;

    ArrayList<HashMap<String, String>> resultList;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_team_info);

        resultList = new ArrayList<>();
        lv = (ListView) findViewById(R.id.list);
        new GetContacts().execute();

    }

    private class GetContacts extends AsyncTask<Void, Void, Void>{
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(TeamInfo.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
        }


        @Override
        protected Void doInBackground(Void... arg0) {
            OkHttpClient client = new OkHttpClient();

            Request request = new Request.Builder()
                    .url("https://heisenbug-premier-league-live-scores-v1.p.rapidapi.com/api/premierleague/team?name=Liverpool")
                    .get()
                    .addHeader("X-RapidAPI-Key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
                    .addHeader("X-RapidAPI-Host", "heisenbug-premier-league-live-scores-v1.p.rapidapi.com")
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    call.cancel();
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                    String jsonStr=response.body().string();
                    Log.e(TAG, "Response from url: " + jsonStr);
                    if (jsonStr != null) {
                        try {
                            JSONObject jsonObj = new JSONObject(jsonStr);

                            // Getting JSON Array node
                            JSONArray records = jsonObj.getJSONArray("records");

                            // looping through All items
                            for (int i = 0; i < records.length(); i++) {
                                JSONObject c = records.getJSONObject(i);
                                String league = c.getString("league");
                                String season = c.getString("season");
                                String name = c.getString("name");
                                String officialName = c.getString("officialName");
                                String address = c.getString("address");
                                String telephone = c.getString("telephone");
                                String fax = c.getString("fax");
                                String website = c.getString("website");
                                String founded = c.getString("founded");
                                String teamSize = c.getString("teamSize");
                                String averageAge = c.getString("averageAge");
                                String foreigners = c.getString("foreigners");
                                String nationaTeamPlayers = c.getString("nationaTeamPlayers");
                                String teamValue = c.getString("teamValue");
                                String venue = c.getString("venue");
                                String venueCapacity = c.getString("venueCapacity");

                                HashMap<String, String> result = new HashMap<>();

                                // adding each child node to HashMap key => value
                                result.put("league",league);
                                result.put("season",season);
                                result.put("name",name);
                                result.put("officialName",officialName);
                                result.put("address",address);
                                result.put("telephone",telephone);
                                result.put("fax",fax);
                                result.put("website",website);
                                result.put("founded",founded);
                                result.put("teamSize",teamSize);
                                result.put("averageAge",averageAge);
                                result.put("foreigners",foreigners);
                                result.put("nationaTeamPlayers",nationaTeamPlayers);
                                result.put("teamValue",teamValue);
                                result.put("venue",venue);
                                result.put("venueCapacity",venueCapacity);

                                resultList.add(result);


                            }
                        } catch (final JSONException e) {
                            Log.e(TAG, "Json parsing error: " + e.getMessage());
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(),
                                            "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    }else {
                        Log.e(TAG, "Couldn't get json from server.");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(),
                                        "Couldn't get json from server. Check LogCat for possible errors!",
                                        Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }
            });
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            ListAdapter adapter = new SimpleAdapter(TeamInfo.this, resultList,
                    R.layout.list_item_team, new String[]{ "league","season","name","officialName","address","telephone","fax","website","founded","teamSize","averageAge","foreigners","nationaTeamPlayers","teamValue","venue","venueCapacity"},
                    new int[]{R.id.league, R.id.season,R.id.name,R.id.officialName,R.id.address,R.id.telephone,R.id.fax,R.id.website,R.id.founded,R.id.teamSize,R.id.averageAge,R.id.foreigners,R.id.nationaTeamPlayers,R.id.teamValue,R.id.venue,R.id.venueCapacity});
            lv.setAdapter(adapter);

        }
    }
}

Hello Guys I received a a big problem in my project. I make the OkHttp request i receive response from server all is perfect. the problem is why i can't display data, i made a model item in xml and listview(this is the required view) and when i acces the page is blank.

Can anyone help me with this issue?

code for page is the following:

package com.example.socceraplication;

import static android.content.ContentValues.TAG;

import androidx.appcompat.app.AppCompatActivity;
import androidx.annotation.NonNull;

import android.os.AsyncTask;
import android.os.Bundle;

import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.Toast;


import com.google.gson.Gson;

import java.util.ArrayList;

import java.util.HashMap;


import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import java.util.ArrayList;

public class TeamInfo extends AppCompatActivity {
    private ListView lv;

    ArrayList<HashMap<String, String>> resultList;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_team_info);

        resultList = new ArrayList<>();
        lv = (ListView) findViewById(R.id.list);
        new GetContacts().execute();

    }

    private class GetContacts extends AsyncTask<Void, Void, Void>{
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(TeamInfo.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
        }


        @Override
        protected Void doInBackground(Void... arg0) {
            OkHttpClient client = new OkHttpClient();

            Request request = new Request.Builder()
                    .url("https://heisenbug-premier-league-live-scores-v1.p.rapidapi.com/api/premierleague/team?name=Liverpool")
                    .get()
                    .addHeader("X-RapidAPI-Key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
                    .addHeader("X-RapidAPI-Host", "heisenbug-premier-league-live-scores-v1.p.rapidapi.com")
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    call.cancel();
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                    String jsonStr=response.body().string();
                    Log.e(TAG, "Response from url: " + jsonStr);
                    if (jsonStr != null) {
                        try {
                            JSONObject jsonObj = new JSONObject(jsonStr);

                            // Getting JSON Array node
                            JSONArray records = jsonObj.getJSONArray("records");

                            // looping through All items
                            for (int i = 0; i < records.length(); i++) {
                                JSONObject c = records.getJSONObject(i);
                                String league = c.getString("league");
                                String season = c.getString("season");
                                String name = c.getString("name");
                                String officialName = c.getString("officialName");
                                String address = c.getString("address");
                                String telephone = c.getString("telephone");
                                String fax = c.getString("fax");
                                String website = c.getString("website");
                                String founded = c.getString("founded");
                                String teamSize = c.getString("teamSize");
                                String averageAge = c.getString("averageAge");
                                String foreigners = c.getString("foreigners");
                                String nationaTeamPlayers = c.getString("nationaTeamPlayers");
                                String teamValue = c.getString("teamValue");
                                String venue = c.getString("venue");
                                String venueCapacity = c.getString("venueCapacity");

                                HashMap<String, String> result = new HashMap<>();

                                // adding each child node to HashMap key => value
                                result.put("league",league);
                                result.put("season",season);
                                result.put("name",name);
                                result.put("officialName",officialName);
                                result.put("address",address);
                                result.put("telephone",telephone);
                                result.put("fax",fax);
                                result.put("website",website);
                                result.put("founded",founded);
                                result.put("teamSize",teamSize);
                                result.put("averageAge",averageAge);
                                result.put("foreigners",foreigners);
                                result.put("nationaTeamPlayers",nationaTeamPlayers);
                                result.put("teamValue",teamValue);
                                result.put("venue",venue);
                                result.put("venueCapacity",venueCapacity);

                                resultList.add(result);


                            }
                        } catch (final JSONException e) {
                            Log.e(TAG, "Json parsing error: " + e.getMessage());
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(),
                                            "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    }else {
                        Log.e(TAG, "Couldn't get json from server.");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(),
                                        "Couldn't get json from server. Check LogCat for possible errors!",
                                        Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }
            });
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            ListAdapter adapter = new SimpleAdapter(TeamInfo.this, resultList,
                    R.layout.list_item_team, new String[]{ "league","season","name","officialName","address","telephone","fax","website","founded","teamSize","averageAge","foreigners","nationaTeamPlayers","teamValue","venue","venueCapacity"},
                    new int[]{R.id.league, R.id.season,R.id.name,R.id.officialName,R.id.address,R.id.telephone,R.id.fax,R.id.website,R.id.founded,R.id.teamSize,R.id.averageAge,R.id.foreigners,R.id.nationaTeamPlayers,R.id.teamValue,R.id.venue,R.id.venueCapacity});
            lv.setAdapter(adapter);

        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

穿越时光隧道 2025-02-15 23:48:04

>呼叫是异步的,这意味着将来的某个时候将在后台运行,并且完成后运行

  • 启动doinbackground
  • 添加您的http呼叫到队列
  • 返回的doinbackground
  • run onpostexecute
  • post post空列表到适配器
  • ...稍后...稍后...
  • 时,请运行onResponse回调

当它获取数据解决此问题 ,您可以完全删除异步任务,然后从主线程中排队工作,因为它已经在后台处理了实际执行请求。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_team_info);

    resultList = new ArrayList<>();
    lv = (ListView) findViewById(R.id.list);
    startRequest();
}

private void startRequest() {
    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            //...
            .build();
            
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
            call.cancel();
        }

        @Override
        public void onResponse(@NonNull Call call, @NonNull Response response) { 
            showResult(response);
        }
    });
}

private void showResult(Response response) {
    // show the result here - no need to runOnUiThread
    // set the adapter, put text in views, etc from in here
}

如果您真的想在背景中从自己的异步箱打电话,则应使用同步API,而不是异步API。这意味着调用执行,而不是inqueue,如下:

// this MUST run on a background thread or it will block the UI thread
Response response = client.newCall(request).execute();

The enqueue call is asynchronous, which means it queues up work to be run in the background at some point in the future, and when it is complete then it runs the callback you supply (onResponse). This means in your case the order of calls is

  • Start doInBackground
  • Add your Http call to the queue
  • Return from doInBackground
  • Run onPostExecute
  • Post empty list to the adapter
  • ... some time later ...
  • Run the onResponse callback when it gets data

To fix this, you can remove the async task entirely and just queue the work from the main thread, since it already handles actually doing the request in the background.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_team_info);

    resultList = new ArrayList<>();
    lv = (ListView) findViewById(R.id.list);
    startRequest();
}

private void startRequest() {
    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            //...
            .build();
            
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
            call.cancel();
        }

        @Override
        public void onResponse(@NonNull Call call, @NonNull Response response) { 
            showResult(response);
        }
    });
}

private void showResult(Response response) {
    // show the result here - no need to runOnUiThread
    // set the adapter, put text in views, etc from in here
}

If you really want to make the call from your own AsyncTask in the background, you should use the synchronous API, not the asynchronous API. This means calling execute instead of enqueue, like this:

// this MUST run on a background thread or it will block the UI thread
Response response = client.newCall(request).execute();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文