I just wanna update my activity automatically when i insert or delete data in SQLite using FAB button and Delete button

huangapple go评论77阅读模式
英文:

I just wanna update my activity automatically when i insert or delete data in SQLite using FAB button and Delete button

问题

以下是已翻译的内容:

这是 MainActivity 代码:

package com.example.booklibrary;

// ... (省略了导入语句)

public class MainActivity extends AppCompatActivity {

    // ... (省略了一部分代码)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // ... (省略了部分代码)

        //method for showing data into UI
        showDataToUi();
        customAdapter = new customAdapter(this, book__id, book__title, book__author, book__pages);
        recyclerView.setAdapter(customAdapter);
        // ... (省略了部分代码)
    }

    // ... (省略了部分代码)

    private void showDataToUi() {
        Cursor cursor = myDatabaseClass.readAllData();
        if (cursor.getCount() == 0) {
            Toast.makeText(this, "No data", Toast.LENGTH_SHORT).show();
            empty_textView.setVisibility(View.VISIBLE);
            empty_image.setVisibility(View.VISIBLE);
        } else {
            while (cursor.moveToNext()) {
                book__id.add(cursor.getString(0));
                book__title.add(cursor.getString(1));
                book__author.add(cursor.getString(2));
                book__pages.add(cursor.getString(3));
            }
            empty_textView.setVisibility(View.GONE);
            empty_image.setVisibility(View.GONE);
        }
    }
}

这是 myDatabase 类:

package com.example.booklibrary;

// ... (省略了导入语句)

public class myDatabaseClass extends SQLiteOpenHelper {

    // ... (省略了一部分代码)

    @Override
    public void onCreate(SQLiteDatabase db) {
        String query = "CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COLUMN_TITLE + " TEXT, " + COLUMN_AUTHOR + " TEXT, " + COLUMN_PAGES + " INTEGER);";
        db.execSQL(query);
    }

    // ... (省略了部分代码)

    //for showing the data to the UI
    Cursor readAllData() {
        String query = "SELECT * FROM " + TABLE_NAME;
        SQLiteDatabase database = this.getReadableDatabase();
        Cursor cursor = database.query(TABLE_NAME, null, null, null, null, null, COLUMN_ID);
        if (database != null) {
            cursor = database.rawQuery(query, null);
        }
        return cursor;
    }

    // ... (省略了部分代码)
}

这是我的 Adapter 类:

package com.example.booklibrary;

// ... (省略了导入语句)

public class customAdapter extends RecyclerView.Adapter<customAdapter.MyViewHolder> implements PopupMenu.OnMenuItemClickListener {

    // ... (省略了一部分代码)

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

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) {
        holder.id.setText(book__id.get(position));
        holder.title.setText(book__title.get(position));
        holder.author.setText(book__author.get(position));
        holder.pages.setText(book__pages.get(position));

        holder.myLinerLayout.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                delete_id = book__id.get(position);
                update_id = book__id.get(position);
                update_title = book__title.get(position);
                update_author = book__author.get(position);
                update_pages = book__pages.get(position);
                longClickMenu(v);
                return true;
            }
        });
    }

    @Override
    public int getItemCount() {
        return book__id.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView id, title, author, pages;
        RelativeLayout myLinerLayout;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            id = itemView.findViewById(R.id.item_id);
            title = itemView.findViewById(R.id.item_title);
            author = itemView.findViewById(R.id.item_AuthorName);
            pages = itemView.findViewById(R.id.item_pages);
            myLinerLayout = itemView.findViewById(R.id.item_linerLayout);
        }
    }

    // ... (省略了部分代码)
}
英文:

and also when I delete any data so it just fills the gap of that data so help me what should I do in my code
https://drive.google.com/file/d/1rkM5D1WE2N-Qmqm2_DwiyLdnXDNhSSyV/view?usp=sharing this is an image here you can see 12 14 and I delete 13 so why it haven't change and if I use Intent for refresh MainActivity so the data is inserted and delete is changed but when we press the back button it moves to the previous mainActivity and data is lost.

This is MainActivity Code

 package com.example.booklibrary;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton fltButn;
