gpt4 book ai didi

java - 如何使用 sharedpreference 将 favorite_List Activity 添加到 Android 中的 ListView Activity

转载 作者:行者123 更新时间:2023-11-30 04:59:21 27 4
gpt4 key购买 nike

这是我正在尝试创建的 listView 类型:当用户单击列表时,它会将用户带到 newActivity,用户将在其中找到 listView 的全部内容。并在 longPressed 上将列表项添加到 favoritesList。

在遵循有关如何使用 BaseAdapter 在 Listview 中添加 favoritesActivity 的教程后,我遇到了错误。那是;我的应用程序在启动时强制关闭。我知道我漏掉了一些行,或者可能在不知不觉中添加了可能导致应用程序崩溃的未格式化对象。我已经为您提供了 logCat 报告,以帮助我解决导致崩溃的问题。我是编程新手,我想学习使用这个程序。我是一名学生,我需要你的帮助才能完成我的项目。

我所有的试验和错误都包含在显示的代码中。请您帮我解决问题。谢谢

这是 MainActivity.java

public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
private String TAG = "MainActivity ----- ; " ;
// Store instance variables

private int page;
private ConsentForm form;

ListView listView;
ListViewAdapter adapter;
String[] title;
String[] description;
int[] icon;
ArrayList<Model> arrayList = new ArrayList<Model>();


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

ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Redeemed Songs");

title = new String[]{"This is the lyrics content example of the song1, This is the lyrics content example of the song2, This is the lyrics content example of the song3, This is the lyrics content example of the song4, This is the lyrics content example of the song5",};

description = new String[]{"MORNING", "MORNING", "MORNING", "MORNING", "MORNING", "MORNING",};

icon = new int[]{ R.drawable.song, R.drawable.song, R.drawable.song, R.drawable.song,R.drawable.song,R.drawable.song,};

listView = findViewById(R.id.list);

for (int i =0; i<title.length; i++){
Model model =new Model(title[i], description[i], icon[i]);
//bind all strings in an array
arrayList.add(model);
}

//pass result to listview class
adapter = new ListViewAdapter(this, arrayList);

//bind the adapter to the listview class
listView.setAdapter(adapter);


}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);

MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView)myActionMenuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}

@Override
public boolean onQueryTextChange(String s) {
if (TextUtils.isEmpty(s)){
adapter.filter("");
listView.clearTextFilter();
}
else {
adapter.filter(s);
}
return true;
}
});

return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();

if (id==R.id.action_settings){
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, Main2Activity.class));
return true;
//do your funtionality here

}
else if (id==R.id.action_howtouse){
Toast.makeText(this, "manual", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, Main3Activity.class));
return true;
//do your funtionality here


}
else if (id==R.id.action_developers){
Toast.makeText(this, "Favorites", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, Main4Activity.class));
return true;
//do your funtionality here

}
return super.onOptionsItemSelected(item);
}

@Override
public boolean onQueryTextSubmit(String query) {
return false;
}

@Override
public boolean onQueryTextChange(String newText) {
return false;
}
}

这是 Model.java 类

public class Model {

String title;
String desc;
int icon;
int fav_icon;

public Model(int fav_icon) {
this.fav_icon = fav_icon;
}

public int getFav_icon() {
return fav_icon;
}

//constructor

public Model(String title, String desc, int icon) {
this.title = title;
this.desc = desc;
this.icon = icon;
}


//getters


public String getTitle() {
return title;
}

public String getDesc() {
return desc;
}

public int getIcon() {
return icon;
}

}

这是 row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:padding="10dp">

<ImageView
android:id="@+id/mainIcon"
android:src="@drawable/song"
android:layout_width="30dp"
android:layout_height="40dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp">

