简体   繁体   English

如何从 recyclerView 中的项目获取数据并在 editTexts 上的不同活动中查看它

[英]How to get data from an item in a recyclerView and view it in a different activity on editTexts

When the user logins an activity where the user can create their account opens (CreateProfileActivity).当用户登录用户可以创建其帐户的活动时,将打开 (CreateProfileActivity)。 When the profile is created the user is redirected to the recyclerView activity where their profile info is displayed in a recyclerView.创建配置文件后,用户将被重定向到 recyclerView 活动,其中他们的配置文件信息显示在 recyclerView 中。 When user clicks on the item in recyclerView the Update Activity will open.当用户单击 recyclerView 中的项目时,更新活动将打开。 I want their profile information from the recyclerView to load on the Update Activity.我希望他们的个人资料信息从 recyclerView 加载到更新活动中。 Please help.请帮忙。

PS Since I haven't made the CreateProfile_Activity open only once, as I don't want the user to create more than one profile, So for now: I ran the app once and created an account and then I changed it so now when the user logins it opens the recyclerView_Activity. PS 由于我没有只打开一次 CreateProfile_Activity,因为我不希望用户创建多个配置文件,所以现在:我运行了一次应用程序并创建了一个帐户,然后我现在更改了它,当用户登录它会打开 recyclerView_Activity。

Here is the recyclerView_Activity这是recyclerView_Activity

package com.example.insert_update_activity;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class recyclerView_Activity extends AppCompatActivity {

   // Button insertBtn;
    RecyclerView recyclerView;
    DBHelper myDB;
    ArrayList<String> temp_id, temp_name, temp_age;
    myAdapter myAdapter;

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

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
 /*       insertBtn = (Button) findViewById(R.id.insertBtn);

        insertBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(recyclerView_Activity.this, Insert_Activity.class);
                startActivity(intent);
            }
        });*/

        myDB = new DBHelper(recyclerView_Activity.this);

        temp_id = new ArrayList<>();
        temp_name = new ArrayList<>();
        temp_age = new ArrayList<>();

        storeDataInArrays();

        myAdapter = new myAdapter(recyclerView_Activity.this, this, temp_id, temp_name, temp_age);
        recyclerView.setAdapter(myAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView_Activity.this));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1)
        {
            recreate();
        }
    }

    void storeDataInArrays() {
        Cursor cursor = myDB.readData();  // Cursor cursor = myDB.readAllData();

        if (cursor.getCount() == 0)
        {
            Toast.makeText(recyclerView_Activity.this, "No Data", Toast.LENGTH_SHORT).show();
        }
        else
        {
            while (cursor.moveToNext()) {

                temp_id.add(cursor.getString(0));
                temp_name.add(cursor.getString(1));
                temp_age.add(cursor.getString(2));


            }
        }
    }
}

Here is the UpdateActivity这是更新活动

package com.example.insert_update_activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class Update_Activity extends AppCompatActivity {

    EditText name, age;
    Button updateBtn;
    String id;

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

        name = (EditText) findViewById(R.id.edit_name);
        age = (EditText) findViewById(R.id.edit_age);
        updateBtn = (Button) findViewById(R.id.updateBtn);

        updateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String sName = name.getText().toString().trim();
                String sAge = age.getText().toString().trim();
                DBHelper db = new DBHelper(Update_Activity.this);

                db.updateData(id, sName, sAge);

                Intent intent = new Intent(Update_Activity.this, com.example.insert_update_activity.recyclerView_Activity.class);
                startActivity(intent);
            }
        });
        getAndSetIntentData();

    }

    void getAndSetIntentData() {
        if (getIntent().hasExtra("id") && getIntent().hasExtra("Name") && getIntent().hasExtra("Age"))
        {
            // Getting data from Intent
            id = getIntent().getStringExtra("id");
            String NAME = getIntent().getStringExtra("Name");
            String AGE = getIntent().getStringExtra("Age");

            // Setting Intent Data
            name.setText(NAME);
            age.setText(AGE);
        }
        else
        {
            Toast.makeText(Update_Activity.this, "No Data", Toast.LENGTH_SHORT).show();
        }
    }
}

Here is the DBHelper这是 DBHelper

package com.example.insert_update_activity;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class DBHelper extends SQLiteOpenHelper {

    private Context context;
    private static final String DATABASE_NAME = "Database.db";
    private static final int DATABASE_VERSION = 1;

    // Create table
    private static final String TABLE_TEMP = "TEMPP";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_NAME = "name";
    private static final String COLUMN_AGE = "age";

    public DBHelper(@Nullable Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String profileQuery = "CREATE TABLE " + TABLE_TEMP +
                " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COLUMN_NAME + " TEXT, " + COLUMN_AGE + " INTEGER " + ")";
        db.execSQL(profileQuery);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEMP);
        onCreate(db);


    }

    // Functions for TEMP TABLE ********************************************************************************************************************************************  PROFILE TEMP
    public Boolean insertData(String name, String age) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        cv.put(COLUMN_NAME, name);
        cv.put(COLUMN_AGE, age);

        long result = db.insert(TABLE_TEMP, null, cv);

        if (result == -1) {
            Toast.makeText(context, "Failed to Insert", Toast.LENGTH_SHORT).show();
            return  false;
        } else {
            Toast.makeText(context, "Data Inserted Successfully!", Toast.LENGTH_SHORT).show();
            return true;
        }
    }

    Cursor readData() {
        String query = "SELECT * FROM " + TABLE_TEMP;
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = null;

        if (db != null) {
            cursor = db.rawQuery(query, null);
        }
        return cursor;
    }

    // Update data using where clause;
    public Boolean updateData(String row_id, String name, String age)
    {
        SQLiteDatabase db = this.getWritableDatabase(); // SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        cv.put(COLUMN_NAME, name);
        cv.put(COLUMN_AGE, age);

        long result = db.update(TABLE_TEMP, cv, COLUMN_ID + " =? ", new String[]{row_id});
       
        if (result == -1)
        {
            Toast.makeText(context, "Failed to Update",  Toast.LENGTH_SHORT).show();
            return false;
        }
        else
        {
            Toast.makeText(context, "Successfully Updated!",  Toast.LENGTH_SHORT).show();
            return true;
        }

    }


}