AlertDialog alertDialog;
SQLiteDatabase mDatabsae;
myDatabaseClass myDatabaseClass;
ArrayList &lt; String &gt; book__id, book__title, book__author, book__pages;
customAdapter customAdapter;
RelativeLayout forsnackbar;
ImageView empty_image , main_Search ,showoff_Search;
TextInputLayout search_text;
TextView empty_textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate ( savedInstanceState );
setContentView ( R.layout.activity_main );
forsnackbar = findViewById ( R.id.main_relative );
//for emptyIamge View
empty_image  = findViewById ( R.id.empty_imageView );
empty_textView =findViewById ( R.id.empty_textView );
//for search
main_Search = findViewById ( R.id.main_search );
search_text =  findViewById ( R.id.search_editText );
//for showoffSearch
showoff_Search = findViewById ( R.id.showoff_search );
showoff_Search.setOnClickListener ( new View.OnClickListener () {
@Override
public void onClick(View v) {
showoff_Search.setVisibility ( View.GONE );
main_Search.setVisibility ( View.VISIBLE );
search_text.setVisibility ( View.VISIBLE );
}
} );
//recyclerView
recyclerView = findViewById ( R.id.recyclerView );
recyclerView.setLayoutManager ( new LinearLayoutManager ( MainActivity.this ) );
myDatabaseClass = new myDatabaseClass ( MainActivity.this );
book__id = new ArrayList &lt;&gt; ();
book__title = new ArrayList &lt;&gt; ();
book__author = new ArrayList &lt;&gt; ();
book__pages = new ArrayList &lt;&gt; ();
//method for showing data into UI
showDataToUi ();
customAdapter = new customAdapter ( this , book__id , book__title , book__author , book__pages );
recyclerView.setAdapter ( customAdapter );
//floatingAction button
fltButn = findViewById ( R.id.addFloating );
fltButn.setOnClickListener ( new View.OnClickListener () {
@Override
public void onClick(View view) {
// Toast.makeText ( MainActivity.this , &quot;Hello&quot; , Toast.LENGTH_SHORT ).show ();
fabButtonClick ();
}
} );
}
private void fabButtonClick() {
MaterialAlertDialogBuilder myDialog = new MaterialAlertDialogBuilder ( this );
LayoutInflater layoutInflater = LayoutInflater.from ( this );
View view = layoutInflater.inflate ( R.layout.add_data , null );
myDialog.setView ( view );
alertDialog = myDialog.create ();
alertDialog.setCancelable ( true );
final TextInputLayout title,author, pages;;
Button addButton;
title = view.findViewById ( R.id.Title );
author = view.findViewById ( R.id.Auther );
pages = view.findViewById ( R.id.pages );
addButton = view.findViewById ( R.id.addButton );
addButton.setOnClickListener ( new View.OnClickListener () {
@Override
public void onClick(View v) {
String bookTitle = title.getEditText ().getText ().toString ().trim ();
String bookAuthor = author.getEditText ().getText ().toString ().trim ();
String bookPages =  pages.getEditText ().getText ().toString ().trim () ;
if(bookTitle.equals ( &quot;&quot; ))
{
title.setError ( &quot;Required Field&quot; );
}
else if(bookAuthor.equals ( &quot;&quot; ))
{
author.setError ( &quot;Required Field&quot; );
}
else if(bookPages.equals ( &quot;&quot;) )
{
pages.setError (  &quot;Required Field&quot;);
}
else {
myDatabaseClass myDatabaseClass = new myDatabaseClass ( MainActivity.this );
myDatabaseClass.addBook ( bookTitle , bookAuthor , bookPages );
alertDialog.dismiss ();
//                Intent intent = new Intent ( getApplicationContext () , MainActivity.class );
//                startActivity ( intent );
Snackbar.make ( forsnackbar,&quot;Added&quot;,Snackbar.LENGTH_SHORT ).show ();
}
} });
alertDialog.show ();
//.getWindow().setLayout(1200, 900); - this work when we use a simple AlerrtDialog
}
private void showDataToUi() {
Cursor cursor = myDatabaseClass.readAllData ();
if (cursor.getCount () == 0) {
Toast.makeText ( this , &quot;No data&quot; , Toast.LENGTH_SHORT ).show ();
empty_textView.setVisibility ( View.VISIBLE );
empty_image.setVisibility ( View.VISIBLE );
} else {
while ((cursor.moveToNext ())) {
book__id.add ( cursor.getString ( 0 ) ); //here add() function is from ArrayList
book__title.add ( cursor.getString ( 1 ) );
book__author.add ( cursor.getString ( 2 ) );
book__pages.add ( cursor.getString ( 3 ) );
}
empty_textView.setVisibility ( View.GONE );
empty_image.setVisibility ( View.GONE );
}
}
}

