1

I'm creating an app that contains a "Tip of the Day" feature. This is essentially a pop-up, activated by a button. It currently has filler text right now, but I am trying to create a way in which a text file (stored in src/main/assets) is read, and an individual line is displayed in the pop-up. How can I do this? These lines in the text file are individualized by the return key. I will find a way to display unique tips each time the button is clicked, but I will get to that part later.

Here is the code for the pop-up itself:

public class homeFragmentDialog extends Activity {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
    builder1.setMessage("Filler text.");
    builder1.setCancelable(true);

    builder1.setPositiveButton(
            "Close",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });

    AlertDialog alert11 = builder1.create();
    alert11.show();

}
}

And just in case, here is the fragment file which holds the button that activates the previous activity:

public class homeFragment extends Fragment {

View rootView;

private Button button0;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_home, container, false);

    button0 = (Button) rootView.findViewById(R.id.buttonDialog);
    button0.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), homeFragmentDialog.class);
            startActivity(intent);
        }


    });

    return rootView;

}

}

2 Answers2

0

This should be enough for you to fetch the information from the text file in the assets folder as String.

If you have problems with this short code snippet this one should be way more extensive.

Once you got the text as a String object you should be able to add it inside your setMessage function to display it.

OneShotDev
  • 21
  • 4
  • I'm confident about this method. From your first link, how can I use .setMessage to display what is stored in the String str_data? I tried declaring in the strings.xml "homeFragmentDialog" and then changing .setMessage to "builder1.setMessage(R.string.str_data);" but that just made the dialog show "homeFragmentDialog" (I can see why it does that now). –  Mar 18 '16 at 00:01
  • Revan TB: Even though Alan Wink's response essentially works for me, I would still like to know how to use .setMessage() to display the str_data variable from yours if you have time to explain. Thanks a lot. –  Mar 18 '16 at 00:24
  • To display the content of str_data in your dialog you just have to put it into your setMessage method as a parameter. The whole line of code should look like this: **builder1.setMessage(str_data)** – OneShotDev Mar 18 '16 at 05:04
0

You can use getAssets() if you access to a Context:

try {
    InputStream inputStream = getAssets().open("textfile.txt");
    builder1.setMessage(convertStreamToString(inputStream));
} catch (IOException e){
    // Log exception
}

Where convertStreamToString() came from Pavel Repin's answer:

static String convertStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

Or you can read the ammount of bytes you want(in your case one line).

EDIT:

Instead of convertStreamToString(), you can use this method to get a single line:

static String getLineFromStream(java.io.InputStream is, int linePos){
    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    String line = null;
    try {
        for (int i = 0; i <= linePos; i++) {
            line = br.readLine();
        }
    } catch (IOException e){
        // Handle exception here (or you can throw)
    }

    return line;
}
Community
  • 1
  • 1
Alan Wink
  • 113
  • 10
  • Looks solid. I am getting the "Cannot resolve method convertStreamToString" error though. It must be the easiest error to fix that my lack of experience is causing. edit: Got this to work. It displays the entire text file in the dialog pop-up which is a big step. Thanks a lot. –  Mar 18 '16 at 00:12
  • I added a method to read only one line, please check if this works for you. – Alan Wink Mar 18 '16 at 00:34
  • This is an elementary error, but when I write "builder1.setMessage(getLineFromStream(inputStream);" it says (InputStream, int) cannot be applied to it. That makes sense, since getLineFromStream uses (InputStream, int)... but how do I make that first line work? I tried "builder1.setMessage(getLineFromStream(inputStream, linePos);" but that fails. –  Mar 18 '16 at 00:56
  • Sorry, I did't explained the method. The linePos is the line of the file you want to read, so if you want to test, you can put a line number (for example: 0 will get the first line, 1 the second and so on. Just make sure the line exists, because if not it will throw an IOException. – Alan Wink Mar 18 '16 at 01:31
  • So I erased "int linePos" and change the interior code to "for (int i = 0; i <= 13; i++)" since there are 14 total lines in my text file. Maybe I'm hindering myself by doing that, unless it's what you were recommending I do. Regardless, this solved the bulk of my problems with getting this feature implemented. I'm very grateful, thank you so much. –  Mar 18 '16 at 01:37
  • Since you probably will track what line you must show on the next startup (or randomly get one), I recommend you use the method to get a line like this: `int line = getTodayLine(); // It's up to you how you will get it.` and later call: ...`getLineFromStream(inputStream, line)`... So you get a code less coupled. – Alan Wink Mar 18 '16 at 01:55