<TextView
android:id="@+id/mainTitle"
android:textStyle="bold"
android:textColor="#740303"
android:text="Title"
android:textSize="15sp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/mainDesc"
android:text="Description"
android:textColor="#262626"
android:textSize="12sp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/list_fav_icon"
android:layout_width="0dp"
android:layout_height="match_parent"
android:src="@drawable/ic_favorite_active"
android:layout_gravity="right"
android:layout_margin="5dp"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>

这是 ListViewAdapter.java 类

public class ListViewAdapter extends BaseAdapter{

//Variables
Context mContext;
LayoutInflater inflater;
List<Model> modellist;
ArrayList<Model> arrayList;
private Model model;
CheckBox checkFavoriteItem;
SharedPreference sharedPreference;

//Constructor
public ListViewAdapter(Context context, List<Model> modellist) {
mContext = context;
this.modellist = modellist;
inflater = LayoutInflater.from(mContext);
this.arrayList = new ArrayList<Model>();
this.arrayList.addAll(modellist);

}

public class ViewHolder{
TextView mTitleTv, mDescTv;
ImageView mIconTv, favIcon;
}

@Override
public int getCount() {
return modellist.size();
}

@Override
public Object getItem(int i) {
return modellist.get(i);
}

@Override
public long getItemId(int i) {
return i;
}

@Override
public View getView(final int i, View view, ViewGroup parent) {
final ViewHolder holder;
if (view==null){
holder = new ViewHolder();
view = inflater.inflate(R.layout.row, null);

//locate the views in row.xml
holder.mTitleTv = (TextView) view.findViewById(R.id.mainTitle);
holder.mDescTv = (TextView) view.findViewById(R.id.mainDesc);
holder.mIconTv = view.findViewById(R.id.mainIcon);
holder.favIcon = view.findViewById(R.id.list_fav_icon);

view.setTag(holder);
}
else {
holder = (ViewHolder)view.getTag();
}

//set the result into textview
Model model = (Model) getItem(i);
holder.mTitleTv.setText(modellist.get(i).getTitle());
holder.mDescTv.setText(modellist.get(i).getDesc());
//Set the result in imagview
holder.mIconTv.setImageResource(modellist.get(i).getIcon());
holder.favIcon.setImageResource(modellist.get(i).getFav_icon());

if (checkFavoriteItem(model)) {
holder.favIcon.setImageResource(R.drawable.ic_favorite_active);
holder.favIcon.setTag("yes");
} else {
holder.favIcon.setImageResource(R.drawable.ic_favorite_default);
holder.favIcon.setTag("no");
}

//listview item clicks
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//code later
if (modellist.get(i).getTitle().equals("This is the lyrics content example of the song1")){
//start NewActivity with title for actionbar and text for textview
Intent intent = new Intent(mContext, NewActivity.class);
intent.putExtra("actionBarTitle", "Song 001");
intent.putExtra("contentTv", "This is the lyrics content example of the song2");
mContext.startActivity(intent);
}
if (modellist.get(i).getTitle().equals("This is the lyrics content example of the song1")){
//start NewActivity with title for actionbar and text for textview
Intent intent = new Intent(mContext, NewActivity.class);
intent.putExtra("actionBarTitle", "Song 002");
intent.putExtra("contentTv", "This is the lyrics content example of the song2");
mContext.startActivity(intent);
}
if (modellist.get(i).getTitle().equals("This is the lyrics content example of the song3")){
//start NewActivity with title for actionbar and text for textview
Intent intent = new Intent(mContext, NewActivity.class);
intent.putExtra("actionBarTitle", "Song 003");
intent.putExtra("contentTv", "This is the lyrics content example of the song3");
mContext.startActivity(intent);
}
if (modellist.get(i).getTitle().equals("This is the lyrics content example of the song4")){
//start NewActivity with title for actionbar and text for textview
Intent intent = new Intent(mContext, NewActivity.class);
intent.putExtra("actionBarTitle", "Song 004");
intent.putExtra("contentTv", "This is the lyrics content example of the song4");
mContext.startActivity(intent);
}
if (modellist.get(i).getTitle().equals("This is the lyrics content example of the song5")){
//start NewActivity with title for actionbar and text for textview
Intent intent = new Intent(mContext, NewActivity.class);
intent.putExtra("actionBarTitle", "Song 005");
intent.putExtra("contentTv", "This is the lyrics content example of the song5");
mContext.startActivity(intent);
}

}
});