This is myDatabse Class

package com.example.booklibrary;
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 myDatabaseClass extends SQLiteOpenHelper {
private Context context;
public static final String DATABASE_NAME = &quot;BookLibrary.DB&quot;;
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = &quot;My_Book&quot;;
public static String COLUMN_ID = &quot;_id&quot;;
public static final String COLUMN_TITLE = &quot;book_title&quot;;
public static final String COLUMN_AUTHOR = &quot;book_author&quot;;
public static final String COLUMN_PAGES = &quot;book_pages&quot;;
SQLiteDatabase mDatabase;
myDatabaseClass(@Nullable Context context) {
super ( context , DATABASE_NAME , null , DATABASE_VERSION );
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
String query = &quot; CREATE TABLE &quot; + TABLE_NAME + &quot; ( &quot; + COLUMN_ID + &quot; INTEGER PRIMARY KEY AUTOINCREMENT, &quot; + COLUMN_TITLE + &quot; TEXT, &quot; + COLUMN_AUTHOR + &quot; TEXT, &quot; + COLUMN_PAGES + &quot; INTEGER);&quot;;
db.execSQL ( query );
}
@Override
public void onUpgrade(SQLiteDatabase db , int oldVersion , int newVersion) {
db.execSQL ( &quot;DROP TABLE IF EXISTS &quot; + TABLE_NAME );
onCreate ( db );
}
//for inserting the data into table
void addBook(String title , String name , String pages) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase (); //this method in use to write the data to our table
ContentValues values = new ContentValues (); //it passs the value to our database table
values.put ( COLUMN_TITLE , title );
values.put ( COLUMN_AUTHOR , name );
values.put ( COLUMN_PAGES , pages );
long result = sqLiteDatabase.insert ( TABLE_NAME , null , values );
if (result == -1) {
Toast.makeText ( context , &quot;failed&quot; , Toast.LENGTH_SHORT ).show ();
} else {
Toast.makeText ( context , &quot; success add book&quot; , Toast.LENGTH_SHORT ).show ();
}
}
//for showing the data to the UI
Cursor readAllData() {
String query = &quot; SELECT * FROM &quot; + TABLE_NAME ;
SQLiteDatabase database = this.getReadableDatabase ();
Cursor cursor= database.query ( TABLE_NAME,null,null,null,null,null,COLUMN_ID);
if (database != null) {
cursor = database.rawQuery ( query , null );
}
return cursor;
}
//for update the data
void upadteData(String row_id , String row_title , String row_author , String row_pages) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase ();
ContentValues contentValues = new ContentValues ();
contentValues.put ( COLUMN_TITLE , row_title );
contentValues.put ( COLUMN_AUTHOR , row_author );
contentValues.put ( COLUMN_PAGES , row_pages );
long result = sqLiteDatabase.update ( TABLE_NAME , contentValues , &quot;_id=?&quot; , new String[]{row_id} );
if (result == -1) {
Toast.makeText ( context , &quot;Failed update&quot; , Toast.LENGTH_SHORT ).show ();
} else {
Toast.makeText ( context , &quot;update done&quot; , Toast.LENGTH_SHORT ).show ();
}
}
//for delete the data
void deleteData(String row_id) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase ();
long result = sqLiteDatabase.delete ( TABLE_NAME , &quot;_id= ?&quot; , new String[]{row_id} );
if (result == -1) {
Toast.makeText ( context , &quot;Failed Delete&quot; , Toast.LENGTH_SHORT ).show ();
} else {
Toast.makeText ( context , &quot;deleted done&quot; , Toast.LENGTH_SHORT ).show ();
}
}
}

This is my Adapter class

package com.example.booklibrary;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;
public class customAdapter extends RecyclerView.Adapter &lt; customAdapter.MyViewHolder &gt; implements PopupMenu.OnMenuItemClickListener {
String delete_id, update_id, update_title, update_author, update_pages;
Intent intent, inn;
private Context context;
AlertDialog alertDialog;
private ArrayList &lt; String &gt; book__id, book__title, book__author, book__pages;
public customAdapter(Context context , ArrayList &lt; String &gt; book__id , ArrayList &lt; String &gt; book__title , ArrayList &lt; String &gt; book__author , ArrayList &lt; String &gt; book__pages) {
this.context = context;
this.book__id = book__id;
this.book__title = book__title;
this.book__author = book__author;
this.book__pages = book__pages;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent , int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from ( context );
View view = layoutInflater.inflate ( R.layout.custom_adapter , null );
return new MyViewHolder ( view );
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder , final int position) {
holder.id.setText ( book__id.get ( position ) );
holder.title.setText ( book__title.get ( position ) );
holder.author.setText ( book__author.get ( position ) );
holder.pages.setText ( book__pages.get ( position ) );
holder.myLinerLayout.setOnLongClickListener ( new View.OnLongClickListener () {
@Override
public boolean onLongClick(View v) {
//for delete the item
delete_id = book__id.get ( position );
update_id = book__id.get ( position );
update_title = book__title.get ( position );
update_author = book__author.get ( position );
update_pages = book__pages.get ( position );
longClickMenu ( v );
return true;
}
} );
}
@Override
public int getItemCount() {
return book__id.size ();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView id, title, author, pages;
RelativeLayout myLinerLayout;
public MyViewHolder(@NonNull View itemView) {
super ( itemView );
id = itemView.findViewById ( R.id.item_id );
title = itemView.findViewById ( R.id.item_title );
author = itemView.findViewById ( R.id.item_AuthorName );
pages = itemView.findViewById ( R.id.item_pages );
myLinerLayout = itemView.findViewById ( R.id.item_linerLayout );
}
}
private void longClickMenu(View view) // View must be pasing
{
PopupMenu popupMenu = new PopupMenu ( view.getContext () , view );
popupMenu.inflate ( R.menu.popup_menu );
popupMenu.setOnMenuItemClickListener ( customAdapter.this );
popupMenu.show ();
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId ()) {
case R.id.edit_item:
//context.startActivity ( intent );
editButtonClick ();
return true;
case R.id.delete_item:
Toast.makeText ( context , &quot;click delete&quot; , Toast.LENGTH_SHORT ).show ();
myDatabaseClass myDatabaseClass = new myDatabaseClass ( context );
myDatabaseClass.deleteData ( delete_id );
Intent intent = new Intent ( context , MainActivity.class );
context.startActivity ( intent );
return true;
default:
return false;
}
}
private void editButtonClick() {
AlertDialog.Builder myDialog = new AlertDialog.Builder ( context );
LayoutInflater layoutInflater = LayoutInflater.from ( context );
View view = layoutInflater.inflate ( R.layout.add_data , null );
myDialog.setView ( view );
alertDialog = myDialog.create ();
alertDialog.setCancelable ( true );
final TextInputLayout updateTitle, updateAuthor, updatePages;
updateTitle = view.findViewById ( R.id.Title );
updateAuthor = view.findViewById ( R.id.Auther );
updatePages = view.findViewById ( R.id.pages );
updateTitle.getEditText ().setText ( update_title );
updateAuthor.getEditText ().setText ( update_author );
updatePages.getEditText ().setText ( update_pages );
Log.d ( &quot;update thing &quot; , update_id );
Button updatebutton = view.findViewById ( R.id.addButton );
updatebutton.setOnClickListener ( new View.OnClickListener () {
@Override
public void onClick(View v) {
myDatabaseClass myDatabaseClass = new myDatabaseClass ( context );
myDatabaseClass.upadteData ( update_id , updateTitle.getEditText ().getText ().toString () , updateAuthor.getEditText ().getText ().toString () , updatePages.getEditText ().getText ().toString () );
inn = new Intent ( context , MainActivity.class );
context.startActivity ( inn );
}
} );
alertDialog.show ();
}
}

答案1

得分: 1

你可以使用 notifyDataSetChanged();

在你的 FloatingActionButton(fab)的点击事件中添加以下代码:

customAdapter.notifyDataSetChanged();

对于删除行的操作,可以使用以下代码:

book_id.remove(position);
customAdapter.notifyItemRemoved(position);
customAdapter.notifyItemRangeChanged(position, book_id.size());

就是这样。

更新:

