java.lang.NoSuchMethodException: <init>[класс android.view.View]. получить эту ошибку при попытке использовать кнопку в recycleview - PullRequest
0 голосов
/ 26 мая 2019

Я пытаюсь создать пример приложения с использованием FirebaseRecyclerAdapter, но постоянно получаю сообщение об ошибке java.lang.NoSuchMethodException: [class android.view.View]

Я получаю данные из базы данных Firebase в реальном времени. Я, но в recycleview, я не могу использовать любую кнопку навигации.

Вот мой код активности:


import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.location_tracking.Users.Employee;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;

public class AdminPanelActivity extends AppCompatActivity {

    private RecyclerView mEmployeeList;

    private DatabaseReference mEmployeeDatabase;



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

        mEmployeeDatabase = FirebaseDatabase.getInstance().getReference().child("Employee");

        mEmployeeList = (RecyclerView) findViewById(R.id.recyclerViewEmplyeeList);
        mEmployeeList.setHasFixedSize(true);
        mEmployeeList.setLayoutManager(new LinearLayoutManager(this));

    }

    @Override
    protected void onStart() {
        super.onStart();

        FirebaseRecyclerAdapter<Employee, EmployeeViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Employee, EmployeeViewHolder>(
                Employee.class,
                R.layout.recycle_list_single_user,
                EmployeeViewHolder.class,
                mEmployeeDatabase
        ) {
            @Override
            protected void populateViewHolder(EmployeeViewHolder viewHolder, Employee model, int position) {

                viewHolder.setName(model.getName());
                viewHolder.setEmployeeImage(model.getImage(), getApplicationContext());
                final String user_id = getRef(position).getKey();
                viewHolder.attendanceButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(AdminPanelActivity.this,AttenadnceActivity.class));
                    }
                });


            }
        };

        mEmployeeList.setAdapter(firebaseRecyclerAdapter);

    }

    public static class EmployeeViewHolder extends RecyclerView.ViewHolder {

        View mView;

        View attendanceButton;

        public EmployeeViewHolder(@NonNull View itemView,View button) {
            super(itemView);
            mView = itemView;
            attendanceButton = (Button) button.findViewById(R.id.button_attendance);
        }

        public void setName(String name) {
            TextView EmployeeNameView = mView.findViewById(R.id.textViewSingleListName);
            EmployeeNameView.setText(name);
        }

        public void setEmployeeImage(String image, Context ctx) {
            CircleImageView EmployeeImageView = (CircleImageView) mView.findViewById(R.id.circleImageViewUserImage);

            Picasso.with(ctx).load(image).placeholder(R.drawable.user_img).into(EmployeeImageView);
        }

    }

}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.firebase:firebase-messaging:17.3.4'
    implementation 'com.google.firebase:firebase-auth:16.0.5'
    implementation 'com.google.firebase:firebase-database:16.0.4'
    implementation 'com.firebaseui:firebase-ui-database:1.2.0'


    implementation 'com.theartofdev.edmodo:android-image-cropper:2.7.+'
    implementation 'de.hdodenhof:circleimageview:2.2.0'

    implementation 'id.zelory:compressor:2.1.0'

    implementation 'com.squareup.picasso:picasso:2.5.2'

    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    implementation 'org.greenrobot:eventbus:3.0.0'

    implementation 'com.android.support:recyclerview-v7:28.0.0-alpha3'
    implementation 'com.android.support:gridlayout-v7:28.0.0-alpha3'
    implementation 'com.android.support:cardview-v7:28.0.0-alpha3'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}


Мой код 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"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#ccc"
    android:layout_margin="5dp"
    android:padding="10dp">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/circleImageViewUserImage"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:layout_marginTop="16dp"
        android:src="@drawable/user_img"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textViewSingleListName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="15dp"
        android:text="Employee Name"
        android:textColor="#000000"
        android:textStyle="bold"
        app:layout_constraintStart_toEndOf="@+id/circleImageViewUserImage"
        app:layout_constraintTop_toTopOf="@+id/circleImageViewUserImage" />

    <Button
        android:id="@+id/button_attendance"
        android:layout_width="wrap_content"
        android:layout_height="36dp"
        android:layout_marginStart="228dp"
        android:layout_marginTop="44dp"
        android:background="@color/red"
        android:padding="7dp"
        android:text="Attendence"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="36dp"
        android:layout_marginStart="72dp"
        android:layout_marginTop="44dp"
        android:background="@color/colorButton"
        android:padding="7dp"
        android:text="Show location"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</android.support.constraint.ConstraintLayout>