final ImageView favoritesbutton = (ImageView) view.findViewById(R.id.list_fav_icon);
favoritesbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String tag = favoritesbutton.getTag().toString();

if (tag.equalsIgnoreCase("no")){
sharedPreference.addFavorite(mContext, modellist.get(i));
Toast.makeText(mContext, R.string.add_favr, Toast.LENGTH_SHORT).show();
favoritesbutton.setTag("yes");
favoritesbutton.setImageResource(R.drawable.ic_favorite_active);
}else{
sharedPreference.removeFavorite(mContext, modellist.get(i));
favoritesbutton.setTag("no");
favoritesbutton.setImageResource(R.drawable.ic_favorite_default);
Toast.makeText(mContext, R.string.favorites_remove_msg, Toast.LENGTH_SHORT).show();
}
}
});


return view;
}

//Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(Model checkCode) {
boolean check = false;
List<Model> favorites = sharedPreference.getFavorites(mContext);
if (favorites != null) {
for (Model model : favorites) {
if (model.equals(checkCode)) {
check = true;
break;
}
}
}
return check;
}

public void add(Model model) {
modellist.add(model);
notifyDataSetChanged();
}
public void remove(Model model) {
modellist.remove(model);
notifyDataSetChanged();
}

//filter
public void filter(String charText){
charText = charText.toLowerCase(Locale.getDefault());
modellist.clear();
if (charText.length()==0){
modellist.addAll(arrayList);
}
else {
for (Model model : arrayList){
if (model.getTitle().toLowerCase(Locale.getDefault()).contains(charText)){
modellist.add(model);
}
}
}
notifyDataSetChanged();
}

}

这是存储值的 SharedPreference.java 类

public class SharedPreference {

public static final String PREFS_NAME = "REDEEMED_APP";
public static final String FAVORITES = "code_Favorite";

public SharedPreference() {
super();
}

// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<Model> favorites) {
SharedPreferences settings;
Editor editor;

settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();

Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);

editor.putString(FAVORITES, jsonFavorites);

editor.commit();
}

public void addFavorite(Context context, Model product) {
List<Model> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<Model>();
favorites.add(product);
saveFavorites(context, favorites);
}

public void removeFavorite(Context context, Model model) {
ArrayList<Model> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(model);
saveFavorites(context, favorites);
}
}

public ArrayList<Model> getFavorites(Context context) {
SharedPreferences settings;
List<Model> favorites;

settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);

if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
Model[] favoriteItems = gson.fromJson(jsonFavorites,
Model[].class);

favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<Model>(favorites);
} else
return null;

return (ArrayList<Model>) favorites;
}
}

这是 MyFavoriteActivity.java 类,用于存储列表

public class MyFavoriteActivity extends AppCompatActivity {
SharedPreference sharedPreference;
List<Model> favorites;

FavouritesAdapter favouritesAdapter;
Context context = this.context;

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

sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(MyFavoriteActivity.this);

if (favorites == null){
Dialog dialog = new Dialog(MyFavoriteActivity.this);
dialog.setTitle(R.string.no_favorites_items);
dialog.show();
}else {
if (favorites.size() ==0){
Dialog dialog = new Dialog(MyFavoriteActivity.this);
dialog.setTitle(R.string.no_favorites_items);
dialog.show();
}

ListView favList = (ListView) findViewById(R.id.FavoriteLayoutListView);

if(favorites != null){
favouritesAdapter = new FavouritesAdapter(MyFavoriteActivity.this, favorites);
favList.setAdapter(favouritesAdapter);

favList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

public void onItemClick(AdapterView<?> parent, View arg1,
int position, long arg3) {

}
});





favList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {

ImageView button = (ImageView) view
.findViewById(R.id.list_fav_icon);

String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("no")) {
sharedPreference.addFavorite(MyFavoriteActivity.this,
favorites.get(position));
Toast.makeText(
MyFavoriteActivity.this,
R.string.add_favr,
Toast.LENGTH_SHORT).show();

button.setTag("yes");
button.setImageResource(R.drawable.ic_favorite_active);
} else {
sharedPreference.removeFavorite(MyFavoriteActivity.this,
favorites.get(position));
button.setTag("no");
button.setImageResource(R.drawable.ic_favorite_default);
Toast.makeText(
MyFavoriteActivity.this,
R.string.remove_favr,
Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
}
}

}

