Search code examples
javaandroidsubstringlastindexof

confused with substring in android


I got confused with substring in android. in my database i have file pdf like this DOGMATIKA-3.pdf and i want to select the "pdf". ho to do it in android? i just want to select 3 last letters , anyone please help me, thank you. i already try with this code but got force close.

package mobile.download;

public class DownloadText extends Activity{
    public Koneksi linkurl;
    public Kondownload linkurl2;
    String url;
    String SERVER_URL;
    String SERVER_URL2;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.linkdownload);

        TextView mTextLink = (TextView) findViewById(R.id.LinkDownload);
        Bundle bundle = this.getIntent().getExtras();

        String param1 = bundle.getString("keyIdc");
        String param2 = bundle.getString("keyReference");
        if(param2.substring(-3, 0).equals("pdf"))
        {
            linkurl = new Koneksi(this);
            SERVER_URL = linkurl.getUrl();
            SERVER_URL += "/moodledata/"+param1+"/"+param2;
            mTextLink.setText(SERVER_URL);
            Pattern pattern = Pattern.compile(SERVER_URL);

           Linkify.addLinks(mTextLink, pattern, "");
        }
        else
        {
            linkurl2 = new Kondownload(param2);
            SERVER_URL2 = linkurl2.getUrl();

            mTextLink.setText(SERVER_URL2);
            Pattern pattern = Pattern.compile(SERVER_URL2);

           Linkify.addLinks(mTextLink, pattern, "");
        }

    }
}

Solution

  • last 3 letters are length() - 3 to length() (the second parameter is implicitely length(), so it is not necessary)

    param2.substring(params2.length() - 3)
    

    however, you could use endsWith which is clearer :

    param2.endsWith("pdf")
    

    which does exactly that.