- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
好的。这是场景。我有一个表单,用户填写该表单以创建一个 Match 对象。我使用 IntentService
在后台线程上将信息写入文件。如果在 intent
中传递了一个“true”的 boolean
,那么相应的 ScoreFile
也会被写入。 GlobalMatch
是一个单例对象 下面是 IntentService
代码:
public class WriteMatchService extends IntentService {
private static final String EXTRA_SCORES_FILE = "scores_file";
public static final String REFRESH_MATCH_LIST_INTENT_FILTER = "refresh_match_list";
public static Intent getIntent(Context context, boolean writeScoresFile) {
Intent intent = new Intent(context.getApplicationContext(),
WriteMatchService.class);
intent.putExtra(EXTRA_SCORES_FILE, writeScoresFile);
return intent;
}
public WriteMatchService() {
super("WriteMatchService");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
boolean writeScoresFile = false;
if (intent != null) {
if (intent.hasExtra(EXTRA_SCORES_FILE)) {
writeScoresFile = intent.getBooleanExtra(EXTRA_SCORES_FILE, false);
}
} else {
// this should never happen
return;
}
Context context = getApplicationContext();
// globalMatch is a singleton object
GlobalMatch globalMatch = GlobalMatch.getInstance(context);
Match match = globalMatch.getCurrentMatch();
if (writeScoresFile) {
FileUtils.writeScoresFile(context, new ScoresFile(match.getMatchId()));
}
FileUtils.writeMatchToFile(context, match);
// notify the match list to reload its contents if necessary
Intent messageIntent = new Intent(REFRESH_MATCH_LIST_INTENT_FILTER);
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getApplicationContext());
manager.sendBroadcast(messageIntent);
}
}
Match文件和Scores文件的两种写法:
匹配文件:
public static void writeMatchToFile(Context context, Match match) {
File file = new File(context.getFilesDir(), Match.getFileName(match.getMatchId().toString()));
String jsonString = "";
FileOutputStream fos = null;
jsonString = new Gson().toJson(match);
try {
fos = context.openFileOutput(file.getName(), Context.MODE_PRIVATE);
fos.write(jsonString.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// after creating match, make it the current one
SharedPreferences.Editor editor = context.getSharedPreferences(MY_GLOBAL_MATCH,
Context.MODE_PRIVATE).edit();
editor.putString(CURRENT_MATCH, jsonString);
editor.apply();
}
匹配对象包含一个 Stage
对象列表。
这是匹配类:
public class Match implements Parcelable {
private static final String TAG = "Match";
private UUID mMatchId;
private String mClubId;
private String mMatchName;
private Date mMatchDate;
private MatchLevel mMatchLevel;
private List<Stage> mStages;
private List<Competitor> mCompetitors;
private String mPassword;
private MatchType mMatchType;
public enum MatchType {
USPSA("USPSA"), ACTION_STEEL("Action Steel");
private String name;
MatchType(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
private enum MatchLevel {
I("I"), II("II"), III("III"), IV("IV"), V("V");
private String value;
MatchLevel(String value){
this.value = value;
}
@Override
public String toString() {
return value;
}
}
// no arg constructor, most likely to be used as initial match created upon installation
public Match() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
mMatchDate = calendar.getTime();
mMatchType = MatchType.USPSA;
mMatchId = UUID.randomUUID();
mMatchName = "";
mMatchLevel = MatchLevel.I;
mClubId = "";
mStages = new ArrayList<>();
mCompetitors = new ArrayList<>();
mPassword = "";
}
public Match(String matchName, Date matchDate, MatchLevel matchLevel, MatchType matchType, String clubID, String password) {
mMatchId = UUID.randomUUID();
mClubId = clubID;
mMatchName = matchName;
mMatchDate = matchDate;
mMatchLevel = matchLevel;
mMatchType = matchType;
mStages = new ArrayList<>();
mCompetitors = new ArrayList<>();
mPassword = password;
}
public String getPassword() {
return mPassword;
}
public void setPassword(String password) {
mPassword = password;
}
public UUID getMatchId() {
return mMatchId;
}
public String getClubId() {
return mClubId;
}
public void setClubId(String clubId) {
mClubId = clubId;
}
public String getMatchName() {
return mMatchName;
}
public void setMatchName(String matchName) {
mMatchName = matchName;
}
public Date getMatchDate() {
return mMatchDate;
}
public void setMatchDate(Date matchDate) {
mMatchDate = matchDate;
}
public MatchLevel getMatchLevel() {
return mMatchLevel;
}
public String getMatchLevelString() {
return mMatchLevel.toString();
}
public void setMatchLevel(MatchLevel matchLevel) {
mMatchLevel = matchLevel;
}
public void setMatchLevel(String str){
switch (str){
case "I":
mMatchLevel = MatchLevel.I;
break;
case "II":
mMatchLevel = MatchLevel.II;
break;
case "III":
mMatchLevel = MatchLevel.III;
break;
case "IV":
mMatchLevel = MatchLevel.IV;
break;
case "V":
mMatchLevel = MatchLevel.V;
break;
default:
Log.d(TAG, "Something went wrong");
}
}
public MatchType getMatchType() {
return mMatchType;
}
public static MatchType getMatchTypeFromString(String matchType){
switch (matchType){
case "USPSA":
return MatchType.USPSA;
case "Action Steel":
return MatchType.ACTION_STEEL;
default:
return null;
}
}
public String getMatchTypeString(){
return mMatchType.toString();
}
public void setMatchType(MatchType matchType){ mMatchType = matchType;}
public void setMatchType(String matchType) {
switch (matchType){
case "USPSA":
mMatchType = MatchType.USPSA;
break;
case "Action Steel":
mMatchType = MatchType.ACTION_STEEL;
break;
default:
Log.d(TAG, "Something went wrong");
}
}
public void addStage(Stage stage) {
mStages.add(stage);
}
public List<Stage> getStages() {
return mStages;
}
public void setStages(List<Stage> stages) {
mStages = stages;
}
public List<Competitor> getCompetitors() {
return mCompetitors;
}
public void setCompetitors(List<Competitor> competitors) {
mCompetitors = competitors;
}
public void addCompetitor(Competitor competitor) {
// if adding a competitor here, assign the competitor a shooter number
competitor.setShooterNum(mCompetitors.size() + 1);
mCompetitors.add(competitor);
}
public void updateCompetitorInMatch(Competitor comp) {
for (Competitor c : mCompetitors) {
// this works because both will have the same ID
if (c.equals(comp) && (c.getShooterNum() == comp.getShooterNum())) {
mCompetitors.remove(c);
mCompetitors.add(comp);
break;
}
}
}
public void updateStageInMatch(Stage stage){
for (Stage s : mStages){
if(stage.equals(s)){
mStages.remove(s);
mStages.add(stage);
break;
}
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Match match = (Match) o;
return Objects.equals(mMatchId, match.mMatchId);
}
@Override
public int hashCode() {
return 7 * mMatchId.hashCode();
}
public static String getFileName(String matchID) {
return "match." + matchID + ".json";
}
public static String formatMatchDate(Date date){
return (String) DateFormat.format("MM/dd/yyyy", date);
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeSerializable(this.mMatchId);
dest.writeString(this.mClubId);
dest.writeString(this.mMatchName);
dest.writeLong(this.mMatchDate != null ? this.mMatchDate.getTime() : -1);
dest.writeInt(this.mMatchLevel == null ? -1 : this.mMatchLevel.ordinal());
dest.writeTypedList(this.mStages);
dest.writeTypedList(this.mCompetitors);
dest.writeString(this.mPassword);
dest.writeInt(this.mMatchType == null ? -1 : this.mMatchType.ordinal());
}
protected Match(Parcel in) {
this.mMatchId = (UUID) in.readSerializable();
this.mClubId = in.readString();
this.mMatchName = in.readString();
long tmpMMatchDate = in.readLong();
this.mMatchDate = tmpMMatchDate == -1 ? null : new Date(tmpMMatchDate);
int tmpMMatchLevel = in.readInt();
this.mMatchLevel = tmpMMatchLevel == -1 ? null : MatchLevel.values()[tmpMMatchLevel];
this.mStages = in.createTypedArrayList(Stage.CREATOR);
this.mCompetitors = in.createTypedArrayList(Competitor.CREATOR);
this.mPassword = in.readString();
int tmpMMatchType = in.readInt();
this.mMatchType = tmpMMatchType == -1 ? null : MatchType.values()[tmpMMatchType];
}
public static final Creator<Match> CREATOR = new Creator<Match>() {
@Override
public Match createFromParcel(Parcel source) {
return new Match(source);
}
@Override
public Match[] newArray(int size) {
return new Match[size];
}
};
}
这是 Stage
表单文件的一部分,我在其中收集字段并创建 IntentService:
{
mStage.setTime(Double.valueOf(mTime.getText().toString()));
mStage.setScoringType(Stage.getScoringTypeFromString(mScoringTypeSpinner.getSelectedItem().toString()));
mStage.setSteelTargets(Integer.valueOf(mSteelTargets.getText().toString()));
mStage.setSteelNPMs(Integer.valueOf(mSteelNPMs.getText().toString()));
mStage.setNoShoots(mNoShoots.isChecked());
mStage.setRounds(mStage.getNumberOfSteelTargets());
mStage.setPoints(mStage.getNumberOfSteelTargets() * 5);
// if creating a new stage include a stage number in the stage name
if (!mEditing) {
int stageNum = (mMatch.getStages().size() + 1);
mStage.setStageNum(stageNum);
mStage.setStageName("Stage " + stageNum + ": " + mStageName.getText().toString());
mMatch.addStage(mStage);
Intent serviceIntent = WriteMatchService.getIntent(mContext, false);
mContext.startService(serviceIntent);
} else if (mEditing) {
// if editing an existing stage, only edit the part of the name after the stage number
mStage.setStageName(getNamePrefix(mStage.getStageName()) + mStageName.getText().toString());
mMatch.updateStageInMatch(mStage);
Intent serviceIntent = WriteMatchService.getIntent(mContext, false);
mContext.startService(serviceIntent);
}
}
服务启动后,我将用户发送到另一个 fragment 。注意:该服务应该运行得非常快。我一直收到 java.util.ConcurrentModificationException,但只是偶尔出现一次。 这并非每次都会发生。我无法确定为什么会出现此错误。 Android Studio 将我指向 WriteMatchToFile(Context, Match)
方法中的“jsonString = new Gson().toJson(match);
”这一行。我错过了什么?
这是显示错误的堆栈跟踪部分:
--------- beginning of crash
2018-11-25 11:20:30.194 13665-13777/com.patgekoski.ez_score E/AndroidRuntime: FATAL EXCEPTION: IntentService[WriteMatchService]
Process: com.patgekoski.ez_score, PID: 13665
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.next(ArrayList.java:860)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:96)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:61)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:69)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:127)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:245)
at com.google.gson.Gson.toJson(Gson.java:704)
at com.google.gson.Gson.toJson(Gson.java:683)
at com.google.gson.Gson.toJson(Gson.java:638)
at com.google.gson.Gson.toJson(Gson.java:618)
at com.patgekoski.ez_score.util.FileUtils.writeMatchToFile(FileUtils.java:75)
at com.patgekoski.ez_score.services.WriteMatchService.onHandleIntent(WriteMatchService.java:63)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:76)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.os.HandlerThread.run(HandlerThread.java:65)
2018-11-25 11:20:30.198 1699-13283/system_process W/ActivityManager: Force finishing activity com.patgekoski.ez_score/.StagesListActivity
最佳答案
如您所述,Match
对象包含 List<Stage>
Match objects contain a list of Stage objects.
问题是虽然 Gson#toJson()
正在处理您的 Match
对象并将其转换为 JSON,它还必须遍历 List<Stage>
使用迭代器并处理它们。有时(当您的应用程序失败时),迭代器被 Gson 用于转换过程,另一个线程修改 List<Stage>
因为它恰好是 Singleton 的嵌套字段。迭代器的 next()
在 Gson 的方法中调用的方法抛出 ConcurrentModificationException
如果自从从列表中获取迭代器后列表已被修改。
解决方案
您希望如何处理此故障取决于您的应用程序的性质(文件的保存方式)。
解决方案之一是使用 CopyOnWriteArrayList
用于存储 Stage
Match
中的对象目的。它为 Iterator
使用列表的副本.对实际列表的修改不会影响 Iterator
.
另可至synchronise
您编写 Match
的方法反对文件并修改它们。
引用this post有关更多信息 ConcurrentModificationException
s 以及如何避免它们。
关于java.util.ConcurrentModificationException -- 执行 IO 操作时的错误(不是列表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53470042/
我在这个网站上发布的代码有这个问题 https://developers.google.com/drive/quickstart-cs是 Google Drive 快速入门的开发人员站点。我按照网站上
我正在尝试制作一个非常简单的 Kafka Producer,目前正在关注 producer example除了我的制作人没有分区程序类。 将所需文件导出到 jar 后,我将它们传输到我的 Linux
问题 在java中,我有一个“Util项目”,在进行单元测试时使用另一个“Mock项目”。 我的问题是“模拟项目”也使用“Util项目”来构建一些模拟对象。 当我使用 Maven 构建项目时,我无法构
据我所知,这些包已经存在很长时间了。但是,我从未见过它们的实际用法。而且这些包似乎不成熟,不再维护。如果是,为什么这些包现在存在? 最佳答案 包裹automata被 scala.xml.dtd 使用,
关闭。这个问题需要debugging details .它目前不接受答案。 想改进这个问题?将问题更新为 on-topic对于堆栈溢出。 1年前关闭。 Improve this question Co
在java.util.Collections中,有一个方法: public static void fill(List list, T obj) 用第二个参数指定的对象填充第一个参数指定的List。
我不明白它要我做什么。分配给 sentence正在工作: val sentences : java.util.List[CoreMap] = document.get(classOf[Sentence
在我的 React 应用程序中,我想使用一些实用程序。我见过两种不同的方法。第一个是,只是创建函数并将其导出。第二个是,创建一个 Util 类并导出一个对象,这样它就不能被实例化(静态类)。 clas
我有一个 util 类,它接受 String jwtToken 和 Key key 并使用 io.jsonwebtoken.jwts 解码 jwt。 但是,我无法对此进行测试。原因是,我无法模拟公钥并
我有使用目标命名空间的专有架构 xmlns:ax216="http://util.java/xsd" 这给我带来了从 java (java.util.xsd) 开始生成禁止的(由 Java 安全管理器
我正在阅读集合以查看 Javadocs 中的实现层次结构。 Collections声明为public class Collections extendds Object Collection声明为pu
我正在使用 Spring-boot 应用程序,我可以在其中连接 Azure 应用程序配置。但是当我尝试使用内容类型应用程序/JSON 读取值时出现错误。 我的Java类 @ConfigurationP
我正在使用 Spring-boot 应用程序,我可以在其中连接 Azure 应用程序配置。但是当我尝试使用内容类型应用程序/JSON 读取值时出现错误。 我的Java类 @ConfigurationP
我在使用格式说明符时遇到问题。这是否意味着我正在使用 %d? public static void main(String[] args) { double y, x; for (x =
鉴于此代码 import java.util.Iterator; private static List someList = new ArrayList(); public static void
我正在 HackerEarth 解决问题,我无法弄清楚为什么我的程序在命令行上正确运行并给出正确的结果,但在代码编辑器上运行时却给出 java.util.NoSuchElementException
我正在尝试使用以下代码使用对象列表列表中的数据填充tableModel readExcel.readSheet(0): TableModel tableModel = new DefaultTabl
java.util.Set 、 java.util.List 和其他 Collection 接口(interface)不可序列化。需要一个简单、直接的解决方案来在可序列化的 POJO 中使用它。 pu
我试图从 servlet 返回数据库搜索结果的 ArrayList 以显示在 jsp 页面上。 在servlet中设置arraylist作为请求的属性,并将请求转发到jsp页面。当我尝试在 jsp 页
我是android新手,最近我试图从firebase中提取数据到recyclerview/cardview中以垂直布局显示数据,它显示将Hashmap转换为Arraylist的错误,其中代码是:
我是一名优秀的程序员,十分优秀!