开发者

Reading XML Strings from Java

开发者 https://www.devze.com 2023-03-29 05:13 出处:网络
With something that I thought was so simple, I\'m surprised to be getting such a strange error... In my program, I have a layout with 5 buttons on it.When you press a button, it launches the phone\'s

With something that I thought was so simple, I'm surprised to be getting such a strange error...

In my program, I have a layout with 5 buttons on it. When you press a button, it launches the phone's dialer with the number pre-loaded into it. 开发者_StackOverflow中文版 I've had no problem with this before, but then I tried moving the phone numbers to strings in an XML file that I put in the /res/values folder called 'phone.xml'. Here's a portion of my code for the Java file:

    public void launchDialer(String number){
        String numberToDial = "tel:"+number;
        startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(numberToDial)));
    }

    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.police_button1:
            launchDialer(Integer.toString(R.string.police1_phone));
            break;
        case R.id.police_button2:
            launchDialer("" + R.string.police2_phone);
            break;
        case R.id.police_button3:
            launchDialer("" + R.string.police3_phone);
            break;
        case R.id.police_button4:
            launchDialer("" + R.string.police4_phone);
            break;
        case R.id.police_button5:
            launchDialer("" + R.string.police5_phone);
            break;
        }
    }

And here's my phone.xml file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="police1_phone">"555-555-5555"</string>
    <string name="police2_phone">1-800-555-5555</string>
    <string name="police3_phone">555-555-5555</string>
    <string name="police4_phone">555-555-5555</string>
    <string name="police5_phone">555-555-5555</string>
</resources>

As you can see in the Java file, I tried something different for police1_phone and police2_phone, but neither of them worked. You can also see I tried putting quotes around 1 of the phone numbers in the xml file, but it still didn't work. My output has always been some random 7 digit number that wasn't even close to the phone number I wanted it to print. This Java code worked:

launchDialer("555-555-5555");

But, I need it to read from an XML file. Any ideas?


Maybe I don't understand something, but getString(R.string.police1_phone) must work.


If you want they are ready to use parsers like

  • SAXXParser (which i allways use) http://www.javaworld.com/javaworld/jw-05-2002/jw-0517-sax.html

  • JAVAXML: http://www.mkyong.com/tutorials/java-xml-tutorials/

  • you could write your own little parser if you want.


If you want to use R.string.xxx, then you need to put your string values in a file named strings.xml in your /res/values/ folder.

0

精彩评论

暂无评论...
验证码 换一张
取 消