我正在开发一个需要使用ROOM ORM实现收藏夹的应用程序。我在一个片段中有不同的Duas,并且有一个用于将该Dua插入数据库的按钮,插入部分可以正常工作,但是当我尝试通过单击我最近添加到收藏夹的dua来加载dua时,一个空指针异常是抛出,并且仅在我同时将两个以上的duas添加到收藏夹列表的情况下才会发生。附带的代码下面是DAO CLASS
import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import com.islam.cheapapps.dua101.model.Favorite;
import java.util.List;
/**
* Created by home on 16/06/2018.
*/
@Dao
public interface FavoriteDao {
@Insert
void insert(Favorite favorite);
@Query("DELETE FROM favorite_dua")
void deleteAll();
//ORDER BY word ASC if ordering is necessary.(optional)
@Query("SELECT * from favorite_dua")
LiveData<List<Favorite>> getAllDuas();
@Query("SELECT * FROM favorite_dua WHERE position = :position AND dua_category = :dua_category")
Favorite getFavoritePosition(int position, String dua_category);
}
最喜欢的按钮被选中的班级
public class ScreenSlidePageFragment extends Fragment {
JSONArray jsonArray;
FavoriteViewModel mWordViewModel;
// Variable for identification of category (0 for duas after salah, 1 for morning azkar) and so on
int id = 0;
private int pos = 0;
//Title Text View
private TextView headerTV;
//Pronunciation Text View
private TextView pronunciationTV;
//Translation Text View
private TextView translationTV;
//Benefit Text View
private TextView benefitTV;
//Reference Text View
private TextView referenceTV;
//Dua Image View
private ImageView duaIV;
//Favorite Button
private LikeButton favoriteBtn;
//Share Button
private SparkButton shareButton;
public void setPosition(int pos) {
this.pos = pos;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.dua_layout, container, false);
//Get reference to the dua title
headerTV = rootView.findViewById(R.id.title);
//Get reference to the dua pronunciation
pronunciationTV = rootView.findViewById(R.id.pronounciationTV);
//Get reference to the dua translation
translationTV = rootView.findViewById(R.id.translationTV);
//Get reference to the dua benefit
benefitTV = rootView.findViewById(R.id.benefitTV);
//Get reference to the dua reference
referenceTV = rootView.findViewById(R.id.referenceTV);
//Get reference to the dua img
duaIV = rootView.findViewById(R.id.duaIV);
//Get reference to the favorite Button
favoriteBtn = rootView.findViewById(R.id.favorite_btn);
//Get reference to the share Button
shareButton = rootView.findViewById(R.id.share_btn);
//Setting onClick Listener on share Button
shareButton.setEventListener(new SparkEventListener() {
@Override
public void onEvent(ImageView imageView, boolean b) {
}
@Override
public void onEventAnimationEnd(ImageView imageView, boolean b) {
}
@Override
public void onEventAnimationStart(ImageView imageView, boolean b) {
shareDua();
}
});
//Setting onClick listener on the fav button which will add the dua to favorite list.
favoriteBtn.setOnLikeListener(new OnLikeListener() {
@Override
public void liked(LikeButton likeButton) {
addToFavorites();
}
@Override
public void unLiked(LikeButton likeButton) {
}
});
// Function for getting data of a specific category
getData();
// Function for setting data into the view
setData();
mWordViewModel = ViewModelProviders.of(this).get(FavoriteViewModel.class);
return rootView;
}
// Getting Data for a specific category
private void getData() {
id = getActivity().getIntent().getIntExtra("position", 0);
switch (id) {
case 0:
readData(this.getResources().openRawResource(R.raw.c0));
break;
case 1:
readData(this.getResources().openRawResource(R.raw.c1));
break;
case 2:
readData(this.getResources().openRawResource(R.raw.c2));
break;
case 3:
readData(this.getResources().openRawResource(R.raw.c0));
break;
case 4:
readData(this.getResources().openRawResource(R.raw.c0));
break;
case 5:
readData(this.getResources().openRawResource(R.raw.c0));
break;
default:
break;
}
}
/**
* Reading data from the JSON array
*/
private void readData(InputStream in) {
StringBuilder text = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader((new InputStreamReader(in)));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
try {
jsonArray = new JSONArray(text.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Set Data depending upon the position of view pager
*/
private void setData() {
try {
JSONArray tempJson = jsonArray.getJSONArray(this.pos);
duaIV.setImageResource(getResources().getIdentifier(tempJson.getString(3).trim().substring(0, tempJson.getString(3).indexOf(".png")), "drawable", getActivity().getPackageName()));
headerTV.setText(tempJson.getString(0).trim());
pronunciationTV.setText(tempJson.getString(3).trim());
translationTV.setText(tempJson.getString(9).trim());
benefitTV.setText(tempJson.getString(12).trim());
referenceTV.setText(tempJson.getString(11).trim());
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* A share intent is fired and gives choice to user for sharing the current dua using the applications
* that are present in his mobile
*/
private void shareDua() {
/*try {
sharingText = mJsonArray.getJSONObject(currPos).getString("seq") + "\n" +
mJsonArray.getJSONObject(currPos).getString("narator") + "\n" +
mJsonArray.getJSONObject(currPos).getString("hadith");
} catch (JSONException e) {
e.printStackTrace();
}*/
Intent sharingIntent = new Intent();
sharingIntent.setAction(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
// sharingIntent.putExtra(Intent.EXTRA_TEXT, sharingText);
startActivity(Intent.createChooser(sharingIntent, "Share using"));
}
//Add dua to favorite on pressing the favorite button
private void addToFavorites() {
String dua_category = "";
switch (id) {
case 0:
dua_category = "Duas after Salah";
break;
case 1:
dua_category = "Morning Azkar";
break;
case 2:
dua_category = "Evening Azkar";
break;
case 3:
dua_category = "Rabbana Duas";
break;
case 4:
dua_category = "Essential Duas";
break;
case 5:
dua_category = "Ruquiya";
break;
default:
dua_category = "";
break;
}
Favorite favorite = new Favorite(headerTV.getText().toString(),
pronunciationTV.getText().toString(), dua_category, this.pos);
Toast.makeText(this.getContext().getApplicationContext(), "Position : " + this.pos + "Category : "
+ dua_category
, Toast.LENGTH_SHORT).show();
mWordViewModel.insert(favorite);
}
}
已将项目添加到列表中后,点击收藏的班级便会实施
public class FavoriteAdapter extends
RecyclerView.Adapter<FavoriteAdapter.MyViewHolder> {
private final LayoutInflater mInflater;
private Context mContext;
private List<Favorite> mDuas; // Cached copy of words
String cat = "";
public FavoriteAdapter(Context mContext) {
this.mContext = mContext;
mInflater = LayoutInflater.from(mContext);
}
@Override
public FavoriteAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemView = mInflater.inflate(R.layout.favorite_single_item, viewGroup, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(FavoriteAdapter.MyViewHolder holder, int position) {
// Variable for holding the position of the current view that was clicked
final int temp = position;
if (mDuas != null) {
Favorite current = mDuas.get(position);
holder.favoriteHeader.setText(current.getHeader());
holder.favoritePronunciation.setText(current.getDua_pronunciation());
cat = current.getDua_category();
} else {
// Covers the case of data not being ready yet.
holder.favoriteHeader.setText("No Word");
}
holder.favoriteCV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
FavoriteRoomDatabase db = FavoriteRoomDatabase.getDatabase(mContext);
FavoriteDao mFavoriteDao = db.favoriteDao();
Favorite f = mFavoriteDao.getFavoritePosition(temp, cat);
////////////////////////// TEST LOGIC //////////////////////////////
Intent intent = new Intent(mContext, ScreenSlidePagerActivity.class);
intent.putExtra("fav", "favorite");
intent.putExtra("category", f.getDua_category());
intent.putExtra("position", f.getPosition());
mContext.startActivity(intent);
////////////////////////////////////////////////////////////////////
}
}).start();
}
});
}
public void setDuas(List<Favorite> duas) {
mDuas = duas;
notifyDataSetChanged();
}
@Override
public int getItemCount() {
if (mDuas != null) {
return mDuas.size();
} else {
return 0;
}
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView favoriteHeader, favoritePronunciation;
public ImageView favoriteImage;
public CardView favoriteCV;
public MyViewHolder(View itemView) {
super(itemView);
favoriteCV = itemView.findViewById(R.id.favoriteCV);
favoriteHeader = itemView.findViewById(R.id.favorite_header);
favoritePronunciation = itemView.findViewById(R.id.favorite_pronunciation);
favoriteImage = itemView.findViewById(R.id.favorite_image);
}
}
}