Android - 使用网址填充字符串数组

时间:2016-07-12 12:33:44

标签: java android

我有一个网址" yyyyyyy.com/test.txt" ;,这是一个文本文件。 它包含.mp3音频的网址。

yyyyyyy.de/1.mp3
yyyyyyy.de/2.mp3
yyyyyyy.de/3.mp3 //exactly like that

我的目的是阅读此文本文件的每一行并将其存储在类似

的数组中
urls[0]=yyyyyyy.de/1.mp3
urls[1]=yyyyyyy.de/2.mp3 ...

此。

String[] urls;
int i=0;

Random rand;
int min=0;
int max=5; // I have 6 Urls in the text file
int randomNum;

@Override

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

  rand = new Random();

    randomNum = rand.nextInt((max - min) + 1) + min; //generates integer between 0-5
    try {
        // Create a URL for the desired page
        URL url = new URL("yyyyy.de/test.txt"); //My text file location

        // Read all the text returned by the server
        BufferedReader in = new BufferedReader(new     InputStreamReader(url.openStream()));
        String str;
        while ((str = in.readLine()) != null) {
           urls[i]=str;
           i++;
        }
        in.close();
       } catch (MalformedURLException e) {
      } catch (IOException e) {
     }


    boolean isPLAYING = false;

    if (!isPLAYING) {
        isPLAYING = true;
        MediaPlayer mp = new MediaPlayer();
        try {
            mp.setDataSource(urls[randomNum]);
            mp.prepare();
            mp.start();
        } catch (IOException e) {

        }
    } else {
        isPLAYING = false;

    }

}

我已经在Manifest.xml中添加了android:permission。 我不知道问题在哪里......应用程序关闭并告诉我 那条线" mp.setDataSource(urls[randomNum]);"是错的

LogCat:http://textuploader.com/5iw5b 在此先感谢!!

1 个答案:

答案 0 :(得分:0)

您的数组是NULL

将此代码放在super.onCreate

之后

urls=new String[max]

更新3:

试试这个:

ArrayList<String> urls=new ArrayList<String>();

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

    try {
        // Create a URL for the desired page
        URL url = new URL("yyyyy.de/test.txt"); //My text file location

        // Read all the text returned by the server
        BufferedReader in = new BufferedReader(new     InputStreamReader(url.openStream()));
        String str;
        while ((str = in.readLine()) != null) {
            urls.add(str);
        }
        in.close();
       } catch (MalformedURLException e) {
      } catch (IOException e) {
     }

Log.i("test","url count="+urls.size());


    boolean isPLAYING = false;

    if (!isPLAYING) {
        isPLAYING = true;
        MediaPlayer mp = new MediaPlayer();
        try {
            int randomPos = new Random().nextInt(urls.size());
            mp.setDataSource(urls.get(randomPos));
            mp.prepare();
            mp.start();
        } catch (IOException e) {

        }
    } else {
        isPLAYING = false;

    }

}