Android Studio - 对 Textview 的数据库提取未正确显示

Posted

技术标签:

【中文标题】Android Studio - 对 Textview 的数据库提取未正确显示【英文标题】:Android Studio - Database fetch to Textview not displaying correctly 【发布时间】:2021-05-25 05:51:43 【问题描述】:

我正在尝试显示从数据库中的表中读取的内容,到目前为止我编写的内容通过了 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上的一个textview

手机示例:

activity.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_
    android:layout_
    android:background="@color/black"
    android:clickable="true"
    tools:context=".MainActivity"
    tools:ignore="ExtraText"
    android:focusable="true">

    >

    <ImageView
        android:id="@+id/imageView2"
        android:layout_
        android:layout_
        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_
        android:layout_
        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_
        android:layout_
        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_
        android:layout_
        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_
        android:layout_
        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_
        android:layout_
        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>

【问题讨论】:

我建议对 textView 等变量使用驼峰式大小写。此外,我没有在您的代码中看到任何 textVew.setText(s) 调用。您正在显示吐司而不是调用 textView.setText(s)。 我该如何解决这个问题? 【参考方案1】:

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

textView.setText(json);

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

【讨论】:

我在这里添加了它:private void settextView(String json) throws JSONException JSONArray jsonArray = new JSONArray(json); String[] tasks = new String[jsonArray.length()]; for (int i = 0; i &lt; jsonArray.length(); i++) JSONObject obj = jsonArray.getJSONObject(i); tasks[i] = obj.getString("Task_title") + " " + obj.getString("task_description"); textView.setText(json); 但仍然显示吐司,有什么想法吗? 要删除toast,你只需要删除onPostExecute()中的行:Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show(); 对不起,我的意思是,即使我删除了 toast,我想在 textview 中显示的文本也没有显示。我要做的就是在 .xml 文件的文本视图中显示来自数据库的文本 在这种情况下,您的布局可能有问题(如果没有崩溃)。你能告诉我们activity_tasks.xml吗? 编辑:文本现在显示在正确的位置,但它仍然显示如下“[“Task_title”:“做一个引导冥想”,“task_description”:“也许这个由Puff Daddy?”] - 什么时候应该是“做引导冥想。也许这是 Puff Daddy 的?”它没有正确显示数据。

以上是关于Android Studio - 对 Textview 的数据库提取未正确显示的主要内容,如果未能解决你的问题,请参考以下文章

Android Studio安装教程及调试(对新手友好简单实用)

android studio aar能加密吗

Android studio对图片存取

Android studio中HTTP协议代理怎么设置

对Android Studio 中Android 类型的目录结构的解析

Android studio多个项目之间怎么实现快速切换?