开发者

Android Read Text File Into Dialog

Hi so i have an app that downloads a text file from my server and what i want to then do is show a dialog that only has a message that is written in dynamically by the text file so for example say i have a text file with the following

This is my text file that contains some message and was downloaded from my server

Now I want to create a simple dialog like this

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(<text from file goes here>)
       .setCancelable(true)
       .setPositiveButton("Okay", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                dialog.cancel
           }
       }).show();

Any help on how i can read开发者_如何学C the text file and then write it into my dialog as a message would be greatly appreciated thanks for any help or suggestions


Ended up figuring out my problem and did it like this

Dialog

AlertDialog.Builder builder = new AlertDialog.Builder(Activity.this);
try {
    builder.setMessage(readFile(context.getFilesDir().getAbsolutePath() + "/filename"))
           .setCancelable(true)
           .setPositiveButton("Okay", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           }).show();
} catch (IOException e) {
    Toast.makeText(Activity.this, "Error", Toast.LENGTH_SHORT).show();
    e.printStackTrace();
}

Method

private static String readFile(String path) throws IOException {
      FileInputStream stream = new FileInputStream(new File(path));
      try {
        FileChannel fc = stream.getChannel();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        return Charset.defaultCharset().decode(bb).toString();
      }
      finally {
        stream.close();
      }
    }

Thanks for the help as always

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