如果是这样,是否有一个我错过的教程可能会帮助我开始这个?如果没有,有人可以指向我开始设置数据库的地方,我会预先加载信息而不是实际让用户这样做吗?
答案 0 :(得分:0)
这是一个简单的例子,它将值xml文件中的值加载到字符串数组中,搜索值,然后选择一个用于显示。
<强>值/ 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);
}
}
如果你宁愿从资源文件夹中的xml文件加载数据,请注意它有点涉及。看看android: how to load xml file from assets directory?。
如果值只是一个简单的字符串列表,则可能不需要xml结构。这是一个从资源文件夹中的文本文件加载值的简单示例。
<强>资产/ 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[] {};
}
}