Recycleview

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    tools:context=".AdminPanelActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerViewEmplyeeList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="5sp">
    </android.support.v7.widget.RecyclerView>

</LinearLayout>

ОШИБКА:

    Process: com.example.location_tracking, PID: 8939
    java.lang.RuntimeException: java.lang.NoSuchMethodException: <init> [class android.view.View]
        at com.firebase.ui.database.FirebaseRecyclerAdapter.onCreateViewHolder(FirebaseRecyclerAdapter.java:171)
        at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6748)
        at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5929)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5812)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5808)
        at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
        at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
        at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3878)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3595)
        at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1842)
        at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:361)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:925)
        at android.view.Choreographer.doCallbacks(Choreographer.java:737)
        at android.view.Choreographer.doFrame(Choreographer.java:666)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:911)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:192)
        at android.app.ActivityThread.main(ActivityThread.java:6760)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)
     Caused by: java.lang.NoSuchMethodException: <init> [class android.view.View]
        at java.lang.Class.getConstructor0(Class.java:2320)
        at java.lang.Class.getConstructor(Class.java:1725)
        at com.firebase.ui.database.FirebaseRecyclerAdapter.onCreateViewHolder(FirebaseRecyclerAdapter.java:168)
        at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6748) 
        at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5929) 
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5812) 
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5808) 
        at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230) 
        at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557) 
        at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517) 
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612) 
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3878) 
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3595) 
        at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1842) 
        at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:361) 
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:925) 
        at android.view.Choreographer.doCallbacks(Choreographer.java:737) 
        at android.view.Choreographer.doFrame(Choreographer.java:666) 
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:911) 
        at android.os.Handler.handleCallback(Handler.java:790) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loop(Looper.java:192) 
        at android.app.ActivityThread.main(ActivityThread.java:6760) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826) 
2019-05-26 07:08:46.529 8939-8949/com.example.location_tracking I/zygote64: Do partial code cache collection, code=30KB, data=18KB
2019-05-26 07:08:46.530 8939-8949/com.example.location_tracking I/zygote64: After code cache collection, code=30KB, data=18KB
2019-05-26 07:08:46.530 8939-8949/com.example.location_tracking I/zygote64: Increasing code cache capacity to 128KB
2019-05-26 07:08:46.619 8939-8939/com.example.location_tracking I/Process: Sending signal. PID: 8939 SIG: 9

Ответы [ 2 ]

0 голосов
/ 26 мая 2019
  1. Согласно информации стека, возможно, потому что вы настраивали конструктор ViewHolder, но не создали экземпляр ViewHolder правильно.

  2. Это README файл FirebaseRecyclerAdapter.

  3. Если у вас есть настроенный ViewHolder, вы должны переопределить метод onCreateViewHolder, чтобы создать EmployeeViewHolder

    Вот похожая проблема Вопрос Как и у вас, его проблема в конструкторе ViewHolder, а не public, и создать ViewHolder не удалось. Таким образом, проблема в том, что настроенный экземпляр ViewHolder не был успешно создан!

Я не уверен, что это работает, но вы можете попробовать.

FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Chat, ChatHolder>(options) {
    @Override
    public ChatHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // Create a new instance of the ViewHolder, in this case we are using a custom
        // layout called R.layout.message for each item


        //replace your own layout file R.layout.recycle_list_single_user
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.message, parent, false);

        //create your own EmployeeViewHolder
        return new ChatHolder(view);
    }

    @Override
    protected void onBindViewHolder(ChatHolder holder, int position, Chat model) {
        // Bind the Chat object to the ChatHolder
        // ...
    }
};

И последнее, может быть, вам следует заменить конструктор из

EmployeeViewHolder(@NonNull View itemView,View button)

до

EmployeeViewHolder(View itemView)

, так как нет необходимости передавать второй параметр в соответствии с кодом, вы можете инициализировать attendanceButton с помощью itemView.findViewById

0 голосов
/ 26 мая 2019

Скорее всего, ваш пользовательский ViewHolder подкласс:

отсутствует конструктор public MyViewHolder(View itemView) {...}

вы должны получить свою кнопку следующим образом:

attendanceButton = (Button) itemView.findViewById(R.id.button_attendance);

вместо этого:

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