Here is the Adapter这是适配器

package com.example.insert_update_activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class myAdapter extends RecyclerView.Adapter<myAdapter.MyViewHolder> {

    private Context context;
    Activity activity;
    private ArrayList id, name, age;

    myAdapter(Activity activity, Context context, ArrayList id, ArrayList name, ArrayList age) {

        this.activity = activity;
        this.context = context;
        this.id = id;
        this.name = name;
        this.age = age;

    }
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.my_row, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) {
        holder.id_txt.setText(String.valueOf(id.get(position)));
        holder.name_txt.setText(String.valueOf(name.get(position)));
        holder.age_txt.setText(String.valueOf(age.get(position)));
        holder.mainLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, Update_Activity.class);
                intent.putExtra("id", String.valueOf(id.get(position)));
                intent.putExtra("name", String.valueOf(name.get(position)));
                intent.putExtra("age", String.valueOf(age.get(position)));
                activity.startActivityForResult(intent, 1);
            }
        });

    }

    @Override
    public int getItemCount() {

        return id.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        TextView id_txt, name_txt, age_txt;
        LinearLayout mainLayout;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);

            id_txt = itemView.findViewById(R.id.id_txt);
            name_txt = itemView.findViewById(R.id.name_txt);
            age_txt = itemView.findViewById(R.id.age_txt);
            mainLayout = itemView.findViewById(R.id.mainLayout);

        }
    }
}

And here is the xml file my_row for the recyclerView这是用于 recyclerView 的 xml 文件 my_row

<?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="wrap_content"
    android:orientation="vertical"
    android:id="@+id/mainLayout">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:outlineSpotShadowColor="#000000"
        app:cardElevation="3dp">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="12dp">

            <TextView
                android:id="@+id/id_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dp"
                android:text="1"
                android:textColor="#9A9797"
                android:textSize="35dp"
                android:textStyle="bold"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/nameTitle"
                android:layout_width="90dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:text="NAME:"
                android:textColor="#000"
                android:textSize="16sp"
                android:textStyle="bold"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/ageTitle"
                android:layout_width="90dp"
                android:layout_height="wrap_content"
                android:text="AGE:"
                android:textColor="#000"
                android:textSize="16sp"
                android:textStyle="bold"
                app:layout_constraintStart_toStartOf="@+id/nameTitle"
                app:layout_constraintTop_toBottomOf="@+id/nameTitle" />

            <TextView
                android:id="@+id/name_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Name"
                android:textSize="15sp"
                app:layout_constraintStart_toEndOf="@+id/nameTitle"
                app:layout_constraintTop_toTopOf="@+id/nameTitle" />

            <TextView
                android:id="@+id/age_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Age"
                android:textSize="15sp"
                app:layout_constraintStart_toEndOf="@+id/ageTitle"
                app:layout_constraintTop_toBottomOf="@+id/nameTitle" />


        </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.cardview.widget.CardView>

</LinearLayout>

The login activity is pretty simple.登录活动非常简单。 It just allows the user to login if username == "User1" and password == "123456".如果用户名==“User1”和密码==“123456”,它只允许用户登录。 The CreateProfile_Activity just uses the insertData once CreateProfile_Activity 只使用一次 insertData

Okay so now it works.好的,现在它可以工作了。 I'm not sure this is why, but I will post the changes I made.我不确定这是为什么,但我会发布我所做的更改。

So one problem was in myAdapter.所以一个问题出在 myAdapter 中。 In the mainLayout OnClick the "name" and "age" where different from the "Name" and "Age" in the UpdateActivity where I get data from Intent.在 mainLayout OnClick 中,“姓名”和“年龄”与我从 Intent 获取数据的 UpdateActivity 中的“姓名”和“年龄”不同。 The first letters of both 'age' and 'name' were not in CAPITALS. “年龄”和“姓名”的第一个字母都不是大写字母。 Another thing I changed was the get(position) in the onBindHolder.我更改的另一件事是 onBindHolder 中的 get(position)。

Now the onBindHolder looks like this:现在 onBindHolder 看起来像这样:

public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) {
    holder.id_txt.setText(String.valueOf(id.get(holder.getAdapterPosition())));
    holder.name_txt.setText(String.valueOf(name.get(holder.getAdapterPosition())));
    holder.age_txt.setText(String.valueOf(age.get(holder.getAdapterPosition())));


    holder.mainLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(v.getContext(), Update_Activity.class);
            intent.putExtra("id", String.valueOf(id.get(holder.getAdapterPosition())));
            intent.putExtra("Name", String.valueOf(name.get(holder.getAdapterPosition())));
            intent.putExtra("Age", String.valueOf(age.get(holder.getAdapterPosition())));
            v.getContext().startActivity(intent);
            //activity.startActivityForResult(intent, 1);
        }
    });

}

Hope it helps anyone希望它可以帮助任何人

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM