Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serialization of Character Data #35

Merged
merged 20 commits into from
Oct 19, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.example.cis.mazeminotaurs;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

/**
* Created by jsmith on 10/18/17.
*/

public class CharacerSelectionFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater li, ViewGroup vg, Bundle b) {
super.onCreateView(li, vg, b);
View view = li.inflate(R.layout.fragment_character_selection, vg, false);

ListView charListView = (ListView) view.findViewById(R.id.character_list_view);
charListView.setAdapter(new CharacterAdapter(getContext()));

charListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Portfolio.get().setActiveCharacterIndex(i);
}
});

return view;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.example.cis.mazeminotaurs;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.cis.mazeminotaurs.character.PlayerCharacter;

import java.util.ArrayList;

/**
* Created by jsmith on 10/18/17.
*/

public class CharacterAdapter extends BaseAdapter {
private Portfolio mPortfolio = Portfolio.get();
private Context mContext;

public CharacterAdapter(Context context) {
mContext = context;
}

public void removeCharacter(int i) {
mPortfolio.deletePlayerCharacter(mPortfolio.getPlayerCharacter(i));
notifyDataSetChanged();
}

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

@Override
public PlayerCharacter getItem(int i) {
return mPortfolio.getPlayerCharacter(i);
}

@Override
public long getItemId(int i) {
return getItem(i).getCharClass().getResId();
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
view = LayoutInflater.from(mContext)
.inflate(R.layout.spinner_item_character, viewGroup, false);
}

TextView nameView = (TextView) view.findViewById(R.id.character_name_view);
TextView classView = (TextView) view.findViewById(R.id.character_class_view);
TextView levelView = (TextView) view.findViewById(R.id.character_level_view);

nameView.setText(getItem(i).getName());
classView.setText(getItem(i).getCharClass().getResId());
levelView.setText(String.valueOf(getItem(i).getCharClass().getLevel()));
return view;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.example.cis.mazeminotaurs;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

/**
* Created by jsmith on 10/19/17.
*/

public class CharacterDeletionFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater li, ViewGroup vg, Bundle b) {
super.onCreateView(li, vg, b);
View view = li.inflate(R.layout.fragment_character_selection, vg, false);

final ListView charListView = (ListView) view.findViewById(R.id.character_list_view);
charListView.setAdapter(new CharacterAdapter(getContext()));

charListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (charListView.getAdapter().getCount() > 1) {
((CharacterAdapter) charListView.getAdapter()).removeCharacter(i);
} else {
Toast.makeText(getContext(), R.string.error_delete_character, Toast.LENGTH_SHORT).show();
}
}
});

return view;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
Expand Down Expand Up @@ -77,6 +78,7 @@ public View onCreateView(LayoutInflater li, ViewGroup vg, Bundle b){
View rootView = li.inflate(R.layout.fragment_character_sheet, vg, false);

mCurrentCharacterIndex = mPortfolio.getActiveCharacterIndex();
Log.d(TAG, String.valueOf(mPortfolio.getActiveCharacterIndex()));

mSheetPlayerCharacter = mPortfolio.getPlayerCharacter(mCurrentCharacterIndex);
mCharacterLevelView = (TextView) rootView.findViewById(R.id.character_level_view);
Expand Down Expand Up @@ -208,6 +210,7 @@ public void onClick(View v){
});

mEquippedWeaponSpinner = (Spinner) rootView.findViewById(R.id.equipped_weapon_spinner);
System.out.println(mSheetPlayerCharacter.getInventory());
DetailedWeaponAdapter weaponAdapter = new DetailedWeaponAdapter(getContext(), mSheetPlayerCharacter.getWeapons());
mEquippedWeaponSpinner.setAdapter(weaponAdapter);
//Get equipped weapon from character Class
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.example.cis.mazeminotaurs;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
Expand All @@ -12,13 +13,25 @@
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.example.cis.mazeminotaurs.NewCharacter.CharacterCreationFragment;
import com.example.cis.mazeminotaurs.character.PlayerCharacter;
import com.example.cis.mazeminotaurs.character.SaveAndLoadPerformer;
import com.example.cis.mazeminotaurs.util.Util;
import com.example.cis.mazeminotaurs.web_resources.CompanionFragment;
import com.example.cis.mazeminotaurs.web_resources.PlayerManualFragment;
import com.example.cis.mazeminotaurs.web_resources.WebsiteFragment;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainMazes extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {

Expand All @@ -28,8 +41,27 @@ public class MainMazes extends AppCompatActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
String basePath = getApplicationContext().getFilesDir().getPath() + "/";
FileInputStream fis = new FileInputStream(basePath + Portfolio.FILENAME);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new BufferedInputStream(fis)));

StringBuilder builder = new StringBuilder();
String line = bufferedReader.readLine();
while (line != null && !line.equals("")) {
builder.append(line);
line = bufferedReader.readLine();
}
SaveAndLoadPerformer.loadPortfolio(builder.toString());
} catch (IOException e) {
e.printStackTrace();
}

mPortfolio = Portfolio.get();
if (mPortfolio.getPortfolio() == null) {
mPortfolio.resetPortfolio();
mPortfolio.addPlayerCharacter(Util.createDummyCharacter());
}
mEquipment = EquipmentDB.getInstance();

