java.lang.ClassCastException: android.support.constraint.ConstraintLayout не может быть приведен к android.widget.TextView - PullRequest
0 голосов
/ 07 декабря 2018

Так что сейчас мое приложение (сканер QR-кода) в настоящий момент падает, когда я пытаюсь его запустить.В результате появляется сообщение об ошибке отладки:

E / AndroidRuntime: FATAL EXCEPTION: main Процесс: com.example.a16007637.qrcodereader, PID: 4032 java.lang.RuntimeException: Невозможно запустить действие ComponentInfo{com.example.a16007637.qrcodereader / com.example.a16007637.qrcodereader.MainActivity}: java.lang.ClassCastException: android.support.constraint.ConstraintLayout не может быть приведен к android.widget.TextView в android.app.ActivityAunch.(ActivityThread.java:2778) в android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2856) в android.app.ActivityThread.-wrap11 (неизвестный источник: 0) в android.app.ActivityThread $ H.handleMessage (ActivityThread.Java: 1589) на android.os.Handler.dispatchMessage (Handler.java:106) на android.os.Looper.loop (Looper.java:164) на android.app.ActivityThread.main (ActivityThread.java:6494) наjava.lang.reflect.Method.invoke (собственный метод) в com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run (RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:807) Причина: java.lang.ClassCastException: android.support.constraint.ConstraintLayout нельзя привести к android.widget.TextViewна com.example.a16007637.qrcodereader.MainActivity.onCreate (MainActivity.java:33) на android.app.Activity.performCreate (Activity.java:7009) на android.app.Activity.performCreate (Activity.java:7000) наandroid.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1214) в android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2731) в android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2856) в android.app.ActivityThread.-wrap11 (неизвестный источник: 0) в android.app.ActivityThread $ H.handleMessage (ActivityThread.java:1589) в android.os.Handler.dispatchMessage (Handler.java:106) в android.os.Looper.loop (Looper.java:164) на android.app.ActivityThread.main (ActivityThread.java:6494) на java.lang.reflect.Method.invoke (собственный метод) на com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run (RuntimeInit.java:438) на com.android.internal.os.ZygoteInit.main (ZygoteInit.java:807)

Главное, что бросается в глазаэта строка здесь:

ConstraintLayout не может быть приведен к android.widget.TextView

Я пытался исследовать больше, но все ответы, которые я нашел в Интернете, не работали дляменя, к сожалению.

Мой код MainActivity.java:

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button Scan;
    private TextView QR_output;
    private IntentIntegrator ScanCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        // Defines the Scan button
        Scan = findViewById(R.id.Scan);
        // defines the output for text
        QR_output = findViewById(R.id.output);

        // looks for the user clicking "Scan"
        Scan.setOnClickListener(this);

        ScanCode = new IntentIntegrator(this);
        // Means the scan button will actually do something
        Scan.setOnClickListener(this);
    }

    // will scan the qr code and reveal its secrets
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            // if an empty QR code gets scanned it returns a message to the user
            //if qr contains data
            if (result.getContents() == null) {
                Toast.makeText(this, "This QR code is empty.", Toast.LENGTH_LONG).show();
            } else try {
                //converting the data to json
                JSONObject obj = new JSONObject(result.getContents());
                //setting values to textviews
                QR_output.setText(obj.getString("name"));
            } catch (JSONException e) {
                e.printStackTrace();
                //if control comes here
                //that means the encoded format not matches
                //in this case you can display whatever data is available on the qrcode
                //to a toast
                Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
    @Override
    public void onClick(View view) {
        //initiating the qr code scan
        ScanCode.initiateScan();
    }
}

И мой XML-файл здесь:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:id="@+id/output"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/Scan"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="148dp"
        android:layout_marginTop="514dp"
        android:layout_marginEnd="148dp"
        android:layout_marginBottom="5dp"
        android:text="@string/Scan"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <TextView
        android:id="@+id/QROutput"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="172dp"
        android:layout_marginTop="358dp"
        android:layout_marginEnd="166dp"
        android:layout_marginBottom="137dp"
        android:text="output"
        app:layout_constraintBottom_toTopOf="@+id/Scan"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Любая помощь для решения этой проблемы будет оченьоценили.

Ответы [ 2 ]

0 голосов
/ 07 декабря 2018

Вы пишете неверный идентификатор для вашего TextView.Введенный вами идентификатор указывает на объект ConstraintLayout в XML.

Вместо (строка 31):

QR_output = findViewById(R.id.output);

Напишите это:

QR_output = findViewById(R.id.QROutput);
0 голосов
/ 07 декабря 2018

Вы использовали идентификатор output для вашего корневого макета.то есть ConstraintLayout, и он даст вам ссылку ConstraintLayout.Очевидно, что ссылка ConstraintLayout не может быть сохранена в переменной типа TextView, которая, если выполнено, выдает исключение.

Используйте следующий код для ссылки на ваш TextView

QR_output = findViewById(R.id.QROutput);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...