最喜欢的Recycler视图更新仅适用于重新启动的应用程序

时间:2018-02-18 20:01:52

标签: java android

我开发了一个包含英语词汇表的单词应用程序,用户可以通过单击浮动按钮添加他们喜欢的单词。每当我最喜欢的列表在列表中有一个项目时它会被更新,但是当它被清空时它不会显示任何内容,但是当我再次运行应用程序列表更新时。 如果您需要任何代码,请通知我发送。

更新: 内页:

    selectDb();

    if(selectFavoriteState()){
        favorite.setImageResource(R.drawable.ic_favorite_like);
    }else {
        favorite.setImageResource(R.drawable.ic_favorite_maylike);
    }

    favorite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (selectFavoriteState()){
                favorite.setImageResource(R.drawable.ic_favorite_maylike);
                updateUnfavorited();

            }else {
                favorite.setImageResource(R.drawable.ic_favorite_like);
                updateFavorited();

            }



        }
    });

 private void selectDb(){
    destpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
    database = SQLiteDatabase.openOrCreateDatabase(destpath + "/md_book.db", null);
}

private boolean selectFavoriteState(){
    @SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main WHERE id = " + id, null);
    while (cursor.moveToNext()){
        favoriteState = cursor.getString(cursor.getColumnIndex("fav"));

    }
    return favoriteState.equals("1");
}

private void updateFavorited(){
    database.execSQL( "UPDATE main SET fav = 1 WHERE id = " + id);

}

private void updateUnfavorited(){
    database.execSQL( "UPDATE main SET fav = 0 WHERE id = " + id);


}

更新2:

package farmani.com.essentialwordsforielts.mainPage;

import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import farmani.com.essentialwordsforielts.R;

public class PageFragment extends Fragment {

private int mPage;
public static final String ARG_PAGE = "ARG_PAGE";
RecyclerView recyclerView;
AdapterFav adapterFav;


public static PageFragment newInstance(int page) {
    Bundle args = new Bundle();
    args.putInt(ARG_PAGE, page);
    PageFragment fragment = new PageFragment();
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate( Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mPage = getArguments().getInt(ARG_PAGE);


}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_page, container, false);

    if (mPage == 1) {
        recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
        AdapterList adapter = new AdapterList(MainActivity.context);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.context));
    }

    if (mPage == 2) {
        recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
        adapterFav = new AdapterFav(MainActivity.context);
        recyclerView.setAdapter(adapterFav);
        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.context));
    }

        return view;

    }


@Override
public void onResume() {
    super.onResume();
    if (adapterFav != null){
        adapterFav.notifyDataSetChanged();
    }
}
}

更新3:AdapterFav

package farmani.com.essentialwordsforielts.mainPage;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.innerpage.ActivityInnerPage;

public class AdapterFav extends RecyclerView.Adapter<ViewHolder> {

Context context;
LayoutInflater inflater;
TextView title;
ImageView avatar;
LinearLayout cardAdapter;

public AdapterFav(Context context){
    this.context = context;
    inflater = LayoutInflater.from(context);
}


@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = inflater.inflate(R.layout.adapter_card_view, parent, false);

    title = (TextView) view.findViewById(R.id.title1);
    avatar = (ImageView) view.findViewById(R.id.avatar);
    cardAdapter = (LinearLayout) view.findViewById(R.id.card_adapter);

    ViewHolder viewHolder = new ViewHolder(view);
    return viewHolder;


}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {

    holder.title.setText(MainActivity.favorite.get(position).getWord());
    String img = MainActivity.favorite.get(position).getImg();
    int id = MainActivity.context.getResources().getIdentifier(img, "drawable", MainActivity.context.getPackageName());
    holder.avatar.setImageResource(id);
    holder.cardAdapter.setOnClickListener(clickListener);
    holder.cardAdapter.setId(position);


}


View.OnClickListener clickListener = new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        int position = view.getId();
        Intent intent = new Intent (MainActivity.context, ActivityInnerPage.class);
        intent.putExtra("name", "favorite");
        intent.putExtra("id", position + "");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        MainActivity.context.startActivity(intent);


    }
};

