Я пишу приложение, которое случайным образом генерирует базовые детали NPC и другие вещи для RPG, это действие является страницей настроек для изменения количества, имен и вероятностей различных рас персонажей для целей случайной генерации этих персонажей.
Мой макет будет иметь ListView, каждый элемент имеет TextView, отображающий название расы, и EditText со значением с плавающей запятой для ввода вероятности появления расы при генерации нового персонажа. У меня проблемы с созданием этого макета, несмотря на его (предполагаемую?) Относительную простоту, так как я довольно новичок в платформе Android, а также в Java в целом.
- ИСПРАВЛЕНО -
При запуске действия я получаю исключение java.lang.ClassCastException: Integer. Отладчик указывает мне на строки в предварительно скомпилированных ресурсных банках, и я не уверен, что именно означает исключение classCastException с переменной e, куда это будет передаваться, если я сам не написал обработчик исключений?
- ИСПРАВЛЕНО -
У меня есть новая ошибка, связанная с JSONArrays, вы можете видеть в моем коде, что я объявляю массивы null String [] и float [], а затем пытаюсь заполнить их внутри try / catch, используя методы, которые извлекают JSONArrays как строки из SharedPreferences и положить значения в указанных массивах. Их объявление null дает мне исключение NullPointer, когда я присваиваю ему значения в моем цикле for ниже, а объявление их в try / catch дает им область видимости только для оператора блока try / catch.
Я ценю ваше внимание к моим затруднениям и любую помощь, которую вы можете предложить.
Это мой код:
import org.json.JSONException;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class GeneratorSettingsNPCRaceProbsActivity extends RandomGeneratorActivity
{
/** Called when the activity is first created.
* @throws JSONException */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_npc_race_probs);
ListView settingsList = (ListView)findViewById(R.id.listView_menu);
//Sets up a list of races with their corresponding probabilities in a text field. In the future,
//one will be able to edit a text field an commit changes to set the probabilities for each race.
//Perhaps I will implement a way to add custom races to the list.
//Finds current profile
SharedPreferences appSettings = getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE);
String currentProfile = appSettings.getString("CurrentProfile", DEFAULT_PROFILE);
//Gets races and probabilities from current SharedPreferences profile
SharedPreferences profileSettings = getSharedPreferences(currentProfile, MODE_PRIVATE);
String[] races = null;
float[] raceProbs = null;
try {
races = getProfileRaces(currentProfile);
raceProbs = getProfileRaceProbabilities(currentProfile);
} catch (JSONException e) {e.printStackTrace();}
//Puts the races and raceProbs into a RaceItem array
RaceItem[] raceItems = new RaceItem[races.length];
for (int i = 0; i < races.length; i++)
{
raceItems[i].raceName = races[i];
raceItems[i].raceProb = raceProbs[i];
}
Context context = this;
final LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
ArrayAdapter<RaceItem> adaptMenu = new ArrayAdapter<RaceItem>(context, android.R.layout.expandable_list_content)
{
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row;
if (convertView == null) {
row = inflater.inflate(R.layout.settings_npc_race_probs_item, null);
}
else {
row = convertView;
}
TextView tv1 = (TextView) row.findViewById(android.R.id.text1);
tv1.setText(getItem(position).raceName);
EditText et1 = (EditText) row.findViewById(android.R.id.text2);
et1.setText(String.valueOf(getItem(position).raceProb));
return row;
}
};
settingsList.setAdapter(adaptMenu);
}
}