这是 FavoriteListAdapter.java.class

public class FavouritesAdapter extends BaseAdapter{

//Variables
Context mContext;
LayoutInflater inflater;
List<Model> modellist;
ArrayList<Model> arrayList;
private Model model;

//Constructor
public FavouritesAdapter(Context context, List<Model> modellist) {
mContext = context;
this.modellist = modellist;
inflater = LayoutInflater.from(mContext);
this.arrayList = new ArrayList<Model>();
this.arrayList.addAll(modellist);

}

public class ViewHolder{
TextView mTitleTv, mDescTv;
ImageView mIconTv, favIcon;
}

@Override
public int getCount() {
return modellist.size();
}

@Override
public Object getItem(int i) {
return modellist.get(i);
}

@Override
public long getItemId(int i) {
return i;
}

@Override
public View getView(final int i, View view, ViewGroup parent) {
final ViewHolder holder;
if (view==null){
holder = new ViewHolder();
view = inflater.inflate(R.layout.row, null);

//locate the views in row.xml
holder.mTitleTv = (TextView) view.findViewById(R.id.mainTitle);
holder.mDescTv = (TextView) view.findViewById(R.id.mainDesc);
holder.mIconTv = view.findViewById(R.id.mainIcon);

view.setTag(holder);
}
else {
holder = (ViewHolder)view.getTag();
}

//set the result into textview
holder.mTitleTv.setText(modellist.get(i).getTitle());
holder.mDescTv.setText(modellist.get(i).getDesc());
//Set the result in imagview
holder.mIconTv.setImageResource(modellist.get(i).getIcon());

//listview item clicks
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//code later
if (modellist.get(i).getTitle().equals("This is the lyrics content example of the song1")){
//start NewActivity with title for actionbar and text for textview
Intent intent = new Intent(mContext, NewActivity.class);
intent.putExtra("actionBarTitle", "Song 001");
intent.putExtra("contentTv", "This is the lyrics content example of the song2");
mContext.startActivity(intent);
}
if (modellist.get(i).getTitle().equals("This is the lyrics content example of the song1")){
//start NewActivity with title for actionbar and text for textview
Intent intent = new Intent(mContext, NewActivity.class);
intent.putExtra("actionBarTitle", "Song 002");
intent.putExtra("contentTv", "This is the lyrics content example of the song2");
mContext.startActivity(intent);
}
if (modellist.get(i).getTitle().equals("This is the lyrics content example of the song3")){
//start NewActivity with title for actionbar and text for textview
Intent intent = new Intent(mContext, NewActivity.class);
intent.putExtra("actionBarTitle", "Song 003");
intent.putExtra("contentTv", "This is the lyrics content example of the song3");
mContext.startActivity(intent);
}
if (modellist.get(i).getTitle().equals("This is the lyrics content example of the song4")){
//start NewActivity with title for actionbar and text for textview
Intent intent = new Intent(mContext, NewActivity.class);
intent.putExtra("actionBarTitle", "Song 004");
intent.putExtra("contentTv", "This is the lyrics content example of the song4");
mContext.startActivity(intent);
}
if (modellist.get(i).getTitle().equals("This is the lyrics content example of the song5")){
//start NewActivity with title for actionbar and text for textview
Intent intent = new Intent(mContext, NewActivity.class);
intent.putExtra("actionBarTitle", "Song 005");
intent.putExtra("contentTv", "This is the lyrics content example of the song5");
mContext.startActivity(intent);
}

}
});


