首页 > 解决方案 > Android Studio - 对 Textview 的数据库提取未正确显示

问题描述

我正在尝试显示从数据库中的表读取的内容,到目前为止我所写的内容通过了 json,但是没有在 textview 中显示 - 它显示为一个简短的弹出窗口,然后消失。

Activity_tasks.java

package com.example.myapp;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;



public class activity_tasks extends AppCompatActivity {

    TextView TextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tasks);

        Button button = findViewById(R.id.button1);
        button.setOnClickListener(v -> showInfo());
        TextView = findViewById(R.id.textView4);
        downloadJSON();
    }

    private void downloadJSON() {


        @SuppressLint("StaticFieldLeak")
        class DownloadJSON extends AsyncTask<Void, Void, String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }


            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
                try {
                    setTextView(s);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected String doInBackground(Void... voids) {
                try {
                    URL url = new URL("https://myurl.php");
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String json;
                    while ((json = bufferedReader.readLine()) != null) {
                        sb.append(json).append("\n");
                    }
                    return sb.toString().trim();
                } catch (Exception e) {
                    return null;
                }
            }
        }
        DownloadJSON getJSON = new DownloadJSON();
        getJSON.execute();
    }

    private void setTextView(String json) throws JSONException {
        JSONArray jsonArray = new JSONArray(json);
        String[] tasks = new String[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            tasks[i] = obj.getString("Task_title") + " " + obj.getString("task_description");
        }


    }

    private void showInfo() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogStyle);
        builder.setIcon(R.drawable.alert);
        builder.setTitle(" ");
        builder.setMessage("Lockdown sucks, we know.\nThat's why we created W2D.\n\nOver the comings weeks/months, we'll be adding some cool stuff here. So bear with...\n\nStay Home\nProtect the NHS\nSave Lives");

        // Create and show the AlertDialog
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }
}

我有一种有趣的感觉,这与我在代码中也有一个请求弹出窗口的按钮有关,也许我没有正确集成第二个 onCreate?

以上链接到activity_tasks.xml 上的文本视图

手机上的例子: 数据显示不正确

活动.xml 下面:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
       android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    android:clickable="true"
    tools:context=".MainActivity"
    tools:ignore="ExtraText"
    android:focusable="true">

    >

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="95dp"
        android:layout_height="90dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.946"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.022"
        app:srcCompat="@drawable/shortlogo"
        tools:ignore="ContentDescription" />

    <Button
        android:id="@+id/button"
        android:layout_width="158dp"
        android:layout_height="153dp"
        android:background="@drawable/circlebutton"
        android:text="@string/hit_me_again"
        android:textColor="#000"
        android:textSize="8sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.896" />

    <Button
        android:id="@+id/button1"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="@drawable/alert"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.077"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.06" />


    <TextView
        android:id="@+id/textView4"
        android:layout_width="183dp"
        android:layout_height="119dp"
        android:textColor="@color/white"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:paddingBottom="5dp"
        android:text="@string/design"
        android:textColor="@color/grey"
        android:textSize="12sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.092"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:paddingBottom="5dp"
        android:text="@string/version_0_0_1"
        android:textColor="@color/grey"
        android:textSize="12sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.963"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

标签: javaandroidarraysjsonandroid-studio

解决方案


您在底部看到的是您在其中创建的吐司onPostExecute()。您收到数据,但从不更新 TextView 的文本。你setTextView()也可以这样做:

textView.setText(json);

另一方面:不要再使用AsyncTasks 了。它们已被弃用并且太费力了。此外,为了更轻松地阅读 Json,您可以使用 Gson 或 Moshi 之类的库。


推荐阅读