@Override
public int getItemCount() {

    return MainActivity.favorite.size();
}
}

更新4:MainActivity

package farmani.com.essentialwordsforielts.mainPage;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.nabinbhandari.android.permissions.PermissionHandler;
import com.nabinbhandari.android.permissions.Permissions;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.search.ActivitySearch;
import farmani.com.essentialwordsforielts.setting.ActivitySetting;

public class MainActivity extends AppCompatActivity {

public static Context context;
public static ArrayList<Structure> list = new ArrayList<>();
public static ArrayList<Structure> favorite = new ArrayList<>();
DrawerLayout drawerLayout;
NavigationView navigationView;
ImageView hamburger;
SQLiteDatabase database;
String destPath;

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


    Permissions.check(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE},
            " storage permissions are required to copy database", new Permissions.Options()
                    .setSettingsDialogTitle("Warning!").setRationaleDialogTitle("Info"),
            new PermissionHandler() {
                @Override
                public void onGranted() {
                    setupDB();
                    selectList();
                    selectFavorite();
                }
            });

    context = getApplicationContext();
    setTabOption();

    drawerLayout = findViewById(R.id.navigation_drawer);
    navigationView = findViewById(R.id.navigation_view);
    hamburger = findViewById(R.id.hamburger);
    hamburger.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            drawerLayout.openDrawer(Gravity.START);
        }
    });

    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            int id = item.getItemId();
            if (id == R.id.exit) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                        MainActivity.this);

                alertDialog.setTitle(R.string.exit);

                alertDialog.setMessage(R.string.exit_ask);
                alertDialog.setCancelable(false);

                alertDialog.setPositiveButton(R.string.yes,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int
                                    which) {
                                finish();
                            }
                        });

                alertDialog.setNegativeButton(R.string.no,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int
                                    which) {

                                dialog.cancel();
                            }
                        });

                alertDialog.show();
            }else if (id == R.id.search) {
                Intent intent = new Intent(MainActivity.this, ActivitySearch.class);
                MainActivity.this.startActivity(intent);
            } else if (id == R.id.setting) {
                Intent intent = new Intent(MainActivity.this, ActivitySetting.class);
                MainActivity.this.startActivity(intent);

            }

            return true;
        }
    });


}

@Override
public void onBackPressed() {
    if (drawerLayout.isDrawerOpen(Gravity.START)) {
        drawerLayout.closeDrawer(Gravity.START);
    } else {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                MainActivity.this);

        alertDialog.setTitle(R.string.exit);

        alertDialog.setMessage(R.string.exit_ask);
        alertDialog.setCancelable(false);

        alertDialog.setPositiveButton(R.string.yes,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });

        alertDialog.setNegativeButton(R.string.no,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.cancel();
                    }
                });

        alertDialog.show();
    }
}


private void setTabOption() {
    ViewPager viewPager = findViewById(R.id.viewpager);
    viewPager.setAdapter(new AdapterFragment(getSupportFragmentManager(),
            context));
    TabLayout tabStrip = findViewById(R.id.tabs);
    tabStrip.setupWithViewPager(viewPager);
}

@Override
protected void onResume() {
    super.onResume();
    if (!list.isEmpty()){
        list.clear();
        selectList();
    } if (!favorite.isEmpty()){
        favorite.clear();
        selectFavorite();
    }
}

private void setupDB() {
    try {
        destPath =
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
        File file = new File(destPath);
        if (!file.exists()) {
            file.mkdirs();
            file.createNewFile();
            CopyDB(getBaseContext().getAssets().open("md_book.db"),
                    new FileOutputStream(destPath + "/md_book.db"));
        }
    } catch (IOException e1) {
        e1.printStackTrace();
    }
}


private void CopyDB(InputStream inputStream, OutputStream outputStream)
        throws IOException {
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) > 0) {
        outputStream.write(buffer, 0, length);
    }
    inputStream.close();
    outputStream.close();
}