package com.example.booklibrary;

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

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputLayout;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    FloatingActionButton fltButn;
    AlertDialog alertDialog;
    SQLiteDatabase mDatabsae;
    myDatabaseClass myDatabaseClass;
    ArrayList<String> book__id, book__title, book__author, book__pages;
    customAdapter customAdapter;
    RelativeLayout forsnackbar;
    ImageView empty_image, main_Search, showoff_Search;
    TextInputLayout search_text;
    TextView empty_textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        forsnackbar = findViewById(R.id.main_relative);

        //for emptyIamge View
        empty_image = findViewById(R.id.empty_imageView);
        empty_textView = findViewById(R.id.empty_textView);

        //for search
        main_Search = findViewById(R.id.main_search);
        search_text = findViewById(R.id.search_editText);

        //for showoffSearch
        showoff_Search = findViewById(R.id.showoff_search);
        showoff_Search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showoff_Search.setVisibility(View.GONE);
                main_Search.setVisibility(View.VISIBLE);
                search_text.setVisibility(View.VISIBLE);
            }
        });

        //recyclerView
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));

        myDatabaseClass = new myDatabaseClass(MainActivity.this);
        book__id = new ArrayList<>();
        book__title = new ArrayList<>();
        book__author = new ArrayList<>();
        book__pages = new ArrayList<>();

        //将数据显示在UI上的方法
        showDataToUi();
        customAdapter = new customAdapter(this, book__id, book__title, book__author, book__pages);
        recyclerView.setAdapter(customAdapter);
        //floatingActionButton
        fltButn = findViewById(R.id.addFloating);
        fltButn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Toast.makeText(MainActivity.this, "Hello", Toast.LENGTH_SHORT).show();
                fabButtonClick();
            }
        });

    }

    //其他方法...
}
英文:

You can use notifyDataSetChanged();

Inside your fab onClick add this

customAdapter.notifyDataSetChanged();

And deleting the rows use

book_id.remove(position);
notifyItemRemoved(position);                 
notifyItemRangeChanged(position, book_id.size());

That's it

Update :

            package com.example.booklibrary;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton fltButn;
AlertDialog alertDialog;
SQLiteDatabase mDatabsae;
myDatabaseClass myDatabaseClass;
ArrayList &lt; String &gt; book__id, book__title, book__author, book__pages;
customAdapter customAdapter;
RelativeLayout forsnackbar;
ImageView empty_image , main_Search ,showoff_Search;
TextInputLayout search_text;
TextView empty_textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate ( savedInstanceState );
setContentView ( R.layout.activity_main );
forsnackbar = findViewById ( R.id.main_relative );
//for emptyIamge View
empty_image  = findViewById ( R.id.empty_imageView );
empty_textView =findViewById ( R.id.empty_textView );
//for search
main_Search = findViewById ( R.id.main_search );
search_text =  findViewById ( R.id.search_editText );
//for showoffSearch
showoff_Search = findViewById ( R.id.showoff_search );
showoff_Search.setOnClickListener ( new View.OnClickListener () {
@Override
public void onClick(View v) {
showoff_Search.setVisibility ( View.GONE );
main_Search.setVisibility ( View.VISIBLE );
search_text.setVisibility ( View.VISIBLE );
}
} );
//recyclerView
recyclerView = findViewById ( R.id.recyclerView );
recyclerView.setLayoutManager ( new LinearLayoutManager ( MainActivity.this ) );
myDatabaseClass = new myDatabaseClass ( MainActivity.this );
book__id = new ArrayList &lt;&gt; ();
book__title = new ArrayList &lt;&gt; ();
book__author = new ArrayList &lt;&gt; ();
book__pages = new ArrayList &lt;&gt; ();
//method for showing data into UI
showDataToUi ();
customAdapter = new customAdapter ( this , book__id , book__title , book__author , book__pages );
recyclerView.setAdapter ( customAdapter );
//floatingAction button
fltButn = findViewById ( R.id.addFloating );
fltButn.setOnClickListener ( new View.OnClickListener () {
@Override
public void onClick(View view) {
// Toast.makeText ( MainActivity.this , &quot;Hello&quot; , Toast.LENGTH_SHORT ).show ();
fabButtonClick ();
}
} );
}
private void fabButtonClick() {
MaterialAlertDialogBuilder myDialog = new MaterialAlertDialogBuilder ( this );
LayoutInflater layoutInflater = LayoutInflater.from ( this );
View view = layoutInflater.inflate ( R.layout.add_data , null );
myDialog.setView ( view );
alertDialog = myDialog.create ();
alertDialog.setCancelable ( true );
final TextInputLayout title,author, pages;;
Button addButton;
title = view.findViewById ( R.id.Title );
author = view.findViewById ( R.id.Auther );
pages = view.findViewById ( R.id.pages );
addButton = view.findViewById ( R.id.addButton );
addButton.setOnClickListener ( new View.OnClickListener () {
@Override
public void onClick(View v) {
String bookTitle = title.getEditText ().getText ().toString ().trim ();
String bookAuthor = author.getEditText ().getText ().toString ().trim ();
String bookPages =  pages.getEditText ().getText ().toString ().trim () ;
if(bookTitle.equals ( &quot;&quot; ))
{
title.setError ( &quot;Required Field&quot; );
}
else if(bookAuthor.equals ( &quot;&quot; ))
{
author.setError ( &quot;Required Field&quot; );
}
else if(bookPages.equals ( &quot;&quot;) )
{
pages.setError (  &quot;Required Field&quot;);
}
else {
myDatabaseClass myDatabaseClass = new myDatabaseClass ( MainActivity.this );
myDatabaseClass.addBook ( bookTitle , bookAuthor , bookPages );
alertDialog.dismiss ();
//                Intent intent = new Intent ( getApplicationContext () , MainActivity.class );
//                startActivity ( intent );
Snackbar.make ( forsnackbar,&quot;Added&quot;,Snackbar.LENGTH_SHORT ).show ();
//Added
showDataToUi
customAdapter.notifyDataSetChanged();
}
} });
alertDialog.show ();
//.getWindow().setLayout(1200, 900); - this work when we use a simple AlerrtDialog
}
private void showDataToUi() {
Cursor cursor = myDatabaseClass.readAllData ();
if (cursor.getCount () == 0) {
Toast.makeText ( this , &quot;No data&quot; , Toast.LENGTH_SHORT ).show ();
empty_textView.setVisibility ( View.VISIBLE );
empty_image.setVisibility ( View.VISIBLE );
} else {
while ((cursor.moveToNext ())) {
book__id.add ( cursor.getString ( 0 ) ); //here add() function is from ArrayList
book__title.add ( cursor.getString ( 1 ) );
book__author.add ( cursor.getString ( 2 ) );
book__pages.add ( cursor.getString ( 3 ) );
}
empty_textView.setVisibility ( View.GONE );
empty_image.setVisibility ( View.GONE );
}
}
}