try{
Expand Down Expand Up @@ -85,6 +117,17 @@ public boolean onOptionsItemSelected(MenuItem item) {
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
} else if (id == R.id.action_save_portfolio) {
try {
FileOutputStream fos = getApplicationContext().openFileOutput(Portfolio.FILENAME, Context.MODE_PRIVATE);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
outputStreamWriter.write(SaveAndLoadPerformer.savePortfolio());
outputStreamWriter.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}

return super.onOptionsItemSelected(item);
Expand All @@ -105,8 +148,10 @@ public boolean onNavigationItemSelected(MenuItem item) {
contentFragment = new CharacterCreationFragment();
} else if (id == R.id.play_character) {
contentFragment = new CharacterSheetFragment();
} else if (id == R.id.select_character) {
contentFragment = new CharacerSelectionFragment();
} else if (id == R.id.delete_character) {

contentFragment = new CharacterDeletionFragment();
} else if (id == R.id.player_manual) {
contentFragment = new PlayerManualFragment();
} else if (id == R.id.player_comapanion) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
*/

public class Portfolio {
public static final String FILENAME = "SavedPortfolio";

private static final String TAG = Portfolio.class.getName();
private ArrayList<PlayerCharacter> portfolio;
private static Portfolio sPortfolio;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package com.example.cis.mazeminotaurs.character;

/**
* Created by jsmith on 10/17/17.
*/

import com.example.cis.mazeminotaurs.Armor;
import com.example.cis.mazeminotaurs.Equipment;
import com.example.cis.mazeminotaurs.Mythics;
import com.example.cis.mazeminotaurs.Weapon;
import com.example.cis.mazeminotaurs.character.Gender;
import com.example.cis.mazeminotaurs.character.Money;
import com.example.cis.mazeminotaurs.character.PlayerCharacter;
import com.example.cis.mazeminotaurs.character.classes.BaseClass;
import com.example.cis.mazeminotaurs.character.stats.Score;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.reflect.TypeToken;
import com.google.gson.typeadapters.RuntimeTypeAdapterFactory;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
* Custom serializer for transforming the PlayerCharacter class into json.
*/
public class CharacterSerializer implements JsonSerializer<PlayerCharacter>, JsonDeserializer<PlayerCharacter> {

private static Gson sGson = null;

private static Gson getGson() {
if (sGson == null) {
GsonBuilder builder = new GsonBuilder();
RuntimeTypeAdapterFactory adapter = RuntimeTypeAdapterFactory
.of(Equipment.class)
.registerSubtype(Equipment.class)
.registerSubtype(Weapon.class)
.registerSubtype(Armor.class)
.registerSubtype(Mythics.class);
builder.registerTypeAdapterFactory(adapter);
builder.setPrettyPrinting();
sGson = builder.create();
}
return sGson;
}

@Override
public JsonElement serialize(PlayerCharacter src, Type typeOfSrc, JsonSerializationContext context) {
BaseClass characterClass = src.getCharClass();
characterClass.setCharacter(null);

Type equipListType = new TypeToken<ArrayList<Equipment>>() {
}.getType();
Type moneyMapType = new TypeToken<HashMap<Money, Integer>>() {
}.getType();

JsonObject rootObject = new JsonObject();
rootObject.add("mScores", context.serialize(src.getScores()));
rootObject.add("mCharClass", context.serialize(src.getCharClass(), BaseClass.class));
rootObject.add("mGender", context.serialize(src.getGender()));
rootObject.add("mMoney", context.serialize(src.getMoney(), moneyMapType));
rootObject.add("mAge", context.serialize(src.getAge()));
rootObject.add("mName", context.serialize(src.getName()));
System.out.println(getGson().toJsonTree(src.getInventory(), equipListType));
rootObject.add("mInventory", getGson().toJsonTree(src.getInventory(), equipListType));
rootObject.add("mCurrentWeapon", context.serialize(src.getCurrentWeapon()));
rootObject.add("mHelmet", context.serialize(src.getHelmet()));
rootObject.add("mBreastplate", context.serialize(src.getBreastplate()));
rootObject.add("mShield", context.serialize(src.getShield()));

JsonElement classJson = context.serialize(characterClass);
rootObject.add("mCharClass", classJson);

characterClass.setCharacter(src);
return rootObject;
}

@Override
public PlayerCharacter deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
final PlayerCharacter newCharacter = new PlayerCharacter();
JsonObject loadedData = json.getAsJsonObject();
for (Score score : Score.values()) {
int loadedScore = loadedData.getAsJsonObject("mScores").getAsJsonObject(score.toString()).get("mScore").getAsInt();
newCharacter.getScore(score).setScore(loadedScore);
}

Type equipListType = new TypeToken<ArrayList<Equipment>>() {
}.getType();
Type moneyMapType = new TypeToken<HashMap<Money, Integer>>() {
}.getType();

newCharacter.setAge((int) context.deserialize(loadedData.get("mAge"), Integer.class));
newCharacter.setBreastplate((Armor) context.deserialize(loadedData.get("mBreastplate"), Armor.class));
newCharacter.setCharClass((BaseClass) context.deserialize(loadedData.get("mCharClass"), BaseClass.class));
newCharacter.setCurrentWeapon((Weapon) context.deserialize(loadedData.get("mCurrentWeapon"), Weapon.class));
newCharacter.setGender((Gender) context.deserialize(loadedData.get("mGender"), Gender.class));
newCharacter.setHelmet((Armor) context.deserialize(loadedData.get("mHelmet"), Armor.class));
newCharacter.setMoney((HashMap<Money, Integer>) context.deserialize(loadedData.get("mMoney"), moneyMapType));
newCharacter.setName(loadedData.get("mName").getAsString());
newCharacter.setInventory((ArrayList<Equipment>) getGson().fromJson(loadedData.get("mInventory"), equipListType));
newCharacter.setShield((Armor) context.deserialize(loadedData.get("mShield"), Armor.class));

return newCharacter;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.io.OutputStreamWriter;

/**
* @deprecated
* Created by jusmith on 4/26/17.
*/

Expand Down
Loading