private void selectFavorite() {

    database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
            null);
    @SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main WHERE fav = 1",
            null);
    while (cursor.moveToNext()) {
        String word = cursor.getString(cursor.getColumnIndex("word"));
        String definition =
                cursor.getString(cursor.getColumnIndex("definition"));
        String trans = cursor.getString(cursor.getColumnIndex("trans"));
        String img = cursor.getString(cursor.getColumnIndex("img"));
        int id = cursor.getInt(cursor.getColumnIndex("id"));

        Structure struct = new Structure(word, definition, trans, img, id);
        struct.setWord(word);
        struct.setDefinition(definition);
        struct.setTrans(trans);
        struct.setImg(img);
        struct.setId(id);
        favorite.add(struct);

    }

}

private void selectList() {

    database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
            null);
    @SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main", null);
    while (cursor.moveToNext()) {
        String word = cursor.getString(cursor.getColumnIndex("word"));
        String definition =
                cursor.getString(cursor.getColumnIndex("definition"));
        String trans = cursor.getString(cursor.getColumnIndex("trans"));
        String img = cursor.getString(cursor.getColumnIndex("img"));
        int id = cursor.getInt(cursor.getColumnIndex("id"));

        Structure struct = new Structure(word, definition, trans, img, id);
        struct.setWord(word);
        struct.setDefinition(definition);
        struct.setTrans(trans);
        struct.setImg(img);
        struct.setId(id);
        list.add(struct);
    }

}

}

更新5内页活动

package farmani.com.essentialwordsforielts.innerpage;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toolbar;
import java.lang.reflect.Field;

import farmani.com.essentialwordsforielts.R;
    import farmani.com.essentialwordsforielts.mainPage.AdapterFav;


public class ActivityInnerPage extends AppCompatActivity {

private TextView contentDescriptione;
private TextView moreDescriptione;
private ImageView avatar;
private ImageView imgCopy;
private ImageView imgShare;
private ImageView imgSms;
private ImageView imgGmail;
private FloatingActionButton favorite;
private CollapsingToolbarLayout collapsingToolbarLayout;
public String word;
public String definition;
public String trans;
public String img;
public int id;
private String destpath;
private SQLiteDatabase database;
private String favoriteState;

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

