Добрый день всем, я студент университета, и я решил сделать игру-кликер для удовольствия, и до сих пор она шла очень хорошо, потому что я наткнулся на "ошибку", которую я не могу понять:
У меня есть абстрактный класс под названием «UpgradesClick», в котором есть все обновления кликов, как показано ниже: Абстрактное дерево классов
Мой абстрактный класс "UpgradesClick" реализует Parcelable (я пытался передать его через Intent.PutExtra, но он не работал) Abstract Class
Тогда я подумал, что SharedPreferences спасет меня, потому что я уже слышал о них, и я хочу, чтобы в моем хранилище Upgrade Click выполнялся вызов save () onPause () Method , чтобы сохранить все значения объекта, уровень и цена, поэтому я решил создать ArrayList для абстрактного класса UpgradeClick и всех их внутри. Добавление объектов в ArrayList
Затем я написал типичные вызовы SharedPreferences Save () и Load (), и всякий раз, когда я перехожу из MainActivity в Store, он показывает, что данные были загружены (1) *, но когда я возвращаюсь в MainActivity, игра вылетает, и устанавливает все мои значения обратно в 0 (2) * --- * см. здесь
И вот моя проблема: я получаю сообщение об ошибке в методе onSave (), которое не могу понять, поскольку оно ничего не подчеркивает. Методы Save () и Load ()
Это выдает ошибку "json = gson.toJson (todosUpgradesClick);" который я предполагаю, где я конвертирую ArrayList в файл Json.
Действительно печально, что такая вещь, как «отправка объектов в другие виды деятельности», не позволяет мне продолжить игру, потому что большая часть кода игры просто добавляет значение каждого класса и умножается на другие в моем методе onClick.
Также извините за то, что не разместил какой-либо код в сообщении, но он был настолько большим, что я подумал, что никто не потрудится прочитать. Большое спасибо за ваше время, дорогие переполнения стека;)
PS: В случае, если вы задаетесь вопросом о «Списке», сначала я использовал ArrayList, но он не сработал, поэтому часть скриншота, где написано «Список», также была опробована как ArrayList.
И еще раз, спасибо за ваше время и терпение.
Редактировать - добавлен код и журнал ошибок
Код:
>
import android.app.Activity;
import android.os.Parcel;
import android.os.Parcelable;
import android.widget.TextView;
public abstract class UpgradesClick extends MainActivity implements Parcelable {
private int nivel;
private int preco;
private int precoBase;
private int valorGanhoPorClick;
Activity act;
//private TextView tvQtdPClick;
private TextView tvnivel;
private TextView tvpreco;
protected UpgradesClick(Activity act, int nivel, int precoBase){
//setTvQtdPClick( (TextView) act.findViewById(R.id.qtdcuspopc) );
this.nivel = nivel;
this.precoBase = precoBase;
this.act = act;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(nivel);
out.writeInt(preco);
}
protected UpgradesClick(Parcel in) {
nivel = in.readInt();
preco = in.readInt();
}
public void comprarUpgrade(){
setNivel( getNivel() + 1 );
setPreco( getNivel() * 5 );
setValorGanhoPorClick( getNivel() );
}
public float getValorGanhoPorClick() {
return valorGanhoPorClick;
}
public void setValorGanhoPorClick(int valorGanhoPorClick) {
this.valorGanhoPorClick = valorGanhoPorClick;
}
public int getPrecoBase() {
return precoBase;
}
public void setPrecoBase(int precoBase) {
this.precoBase = precoBase;
}
public void setPreco(int preco) {
this.preco = preco;
}
public int getPreco(){
if (getNivel() == 0){
return precoBase;
}else {
return preco;
}
}
public int getNivel() {
return nivel;
}
public void setNivel(int nivel) {
this.nivel = nivel;
}
public void setTvnivel(TextView tvnivel) {
this.tvnivel = tvnivel;
}
public TextView getTvnivel() {
return tvnivel;
}
public void setTvpreco(TextView tvpreco) {
this.tvpreco = tvpreco;
}
public TextView getTvpreco() {
return tvpreco;
}
}
class UpgradeClick_Gosma extends UpgradesClick{
public UpgradeClick_Gosma(Activity act, int nivel, int precoBase) {
super(act, nivel, precoBase);
setValorGanhoPorClick(getNivel());
setPreco(getPrecoBase() * getNivel());
}
public static final Parcelable.Creator<UpgradeClick_Gosma> CREATOR = new Parcelable.Creator<UpgradeClick_Gosma>() {
public UpgradeClick_Gosma createFromParcel(Parcel in) {
return new UpgradeClick_Gosma(in);
}
@Override
public UpgradeClick_Gosma[] newArray(int size) {
return new UpgradeClick_Gosma[size];
}
};
public UpgradeClick_Gosma(Parcel in) {
super(in);
}
@Override
public int describeContents() {
return 0;
}
}
class UpgradeClick_Dedeta extends UpgradesClick{
public UpgradeClick_Dedeta(Activity act, int nivel, int precoBase) {
super(act, nivel, precoBase);
setValorGanhoPorClick(getNivel());
setPreco(getPrecoBase() * getNivel());
}
public static final Parcelable.Creator<UpgradeClick_Dedeta> CREATOR = new Parcelable.Creator<UpgradeClick_Dedeta>() {
public UpgradeClick_Dedeta createFromParcel(Parcel in) {
return new UpgradeClick_Dedeta(in);
}
@Override
public UpgradeClick_Dedeta[] newArray(int size) {
return new UpgradeClick_Dedeta[size];
}
};
public UpgradeClick_Dedeta(Parcel in) {
super(in);
}
@Override
public int describeContents() {
return 0;
}
}
class UpgradeClick_Sorte extends UpgradesClick{
public UpgradeClick_Sorte(Activity act, int nivel, int precoBase) {
super(act, nivel, precoBase);
setValorGanhoPorClick(getNivel());
setPreco(getPrecoBase() * getNivel());
}
public static final Parcelable.Creator<UpgradeClick_Sorte> CREATOR = new Parcelable.Creator<UpgradeClick_Sorte>() {
public UpgradeClick_Sorte createFromParcel(Parcel in) {
return new UpgradeClick_Sorte(in);
}
@Override
public UpgradeClick_Sorte[] newArray(int size) {
return new UpgradeClick_Sorte[size];
}
};
public UpgradeClick_Sorte(Parcel in) {
super(in);
}
@Override
public int describeContents() {
return 0;
}
}
class UpgradeClick_Douro extends UpgradesClick{
public UpgradeClick_Douro(Activity act, int nivel, int precoBase) {
super(act, nivel, precoBase);
setValorGanhoPorClick(getNivel());
setPreco(getPrecoBase() * getNivel());
}
public static final Parcelable.Creator<UpgradeClick_Douro> CREATOR = new Parcelable.Creator<UpgradeClick_Douro>() {
public UpgradeClick_Douro createFromParcel(Parcel in) {
return new UpgradeClick_Douro(in);
}
@Override
public UpgradeClick_Douro[] newArray(int size) {
return new UpgradeClick_Douro[size];
}
};
public UpgradeClick_Douro(Parcel in) {
super(in);
}
@Override
public int describeContents() {
return 0;
}
}
class UpgradeClick_Agua extends UpgradesClick{
public UpgradeClick_Agua(Activity act, int nivel, int precoBase) {
super(act, nivel, precoBase);
setValorGanhoPorClick(getNivel());
setPreco(getPrecoBase() * getNivel());
}
public static final Parcelable.Creator<UpgradeClick_Agua> CREATOR = new Parcelable.Creator<UpgradeClick_Agua>() {
public UpgradeClick_Agua createFromParcel(Parcel in) {
return new UpgradeClick_Agua(in);
}
@Override
public UpgradeClick_Agua[] newArray(int size) {
return new UpgradeClick_Agua[size];
}
};
public UpgradeClick_Agua(Parcel in) {
super(in);
}
@Override
public int describeContents() {
return 0;
}
}
- код магазина деятельности
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.List;
public class UpgradeClickActvity extends AppCompatActivity {
//UpgradesClick.UpgradeClick1 upgrade;
Intent intent;
int[] IMAGEM = {R.drawable.upgradespit1, R.drawable.upgradespit2, R.drawable.upgradespit3, R.drawable.upgradespit4, R.drawable.upgradespit5};
int[] NOME = {R.string.UpgradeClick1Titulo, R.string.UpgradeClick2Titulo, R.string.UpgradeClick3Titulo, R.string.UpgradeClick4Titulo, R.string.UpgradeClick5Titulo};
int[] DESCRICAO = {R.string.UpgradeClick1Descricao, R.string.UpgradeClick2Descricao, R.string.UpgradeClick3Descricao, R.string.UpgradeClick4Descricao, R.string.UpgradeClick5Descricao};
UpgradeClick_Gosma upgradeclickgosma;
UpgradeClick_Dedeta upgradeclickdedeta;
UpgradeClick_Sorte upgradeclicksorte;
UpgradeClick_Douro upgradeclickdouro;
UpgradeClick_Agua upgradeclickagua;
List<UpgradesClick> todosUpgradesClick;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upgrades_click);
todosUpgradesClick = new ArrayList<>();
loadData();
Intent intent = getIntent();
Cuspo cuspo = (Cuspo) intent.getParcelableExtra("objCuspo");
TextView textoQtdCuspo = (TextView)findViewById(R.id.lojaQtdCuspo);
textoQtdCuspo.setText(String.valueOf(cuspo.getQtd()));
TextView textoQtdCuspoUni = (TextView)findViewById(R.id.lojaQtdCuspoUni);
textoQtdCuspoUni.setText(String.valueOf(cuspo.getQtdUni()));
upgradeclickgosma = new UpgradeClick_Gosma(this, 0, 20);
upgradeclickdedeta = new UpgradeClick_Dedeta(this, 0, 100);
upgradeclicksorte = new UpgradeClick_Sorte(this, 0, 500);
upgradeclickdouro = new UpgradeClick_Douro(this, 0, 1000);
upgradeclickagua = new UpgradeClick_Agua(this, 0, 5000);
todosUpgradesClick.add(upgradeclickgosma);
todosUpgradesClick.add(upgradeclickdedeta);
todosUpgradesClick.add(upgradeclicksorte);
todosUpgradesClick.add(upgradeclickdouro);
todosUpgradesClick.add(upgradeclickagua);
ListView listView = (ListView)findViewById(R.id.listviewupgclick);
CustomAdapter customAdapter = new CustomAdapter();
listView.setAdapter(customAdapter);
ImageView btnBack = (ImageView)findViewById(R.id.btnback) ;
btnBack.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent(UpgradeClickActvity.this, MainActivity.class);
intent.putExtra("upggosma", upgradeclickgosma);
//intent.putExtra("upgdedeta", upgradeclickdedeta);
startActivity(intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
}
});
}
@Override
protected void onPause() {
super.onPause();
saveData();
//intent = new Intent(UpgradeClickActvity.this, MainActivity.class);
Toast.makeText(UpgradeClickActvity.this, "Data saved" ,Toast.LENGTH_LONG).show();
}
class CustomAdapter extends BaseAdapter{
@Override
public int getCount() {
return IMAGEM.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
view = getLayoutInflater().inflate(R.layout.upgradestemplate, null);
ImageView imageView = (ImageView)view.findViewById(R.id.template_imagem);
TextView textView_name = (TextView)view.findViewById(R.id.template_titulo);
TextView textView_descricao = (TextView)view.findViewById(R.id.template_descricao);
TextView textView_preco = (TextView)view.findViewById(R.id.template_preco);
TextView textView_nivel = (TextView)view.findViewById(R.id.template_nivel);
imageView.setImageResource(IMAGEM[position]);
textView_name.setText(NOME[position]);
textView_descricao.setText(DESCRICAO[position]);
textView_preco.setText(String.valueOf(todosUpgradesClick.get(position).getPreco()));
textView_nivel.setText(String.valueOf(todosUpgradesClick.get(position).getNivel()));
return view;
}
}
private void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(todosUpgradesClick);
editor.putString("todosUpgradesClick", json);
editor.apply();
}
private void loadData(){
Toast.makeText(UpgradeClickActvity.this, "Carregou dados" ,Toast.LENGTH_LONG).show();
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("todosUpgradesClick", null);
Type type = new TypeToken<List<UpgradesClick>>() {}.getType();
todosUpgradesClick = gson.fromJson(json, type);
if(todosUpgradesClick == null){
todosUpgradesClick = new ArrayList<UpgradesClick>();
}
}
}
И, наконец, журнал ошибок:
2018-10-30 21:34:44.470 1843-1963/? E/LogCollectService: illegal eventid
2018-10-30 21:34:45.343 12820-12820/? E/XmlParser: startElement mResult:1024
2018-10-30 21:34:45.343 12820-12820/? E/XmlParser: startElement mResult:2097152
2018-10-30 21:34:45.351 408-2015/? E/ion: set flags ioctrl failed!
2018-10-30 21:34:45.439 12706-12706/paixao.com.findingdawae E/AndroidRuntime: FATAL EXCEPTION: main
Process: paixao.com.findingdawae, PID: 12706
java.lang.RuntimeException: Unable to pause activity {paixao.com.findingdawae/paixao.com.findingdawae.UpgradeClickActvity}: java.lang.SecurityException: Can not make a java.lang.reflect.Method constructor accessible
at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3952)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3918)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3892)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3860)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1588)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
Caused by: java.lang.SecurityException: Can not make a java.lang.reflect.Method constructor accessible
at java.lang.reflect.AccessibleObject.setAccessible0(AccessibleObject.java:133)
at java.lang.reflect.AccessibleObject.setAccessible(AccessibleObject.java:119)
at com.google.gson.internal.reflect.PreJava9ReflectionAccessor.makeAccessible(PreJava9ReflectionAccessor.java:31)
at com.google.gson.internal.ConstructorConstructor.newDefaultConstructor(ConstructorConstructor.java:103)
at com.google.gson.internal.ConstructorConstructor.get(ConstructorConstructor.java:85)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:101)
at com.google.gson.Gson.getAdapter(Gson.java:458)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:117)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:166)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:102)
at com.google.gson.Gson.getAdapter(Gson.java:458)
at com.google.gson.internal.bind.ArrayTypeAdapter$1.create(ArrayTypeAdapter.java:48)
at com.google.gson.Gson.getAdapter(Gson.java:458)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:117)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:166)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:102)
at com.google.gson.Gson.getAdapter(Gson.java:458)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:117)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:166)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:102)
at com.google.gson.Gson.getAdapter(Gson.java:458)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:117)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:166)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:102)
at com.google.gson.Gson.getAdapter(Gson.java:458)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:117)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:166)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:102)
at com.google.gson.Gson.getAdapter(Gson.java:458)
2018-10-30 21:34:45.439 12706-12706/paixao.com.findingdawae E/AndroidRuntime: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:117)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:166)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:102)
at com.google.gson.Gson.getAdapter(Gson.java:458)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:56)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:97)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:61)
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 paixao.com.findingdawae.UpgradeClickActvity.saveData(UpgradeClickActvity.java:133)
at paixao.com.findingdawae.UpgradeClickActvity.onPause(UpgradeClickActvity.java:87)
at android.app.Activity.performPause(Activity.java:7071)
at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1335)
at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3941)
... 11 more
2018-10-30 21:34:45.443 1218-4703/? E/ReportTools: This is not beta user build
2018-10-30 21:34:45.518 554-830/? E/logserver: imonitor_add_dynamic_path, path:/data/system/dropbox/data_app_crash@1540935285455.txt.gz
2018-10-30 21:34:45.635 1218-6950/? E/HsmCoreServiceImpl: onTransact in code is: 102
2018-10-30 21:34:45.678 1020-12064/? E/AsyncOperation: serviceID=40, operation=LogOperation
OperationException[Status{statusCode=Log from CONTEXT_MANAGER dropped because of storage full, resolution=null}]
at oxj.a(:com.google.android.gms@14366021@14.3.66 (040408-213742215):72)
at xey.run(:com.google.android.gms@14366021@14.3.66 (040408-213742215):27)
at bdrz.run(:com.google.android.gms@14366021@14.3.66 (040408-213742215):2)
at qjt.run(:com.google.android.gms@14366021@14.3.66 (040408-213742215):35)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at qpu.run(:com.google.android.gms@14366021@14.3.66 (040408-213742215))
at java.lang.Thread.run(Thread.java:776)
2018-10-30 21:34:45.685 1020-12064/? E/AsyncOperation: serviceID=40, operation=LogOperation
OperationException[Status{statusCode=Log from LB_COUNTERS dropped because of storage full, resolution=null}]
at oxj.a(:com.google.android.gms@14366021@14.3.66 (040408-213742215):72)
at xey.run(:com.google.android.gms@14366021@14.3.66 (040408-213742215):27)
at bdrz.run(:com.google.android.gms@14366021@14.3.66 (040408-213742215):2)
at qjt.run(:com.google.android.gms@14366021@14.3.66 (040408-213742215):35)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at qpu.run(:com.google.android.gms@14366021@14.3.66 (040408-213742215))
at java.lang.Thread.run(Thread.java:776)
2018-10-30 21:34:45.720 1020-12064/? E/AsyncOperation: serviceID=40, operation=LogOperation
OperationException[Status{statusCode=Log from CONTEXT_MANAGER dropped because of storage full, resolution=null}]
at oxj.a(:com.google.android.gms@14366021@14.3.66 (040408-213742215):72)
at xey.run(:com.google.android.gms@14366021@14.3.66 (040408-213742215):27)
at bdrz.run(:com.google.android.gms@14366021@14.3.66 (040408-213742215):2)
at qjt.run(:com.google.android.gms@14366021@14.3.66 (040408-213742215):35)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at qpu.run(:com.google.android.gms@14366021@14.3.66 (040408-213742215))
at java.lang.Thread.run(Thread.java:776)