return view;
}

//filter
public void filter(String charText){
charText = charText.toLowerCase(Locale.getDefault());
modellist.clear();
if (charText.length()==0){
modellist.addAll(arrayList);
}
else {
for (Model model : arrayList){
if (model.getTitle().toLowerCase(Locale.getDefault()).contains(charText)){
modellist.add(model);
}
}
}
notifyDataSetChanged();
}

}

这是 LogCat


--------- beginning of crash
2019-10-22 02:02:39.715 11214-11214/com.gritchen.redeemedsongs E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gritchen.redeemedsongs, PID: 11214
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList com.gritchen.redeemedsongs.SharedPreference.getFavorites(android.content.Context)' on a null object reference
at com.gritchen.redeemedsongs.ListViewAdapter.checkFavoriteItem(ListViewAdapter.java:372)
at com.gritchen.redeemedsongs.ListViewAdapter.getView(ListViewAdapter.java:86)
at android.widget.AbsListView.obtainView(AbsListView.java:2365)
at android.widget.ListView.makeAndAddView(ListView.java:2052)
at android.widget.ListView.fillDown(ListView.java:786)
at android.widget.ListView.fillFromTop(ListView.java:847)
at android.widget.ListView.layoutChildren(ListView.java:1826)
at android.widget.AbsListView.onLayout(AbsListView.java:2164)
at android.view.View.layout(View.java:20323)
at android.view.ViewGroup.layout(ViewGroup.java:6199)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1083)
at android.view.View.layout(View.java:20323)
at android.view.ViewGroup.layout(ViewGroup.java:6199)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:20323)
at android.view.ViewGroup.layout(ViewGroup.java:6199)
at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:443)
at android.view.View.layout(View.java:20323)
at android.view.ViewGroup.layout(ViewGroup.java:6199)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:20323)
at android.view.ViewGroup.layout(ViewGroup.java:6199)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1791)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1635)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1544)
at android.view.View.layout(View.java:20323)
at android.view.ViewGroup.layout(ViewGroup.java:6199)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at com.android.internal.policy.DecorView.onLayout(DecorView.java:764)
at android.view.View.layout(View.java:20323)
at android.view.ViewGroup.layout(ViewGroup.java:6199)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2612)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2317)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1453)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7047)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:924)
at android.view.Choreographer.doCallbacks(Choreographer.java:732)
at android.view.Choreographer.doFrame(Choreographer.java:664)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:910)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6524)
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:888)
2019-10-22 02:02:39.737 11214-11253/com.gritchen.redeemedsongs D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2019-10-22 02:02:39.899 11214-11253/com.gritchen.redeemedsongs D/libc-netbsd: getaddrinfo: get result from proxy gai_error = 0
2019-10-22 02:02:39.918 11214-11253/com.gritchen.redeemedsongs I/System.out: port:443
2019-10-22 02:02:41.595 11214-11239/com.gritchen.redeemedsongs

最佳答案

你在打电话

List<Model> favorites = sharedPreference.getFavorites(mContext);

sharedPreference 永远不会被实例化。从而抛出 NullPointerException。尝试在构造函数中实例化对象

//Constructor
public ListViewAdapter(Context context, List<Model> modellist) {
mContext = context;
this.modellist = modellist;
inflater = LayoutInflater.from(mContext);
this.arrayList = new ArrayList<Model>();
this.arrayList.addAll(modellist);
this.sharedPreference = new SharedPreference();
}

关于java - 如何使用 sharedpreference 将 favorite_List Activity 添加到 Android 中的 ListView Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58499918/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com