    final android.support.v7.widget.Toolbar toolbar = findViewById(R.id.toolbar);

    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getApplicationContext(),MainActivity.class);
            startActivity(i);
            finish();

        }
    });

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        int layoutId = Integer.parseInt(extras.getString("id"));
        String pageName = extras.getString("name");

        assert pageName != null;
        if (pageName.equals("list")) {

            id = MainActivity.list.get(layoutId).getId();
            word = MainActivity.list.get(layoutId).getWord();
            definition = MainActivity.list.get(layoutId).getDefinition();
            trans = MainActivity.list.get(layoutId).getTrans();
            img = MainActivity.list.get(layoutId).getImg();

        } else if (pageName.equals("favorite")) {

            id = MainActivity.favorite.get(layoutId).getId();
            word = MainActivity.favorite.get(layoutId).getWord();
            definition = MainActivity.favorite.get(layoutId).getDefinition();
            trans = MainActivity.favorite.get(layoutId).getTrans();
            img = MainActivity.favorite.get(layoutId).getImg();
        }
    }

    contentDescriptione = findViewById(R.id.content_description);
    moreDescriptione = findViewById(R.id.more_description);
    imgCopy = findViewById(R.id.img_copy);
    imgShare = findViewById(R.id.img_share);
    imgSms = findViewById(R.id.img_sms);
    imgGmail = findViewById(R.id.img_gmail);
    avatar = findViewById(R.id.avatar);
    favorite = findViewById(R.id.favorite);
    collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);
    collapsingToolbarLayout.getExpandedTitleMarginStart();
    collapsingToolbarLayout.setTitle(word);
    collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(android.R.color.holo_red_light));

    contentDescriptione.setText(definition);
    moreDescriptione.setText(trans);

    int imgageId = MainActivity.context.getResources().getIdentifier(img, "drawable", MainActivity.context.getPackageName());
    avatar.setImageResource(imgageId);

    SharedPreferences prefes = getSharedPreferences("font_size", MODE_PRIVATE);
    int value = prefes.getInt("fontsize", 16);
    contentDescriptione.setTextSize(value);
    moreDescriptione.setTextSize(value);

    selectDb();

    if(selectFavoriteState()){
        favorite.setImageResource(R.drawable.ic_favorite_like);
    }else {
        favorite.setImageResource(R.drawable.ic_favorite_maylike);
    }

    favorite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (selectFavoriteState()){
                favorite.setImageResource(R.drawable.ic_favorite_maylike);
                updateUnfavorited();

            }else {
                favorite.setImageResource(R.drawable.ic_favorite_like);
                updateFavorited();

            }



        }
    });

    imgCopy.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           final ClipboardManager  clipboardManager =
                   (ClipboardManager)ActivityInnerPage.this.getSystemService(Context.CLIPBOARD_SERVICE);
           final ClipData clip = ClipData.newPlainText(word, trans+definition);

            assert clipboardManager != null;
            clipboardManager.setPrimaryClip(clip);
            Snackbar.make(view,"متن کپی شد ",Snackbar.LENGTH_SHORT).show();
        }
    });

    imgShare.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_TEXT, definition+trans);
            shareIntent.putExtra(Intent.EXTRA_SUBJECT, word);
            startActivity(Intent.createChooser(shareIntent, "Share"));
        }
    });

    imgGmail.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {

                Intent emailIntent = new Intent(Intent.ACTION_SENDTO
                        , Uri.fromParts("mailto", "", null));
                emailIntent.putExtra(Intent.EXTRA_SUBJECT, word);
                emailIntent.putExtra(Intent.EXTRA_TEXT, definition);
                startActivity(Intent.createChooser(emailIntent, "Send email..."));

            }catch (Exception e){
                Snackbar.make(view,"برنامه ای برای ارسال ایمیل یافت نشد",Snackbar.LENGTH_SHORT).show();
            }
        }
    });

    imgSms.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                Intent sendSms = new Intent(Intent.ACTION_VIEW);
                sendSms.putExtra("sms_body", definition + trans);
                sendSms.setType("vnd.android-dir/mms-sms");
                startActivity(sendSms);
            }catch (Exception e){
                Snackbar.make(view,"برنامه ای برای ارسال پیام یافت نشد",Snackbar.LENGTH_SHORT).show();
            }
        }
    });


}


private void selectDb(){
    destpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
    database = SQLiteDatabase.openOrCreateDatabase(destpath + "/md_book.db", null);
}

private boolean selectFavoriteState(){
    @SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main WHERE id = " + id, null);
    while (cursor.moveToNext()){
        favoriteState = cursor.getString(cursor.getColumnIndex("fav"));

    }
    return favoriteState.equals("1");
}

private void updateFavorited(){
    database.execSQL( "UPDATE main SET fav = 1 WHERE id = " + id);

}

private void updateUnfavorited(){
    database.execSQL( "UPDATE main SET fav = 0 WHERE id = " + id);


}

}

2 个答案:

答案 0 :(得分:0)

在数据库中保存新项目后,在您的FloatingActionButton onClick方法中,将新项目插入recyclelerview数据源列表并在适配器上调用notifyDatasetChanged()。

答案 1 :(得分:0)

选择1 :在MainActivity的onResume()存根中,调用selectList()selectFavorite(),然后再次加载PageFragment,以便正确加载新列表。

这是最短的出路,但这种方法非常不优化,不推荐

选择2 :您必须在数据库中插入新项目并将其添加到List ,然后致电notifyDatasetChanged

分别在执行MainActivityselectList()后,在方法selectFavorite()list.add(struct)内的favourite.add(struct)中,您必须致电notifyDatasetChanged()适配器。

问题RecyclerViewPageFragment,而您正在填充MainActivity中的列表。

首先将您的selectList()selectFavorite()移至PageFragment,然后首先初始化RecylerView,然后设置Adapter,然后填充列表并最终在适配器上调用notifyDatasetChanged()