Skip to content Skip to sidebar Skip to footer

Read Txt File In App Widget

I need read txt file in app Widget. I create txt in external set activity with name 'NASTAVENI': @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); set

Solution 1:

I am not sure if you want just a widget that reads from a txt or you want also "an activity". For the reading the txt file, I use to create a class that reads the file and give me back what I need, in a function like this:

  ShowLine(){
    try {
                InputStream is = mContext.getAssets().open(monthFile);
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
                // Skips lines
                Log.w("day", String.valueOf(monthFile));
                for (int i = 0; i< DayMonth-1; i++) {
                    reader.readLine();
                }
                Line = reader.readLine(); // read the line of the day

                Name= Line.substring(Line.indexOf("*") + 1,Line.indexOf("-"));// I read between + and (my data is like: DAY * NAME -)
                dia= ""+DayMonth+" de "+ monthNames[Month]+"" ;
                Log.w("Name", String.valueOf(Name)); //to check that it works

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

For the widget , you need to create a class that is a Widget with :

publicclassWidgetextendsAppWidgetProvider {
Stringdia="1 Feb.";
String Name= "Pavel";

    @OverridepublicvoidonUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){

        mContext = context;
        Resourcesres= mContext.getResources();

        ComponentNamethisWidget=newComponentName(context,Widget.class);
        int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);

        for(int widgetIds: allWidgetIds){


            RemoteViewsremoteViews=newRemoteViews(context.getPackageName(), R.layout.widget);
            //Log.w("Widget test", String.valueOf(number));try{
                ShowLine();
                Log.w("Line 1", String.valueOf(Name));

            }catch (Exception e) {
                Name= "error";
            }

I am not sure my code works perfect, probably you have to complete it a bit, because I didn't paste the whole functions. But If you have doubts , this is a good tutorial: vogella.com I hope it helps you :)

Post a Comment for "Read Txt File In App Widget"