答案2

得分: 0

@jerson

这是我的浮动按钮点击代码但当我们添加新数据时RecyclerView 不会改变

// 浮动操作按钮
fltButn = findViewById(R.id.addFloating);
fltButn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        // Toast.makeText(MainActivity.this, "Hello", Toast.LENGTH_SHORT).show();
        fabButtonClick();
        customAdapter.notifyDataSetChanged();
    }
});

以下是适配器类中的删除按钮代码

switch (item.getItemId()) {
    case R.id.delete_item:
        Toast.makeText(context, "点击删除", Toast.LENGTH_SHORT).show();
        myDatabaseClass myDatabaseClass = new myDatabaseClass(context);
        myDatabaseClass.deleteData(delete_id);

        book__id.remove(postionForDelete);
        notifyItemRemoved(postionForDelete);
        notifyItemRangeChanged(postionForDelete, book__id.size());
        notifyDataSetChanged();
        return true;
}

此代码粘贴在 onBindViewHolder 类中我将位置存储到 postionForDelete 变量中但它删除了其他 id 的数据

this.postionForDelete = position;
英文:

@jerson

Here is my Fab button clik code but when we add new data the recyclerView is not changing.

 //floatingAction button
fltButn = findViewById ( R.id.addFloating );
fltButn.setOnClickListener ( new View.OnClickListener () {
@Override
public void onClick(View view) {
// Toast.makeText ( MainActivity.this , &quot;Hello&quot; , Toast.LENGTH_SHORT ).show ();
fabButtonClick ();
customAdapter.notifyDataSetChanged();
}
} );

and Here is my delete button code in adapter class

case R.id.delete_item:
Toast.makeText ( context , &quot;click delete&quot; , Toast.LENGTH_SHORT ).show ();
myDatabaseClass myDatabaseClass = new myDatabaseClass ( context );
myDatabaseClass.deleteData ( delete_id );
book__id.remove (postionForDelete);
notifyItemRemoved(postionForDelete);
notifyItemRangeChanged(postionForDelete, book__id.size());
notifyDataSetChanged ();
return true;

and this code is paste in onBindViewHolder class ,m storing the postion into postionForDelete var.But its deleting the other id data.

this.postionForDelete =  position;

huangapple
  • 本文由 发表于 2020年9月24日 15:46:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/64041757.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定