- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我目前正在用 Java 编写一个 Android 应用程序,该应用程序旨在记录运动员的锻炼日志并将其存储在其内部存储中。然后它应该能够调用、编辑和删除现有的锻炼日志。当我尝试检查内部存储的过去锻炼日志的 ArrayList 成员与其中一个日志的打包副本之间的相等性时,出现错误。
如果我尝试检查两个存储的日志或一个存储的日志与其自身之间的相等性,我会得到正确的结果,没有空指针异常。但是,当我向 DataHandler 类传递要删除的日志(包含在我的 DetailActivity 类中)时,会发生错误。无论我在何处或如何尝试将这个传递的、以前打包的日志与我的 equals() 方法进行比较,我都会遇到空指针异常。我对此感到非常困惑,因为我知道一个事实,当我打印我传递的日志和我试图删除的存储日志的字段时,它们是完全相同的。我知道 equals() 不能对空对象起作用,但这个对象显然不是空的,因为我可以打印它的字段。如有任何帮助,我们将不胜感激。
尝试使用 copy.equals(storedObject) 时出现以下错误:
Caused by: java.lang.NullPointerException
at com.cs121.team2.workoutlog.WOLog.equals(WOLog.java:168)
at com.cs121.team2.workoutlog.DataHandler.editLog(DataHandler.java:134)
at com.cs121.team2.workoutlog.DetailActivity.onDeleteClick(DetailActivity.java:95)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3592)
at android.view.View.performClick(View.java:4202)
at android.view.View$PerformClick.run(View.java:17340)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5039)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
这是我的 DataHandler 类。我在线收到错误:
Log.d("arraylist(1)==arrayList(1)","结果:"+ dummy.equals(logList.get(1)));
在我的 editLog 方法中。
public class DataHandler extends Activity {
private final String TAG = "Data Handler";
public static DataHandler _dh; //the DataHandler instance that will be constructed and kept
private static Gson gson;
private static Type listType;
private static Context mContext;
private DataHandler() throws IOException { //this is a singleton class, so this is kept private
gson = new Gson();
listType = new TypeToken<ArrayList<WOLog>>(){}.getType();
File file = new File(mContext.getFilesDir(), "jsonLogs.json");
file.createNewFile();
}
public synchronized static DataHandler getDataHandler(Context context) { //used to make/get the DH
mContext = context;
if (_dh == null) { //does the DH already exist?
try {
_dh = new DataHandler(); //if not, create a new one
} catch (IOException e) {
e.printStackTrace();
}
}
return _dh; //if so, just return the DH that is already instantiated
}
//sends the ArrayList of Logs to LLAdapter
public synchronized ArrayList<WOLog> getLogs() throws IOException {
//find and read data from data storage to string temp
FileInputStream fis = mContext.openFileInput("jsonLogs.json");
int c;
String temp="";
while( (c = fis.read()) != -1){
temp = temp + Character.toString((char)c);
}
fis.close();
//convert to non-JSON
ArrayList<WOLog> toReturn = (ArrayList<WOLog>) gson.fromJson(temp, listType);
if (toReturn == null){
toReturn = new ArrayList<WOLog>();
//TODO show user friendly error message
}
//send to LLAdapter
return toReturn;
}
//appends a new log to the Log AList
public synchronized void addLog(WOLog toAdd) throws IOException {
//retrive data from file
FileInputStream fis = mContext.openFileInput("jsonLogs.json");
int c;
String temp="";
while( (c = fis.read()) != -1){
temp = temp + Character.toString((char)c);
}
fis.close();
//convert to non-JSON
ArrayList<WOLog> logList = (ArrayList<WOLog>) gson.fromJson(temp, listType);
if (logList == null) {
logList = new ArrayList<WOLog>();
}
logList.add(toAdd);
// Sorts the list of logs from oldest to newest
Collections.sort(logList, new Comparator<WOLog>() {
@Override
public int compare(WOLog woLog, WOLog woLog2) {
return woLog2.getDateCompare() - woLog.getDateCompare();
}
});
// For clearing the file while testing: logList = null;
//convert to JSON
String jsonLog = gson.toJson(logList);
//save to a .txt file
FileOutputStream fos = mContext.openFileOutput("jsonLogs.json", Context.MODE_PRIVATE);
//write to internal storage
fos.write(jsonLog.getBytes());
fos.close();
}
//edits or removes an existing log
public synchronized void editLog(WOLog newLog, WOLog oldLog, boolean delete) throws IOException {
//save a dummy copy of oldLog
WOLog dummy = oldLog;
//retrieve data from file
FileInputStream fis = mContext.openFileInput("jsonLogs.json");
int c;
String temp="";
while( (c = fis.read()) != -1){
temp = temp + Character.toString((char)c);
}
fis.close();
//convert to non-JSON
ArrayList<WOLog> logList = (ArrayList<WOLog>) gson.fromJson(temp, listType);
//for(WOLog bleh : logList) {
// Log.d("logList bleh",bleh.toStringList());
//}
if(delete) { //are we deleting the log?
//Log.d("oldLog fields","oldLog. date: " + oldLog.getDate() + ", name: " + oldLog.getName() + ", time: ." + oldLog.getTime() + ", distance: " + oldLog.getDistance() + ", mood: " + oldLog.getMood() + ", weight " + oldLog.getWeight() + ", sets: " + oldLog.getSets() + ", reps: " + oldLog.getReps() + ", memo: " + oldLog.getMemo() + ", type: " + oldLog.getType() + ", subtype: " + oldLog.getSubtype() + ", dateCompare: " + oldLog.getDateCompare());
//Log.d("arrayList(0) fields","arrayList(0). date: " + logList.get(0).getDate() + ", name: " + logList.get(0).getName() + ", time: ." + logList.get(0).getTime() + ", distance: " + logList.get(0).getDistance() + ", mood: " + logList.get(0).getMood() + ", weight " + logList.get(0).getWeight() + ", sets: " + logList.get(0).getSets() + ", reps: " + logList.get(0).getReps() + ", memo: " + logList.get(0).getMemo() + ", type: " + logList.get(0).getType() + ", subtype: " + logList.get(0).getSubtype() + ", dateCompare: " + logList.get(0).getDateCompare());
//Log.d("arrayList(1) fields","arrayList(1). date: " + logList.get(1).getDate() + ", name: " + logList.get(1).getName() + ", time: ." + logList.get(1).getTime() + ", distance: " + logList.get(1).getDistance() + ", mood: " + logList.get(1).getMood() + ", weight " + logList.get(1).getWeight() + ", sets: " + logList.get(1).getSets() + ", reps: " + logList.get(1).getReps() + ", memo: " + logList.get(1).getMemo() + ", type: " + logList.get(1).getType() + ", subtype: " + logList.get(1).getSubtype() + ", dateCompare: " + logList.get(1).getDateCompare());
Log.d("arraylist(1)==arrayList(1)","result: " + dummy.equals(logList.get(1)));
//Log.d("contained?","oldLog contained: " + logList.contains(oldLog));
//Log.d("arrayList(0)",logList.get(0).toStringDetail());
//logList.indexOf(oldLog); //...if so, delete the log
//Log.d("past remove","we got past remove(oldLog)");
}
else { //...if not, we're editing the log
int myIndex = logList.indexOf(oldLog); //find the index of the old log
logList.set(myIndex, newLog); //set the old log to the new log
}
// For clearing the file while testing: logList = new ArrayList<WOLog>();
//sort loglist
if(!logList.isEmpty()) {
Collections.sort(logList, new Comparator<WOLog>() {
@Override
public int compare(WOLog woLog, WOLog woLog2) {
return woLog2.getDateCompare() - woLog.getDateCompare();
}
});
}
Log.d("past sort","we got past Collections.sort");
//convert to JSON
String jsonLog = gson.toJson(logList);
Log.d("past toJson","we got past jsonLog = gson.toJson(logList)");
//save to a .txt file
FileOutputStream fos = mContext.openFileOutput("jsonLogs.json", Context.MODE_PRIVATE);
Log.d("past fos","we got past fos = mContext.openFileOutput(...)");
//write to internal storage
fos.write(jsonLog.getBytes());
Log.d("past write","we got past fos.write(...)");
fos.close();
Log.d("past close","we got past fos.close()");
}
}
最后,这是我的 WOLog 类,其中包含 equals 方法。终端显示错误发生在返回行。
public class WOLog implements Parcelable {
// Just a lot of static data
final static int TYPE_CARDIO = 0;
final static int TYPE_STRENGTH = 1;
final static int TYPE_CUSTOM = 2;
final static int SUBTYPE_NONE = 0;
final static int SUBTYPE_TIME_BODY = 1;
final static int SUBTYPE_DIST_WEIGHTS = 2;
final static String[] MOOD_ARRAY = {"awful", "bad", "k", "good", "perfect"};
final static String[] TYPE_ARRAY = {"Cardio", "Strength", "Custom"};
final static String[] SUBTYPE_ARRAY = {"None", "Time/Body", "Distance/Weights"};
// Data stored in log
private int dateCompare;
private String date, name, time, distance, mood, weight, sets, reps, memo, type, subtype;
//tag for debug logging.
private static final String TAG = "WOLog";
public WOLog()
{
dateCompare = 0;
date = name = time = distance = mood = weight = sets = reps = memo = type = subtype = null;
}
// Setter Methods
public void setDate(int m, int dy, int yr, int hr, int min){
date = m + "-" + dy + "-" + yr + " " + hr + ":";
if (min < 10) date += "0" + min;
else date += min;
dateCompare += min;
dateCompare += hr * 10;
dateCompare += dy * 1000;
dateCompare += m * 100000;
dateCompare += yr * 10000000;
}
public void setName(String t){ name = t; }
public void setTime(String t){ time = t; }
public void setDistance(String d){ distance = d; }
public void setReps(String r){ reps = r; }
public void setSets(String s){ sets = s; }
public void setWeight(String w){ weight = w;}
public void setMood(String m){ mood = m; }
public void setMemo(String m) { memo = m; }
public void setType(String t) { type = t; }
public void setSubtype(String t) { subtype = t; }
// Getter Methods
// TODO: Remove these if we don't wind up using them for stats
public int getDateCompare(){ return dateCompare; }
public String getDate(){ return date; }
public String getName(){ return name; }
public String getTime(){ return time; }
public String getDistance(){ return distance; }
public String getReps() { return reps; }
public String getSets() { return sets; }
public String getWeight() { return weight; }
public String getMood(){ return mood; }
public String getMemo() { return memo; }
public String getType() { return type; }
public String getSubtype() { return subtype; }
// toString formatted with HTML for ListView
public String toStringList(){
String s = "";
s += "<center><b>" + name + "</b>";
if(date != null){
s += "<br><b>Date: </b>" + date;
}
if(mood != null){
s += "<br><b>Mood: </b>" + mood;
}
s += "</center>";
return s;
}
// toString formatted with HTML for DetailView
public String toStringDetail(){
String s = "";
s += "<center><b>" + name.toUpperCase() + "</b><br>";
s += "<b>(Workout Info):</b><br>";
if(date != null && !date.isEmpty()){
s += "<b>Date: </b>" + date + "<br>";
}
if(time != null && !time.isEmpty()){
s += "<b>Time: </b>" + time + "<br>";
}
if(mood != null && !mood.isEmpty()){
s += "<b>Mood: </b>" + mood + "<br>";
}
if(distance != null && !distance.isEmpty()){
s += "<b>Distance: </b>" + distance + "<br>";
}
if(weight != null && !weight.isEmpty()) {
s += "<b>Weight: </b>" + weight + "<br>";
}
if(sets != null && !sets.isEmpty()) {
s += "<b>Sets: </b>" + sets + "<br>";
}
if(reps != null && !reps.isEmpty()) {
s += "<b>Reps: </b>" + reps + "<br>";
}
if(memo != null && !memo.isEmpty()) {
s += "<b>Memo: </b>" + memo + "<br>";
}
s += "</center>";
return s;
}
// TODO: Write comparable function in WOLog instead of overriding in DataHandler?
//Equals function
@Override
public boolean equals(Object otherLog){
//return true if objects are identical
if (this == otherLog) {
return true;
}
//return false if the otherLog is null
if (otherLog == null) {
return false;
}
//return false if other object is wrong type
if (!(otherLog instanceof WOLog)) {
return false;
}
return (this.getDate().equals(((WOLog)otherLog).getDate()) &&
this.getName().equals(((WOLog)otherLog).getName()) &&
this.getTime().equals(((WOLog)otherLog).getTime()) &&
this.getDistance().equals(((WOLog)otherLog).getDistance()) &&
this.getMood().equals(((WOLog)otherLog).getMood()) &&
this.getWeight().equals(((WOLog)otherLog).getWeight()) &&
this.getSets().equals(((WOLog)otherLog).getSets()) &&
this.getReps().equals(((WOLog)otherLog).getReps()) &&
this.getMemo().equals(((WOLog)otherLog).getMemo()) &&
this.getType().equals(((WOLog)otherLog).getType()) &&
this.getSubtype().equals(((WOLog)otherLog).getSubtype()));
}
//in case this project ever uses hash coding, make sure they know they have to write it
@Override public int hashCode() {
throw new UnsupportedOperationException();
}
//The following functions allow for a WOLog to be passed as a Parcel
public static final Parcelable.Creator<WOLog> CREATOR = new Parcelable.Creator<WOLog>() {
public WOLog createFromParcel(Parcel in) {
return new WOLog(in);
}
public WOLog[] newArray(int size) {
return new WOLog[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(dateCompare);
dest.writeString(name);
dest.writeString(time);
dest.writeString(distance);
dest.writeString(mood);
dest.writeString(date);
dest.writeString(memo);
dest.writeString(weight);
dest.writeString(sets);
dest.writeString(reps);
dest.writeString(type);
dest.writeString(subtype);
}
private WOLog(Parcel in) {
dateCompare = 0;
dateCompare = in.readInt();
name = null;
name = in.readString();
time = null;
time = in.readString();
distance = null;
distance = in.readString();
mood = null;
mood = in.readString();
date = null;
date = in.readString();
memo = null;
memo = in.readString();
weight = null;
weight = in.readString();
sets = null;
sets = in.readString();
reps = null;
reps = in.readString();
type = null;
type = in.readString();
subtype = null;
subtype = in.readString();
}
}
最佳答案
尝试使用 ApacheCommons 的 EqualsBuilder 类:
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
关于java - 检查包裹的自定义对象之间的相等性时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27179466/
我的应用程序从一个有 5 个选项卡的选项卡栏 Controller 开始。一开始,第一个出现了它的名字,但其他四个没有名字,直到我点击它们。然后根据用户使用的语言显示名称。如何在选项卡栏出现之前设置选
我有嵌套数组 json 对象(第 1 层、第 2 层和第 3 层)。我的问题是数据表没有出现。任何相关的 CDN 均已导入。该表仅显示部分。我引用了很多网站,但都没有解决我的问题。 之前我使用标准表来
我正在尝试设置要显示的 Parse PFLoginViewController。这是我的一个 View Controller 的类。 import UIKit import Parse import
我遇到了这个问题,我绘制的对象没有出现在 GUI 中。我知道它正在被处理,因为数据被推送到日志文件。但是,图形没有出现。 这是我的一些代码: public static void main(Strin
我有一个树状图,其中包含出现这样的词...... TreeMap occurrence = new TreeMap (); 字符串 = 单词 整数 = 出现次数。 我如何获得最大出现次数 - 整数,
因此,我提示用户输入变量。如果变量小于 0 且大于 10。如果用户输入 10,我想要求用户再次输入数字。我问时间的时候输入4,它说你输入错误。但在第二次尝试时效果很好。例如:如果我输入 25,它会打印
我已经用 css overflow 属性做了一个例子。在这个例子中我遇到了一个溢出滚动的问题。滚动条出现了,但没有工作意味着每当将光标移动到滚动条时,在这个滚动条不活动的时间。我对此一无所知,所以请帮
我现在正在做一个元素。当您单击一个元素时,会出现以下信息,我想知道如何在您单击下一个元素而不重新单击同一元素时使其消失....例如,我的元素中有披萨,我想单击肉披萨看到浇头然后点击奶酪披萨看到浇头和肉
我有一个路由器模块,它将主题与正则表达式进行比较,并将出现的事件与一致的键掩码链接起来。 (它是一个简单的 url 路由过滤,如 symfony http://symfony.com/doc/curr
这个问题在这里已经有了答案: 9年前关闭。 Possible Duplicate: mysql_fetch_array() expects parameter 1 to be resource, bo
我在底部有一个带有工具栏的 View ,我正在使用 NavigationLink 导航到该 View 。但是当 View 出现时,工具栏显示得有点太低了。大约半秒钟后,它突然跳到位。它只会在应用程序启
我试图在我的应用程序上为背景音乐添加一个 AVAudioPlayer,我正在主屏幕上启动播放器,尝试在应用程序打开时开始播放但出现意外行为... 它播放并立即不断创建新玩家并播放这些玩家,因此同时播放
这是获取一个数字,获取其阶乘并将其加倍,但是由于基本情况,如果您输入 0,它会给出 2 作为答案,因此为了绕过它,我使用了 if 语句,但收到错误输入“if”时解析错误。如果你们能提供帮助,我真的很感
暂停期间抛出异常 android.os.DeadObjectException 在 android.os.BinderProxy.transactNative( native 方法) 在 androi
我已经为猜词游戏编写了一些代码。它从用户输入中读取字符并在单词中搜索该字符;根据字符是否在单词中,程序返回并控制一些变量。 代码如下: import java.util.Random; import
我是自动化领域的新手。这是我的简单 TestNG 登录代码,当我以 TestNG 身份运行该代码时,它会出现 java.lang.NullPointerException,双击它会突出显示我导航到 U
我是c#程序员,我习惯了c#的封装语法和其他东西。但是现在,由于某些原因,我应该用java写一些东西,我现在正在练习java一天!我要创建一个为我自己创建一个虚拟项目,以便让自己更熟悉 Java 的
我正在使用 Intellij,我的源类是 main.com.coding,我的资源文件是 main.com.testing。我将 spring.xml 文件放入资源文件中。 我的测试类位于 test.
我想要我的tests folder separate到我的应用程序代码。我的项目结构是这样的 myproject/ myproject/ myproject.py moduleon
这个问题已经有答案了: What is a NullPointerException, and how do I fix it? (12 个回答) 已关闭 6 年前。 因此,我尝试比较 2 个值,一个
我是一名优秀的程序员,十分优秀!