If so, is there a tutorial that I have missed somewhere that might help me get started with this? If not, can someone point me towards a place to get started setting up a database where I would preload the information instead of actua开发者_StackOverflow中文版lly having the user do it?
Here's a simple example of loading values from a values xml file into a string array, searching through the values, and selecting one for display.
values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string
name="hello">Hello World, Main!</string>
<string
name="app_name">Q6024120_Load_And_Search_Array</string>
<string-array
name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
</resources>
public class Main extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] planets = getResources().getStringArray(R.array.planets_array);
int foundIndex = -1;
for (int i = 0; i < planets.length; i++)
{
String planet = planets[i];
if (planet.equals("Mars"))
{
foundIndex = i;
break;
}
}
String foundPlanet = foundIndex >= 0 ? planets[foundIndex] : "nothing";
((TextView)findViewById(R.id.found_planet)).setText("found: " + foundPlanet);
}
}
If you'd rather load the data from an xml file in the assets folder, note that it's a bit involved. Take a look at android: how to load xml file from assets directory?.
If the values are just a simple list of strings, then xml structure probably isn't necessary. Here's a simple example of loading the values from a text file in the assets folder.
assets/planets.txt
Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
public class Main extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// String[] planets = getResources().getStringArray(R.array.planets_array);
String[] planets = readFromAssetsTxt();
int foundIndex = -1;
for (int i = 0; i < planets.length; i++)
{
String planet = planets[i];
if (planet.equals("Mars"))
{
foundIndex = i;
break;
}
}
String foundPlanet = foundIndex >= 0 ? planets[foundIndex] : "nothing";
((TextView) findViewById(R.id.found_planet)).setText("found: " + foundPlanet);
}
String[] readFromAssetsTxt()
{
try
{
AssetManager assetManager = getAssets();
List<String> planets = new ArrayList<String>();
BufferedReader in = new BufferedReader(new InputStreamReader(assetManager.open("planets.txt")));
String planet = null;
while ((planet = in.readLine()) != null)
{
planets.add(planet);
}
in.close();
String[] planetsArray = new String[planets.size()];
planets.toArray(planetsArray);
return planetsArray;
}
catch (IOException e)
{
e.printStackTrace();
}
return new String[] {};
}
}
精彩评论