Search code examples
javaandroidstringlistviewonclicklistener

How to open a file the same name as defined in the String?


I'm creating a lyric app and I need some help in coding the next processes I need. I created a ListView and added some Strings on it.

public class MainActivity extends AppCompatActivity {

String titles[] = new String [] {"Amazing Grace", "How Great Thou Art", 
"King of All Kings", "What A Beautiful Name"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ListView listView =(ListView) findViewById(R.id.titlelist);
    ArrayAdapter<String> adapter=new ArrayAdapter<String> 
    (this,android.R.layout.simple_list_item_1,titles);
    listView.setAdapter(adapter);
 }
}

Now the next step is to create an OnItemClickListener and let's say if "Amazing Grace" was selected from the list, it will look for a file the same name as it is defined in the String. For example : "Amazing Grace.xml" //even with the space included

so the logic will be like : open filelocation/"title that was selected".xml

I can't use "case" since I will be creating lots of song titles and add more as I update the app. Thanks for reading, I'd really appreciate any help with this ;)


Solution

  • To open file:

    int selected = 0; // set selected to index of what is selected
    File file = new File(Environment.getExternalStorageDirectory(), //folder location where you store the files
    titles[selected]+".xml"); //in case of xml files. If other types, you'll need to add case for diff types
    Uri path = Uri.fromFile(file);
    Intent fileOpenintent = new Intent(Intent.ACTION_VIEW);
    fileOpenintent .setDataAndType(path, "application/xml"); //for xml MIME types are text/xml and application/xml
    try {
        startActivity(fileOpenintent);
    }
    catch (ActivityNotFoundException e) {
    
    }
    

    Your biggest issue as you explained it was how to handle multiple file names. That's this part of code: titles[selected]+".xml"