有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何向TextView显示JSON对象?任何建议都将不胜感激

我想将从newsapi返回的json数据的标题显示到textview。有没有正确的方法?返回每篇文章的标题,我知道这是因为在for循环日志中。i(“Titles,title”)将所需的标题输出到logcat。我只需要以某种方式将它们转换为文本视图或任何允许用户查看标题的方式。谨致问候, 罗布

public class quotesPage extends AppCompatActivity {

    String FactsUrl;
    Button goButton;
    TextView displayBox;
    String [] array;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quotes_page);



        goButton = findViewById(R.id.button1);
        displayBox = findViewById(R.id.textView4);

        goButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                FactsUrl = "https://newsapi.org/v2/top-headlines?country=gb&category=health&apiKey=2b3d6472849543e4a908f43cf5c77410";
                //displayBox.setText("THIS IS JUST A TEST ");
                new quotesPage.AsyncHttpTask().execute(FactsUrl);
            }
        });

    }
    public class AsyncHttpTask extends AsyncTask<String, Void, String>
    {

        @Override
        protected String doInBackground(String... urls)
        {
            String result = "";
            URL url;
            HttpURLConnection urlConnection = null;

            try {
                url = new URL (urls[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                String response = streamToString(urlConnection.getInputStream());
                parseResult(response);
                return result;


            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }
    }

    String streamToString(InputStream stream) throws IOException
    {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
        String data;
        String result = "";

        while ((data = bufferedReader.readLine()) != null)
        {
            result += data;
        }
        if (null != stream)
        {
            stream.close();
        }

        return result;

    }

    public void parseResult(String result)
    {
        JSONObject response = null;
        try {
            response = new JSONObject(result);
            JSONArray articles = response.optJSONArray("articles");

            for (int i = 0; i < articles.length(); i++)
            {
                JSONObject article = articles.optJSONObject(i);
                String title = article.optString("title");
                Log.i("Titles", title);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}

活动\引用\页面。xml

<?xml version="1.0" encoding="utf-8"?>
<安卓.support.constraint.ConstraintLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:app="http://schemas.安卓.com/apk/res-auto"
    xmlns:tools="http://schemas.安卓.com/tools"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    安卓:background="@安卓:color/holo_orange_dark"
    tools:context=".quotesPage">

    <LinearLayout
        安卓:id="@+id/linearLayout1"
        安卓:layout_width="match_parent"
        安卓:layout_height="445dp"
        安卓:orientation="vertical">

        <TextView
            安卓:id="@+id/textView3"
            安卓:layout_width="match_parent"
            安卓:layout_height="wrap_content"
            安卓:fontFamily="@font/baloo"
            安卓:text="Click the GO! button to see uk health news headlines!"
            安卓:textAlignment="center"
            安卓:textColor="@安卓:color/black"
            安卓:textSize="24sp" />

        <Button
            安卓:id="@+id/button1"
            安卓:layout_width="100dp"
            安卓:layout_height="wrap_content"
            安卓:layout_marginLeft="130dp"
            安卓:layout_marginRight="130dp"
            安卓:background="?attr/colorButtonNormal"
            安卓:fontFamily="@font/baloo"
            安卓:text="Go!"
            安卓:textSize="24sp"
            安卓:visibility="visible" />

        <TextView
            安卓:id="@+id/textView4"
            安卓:layout_width="wrap_content"
            安卓:layout_height="wrap_content"
            安卓:text="TextView" />

    </LinearLayout>

    <LinearLayout
        安卓:id="@+id/linearLayout2"
        安卓:layout_width="344dp"
        安卓:layout_height="62dp"
        安卓:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent">

        <ImageButton
            安卓:id="@+id/imageButton1"
            安卓:layout_width="match_parent"
            安卓:layout_height="match_parent"
            安卓:layout_weight="1"
            安卓:background="@安卓:color/holo_orange_dark"
            app:srcCompat="@drawable/leftarrowlarge" />

        <ImageButton
            安卓:id="@+id/imageButton3"
            安卓:layout_width="match_parent"
            安卓:layout_height="match_parent"
            安卓:layout_weight="1"
            安卓:background="@安卓:color/holo_orange_dark"
            app:srcCompat="@drawable/timerlarge" />

        <ImageButton
            安卓:id="@+id/imageButton2"
            安卓:layout_width="match_parent"
            安卓:layout_height="match_parent"
            安卓:layout_weight="1"
            安卓:background="@安卓:color/holo_orange_dark"
            app:srcCompat="@drawable/rightarrowlarge" />
    </LinearLayout>

</安卓.support.constraint.ConstraintLayout>

id要做的是在“parseResult”for循环中执行以下操作:

显示框。追加(显示框+标题)


共 (2) 个答案

  1. # 1 楼答案

    我通常创建一个模型,以便轻松地解析和使用网络数据

    public class ModelArticleList {
        List<ModelArticle> list;
    
        public List<ModelArticle> getList() {
            return list;
        }
    
        public void parseData(String s) {
            JSONObject jsonObject;
            try {
                jsonObject = new JSONObject(s);
                JSONArray articles = jsonObject.optJSONArray("articles");
                for (int i = 0; i < articles.length(); i++)
                {
                    JSONObject article = articles.optJSONObject(i);
                    ModelArticle modelArticle = new ModelArticle();
                    modelArticle.parseData(article);
                    list.add(modelArticle);
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    public class ModelArticle {
    
        String title;
    
        public String getTitle() {
            return title;
        }
    
        void parseData(JSONObject jsonObject) {
            if(jsonObject != null) {
                title = jsonObject.optString("title");
            }
        }
    }
    

    现在根据需要使用列表视图或回收器视图来显示标题

  2. # 2 楼答案

    罗布

    进行api调用并使用json响应的行业标准是使用改型,并获得一个对象作为结果。一旦您学会了如何使用它,您将永远不会使用asyntask并自己解析json

    这里有一个关于如何做的好方法