简体   繁体   中英

Reading XML Strings from Java

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. 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM