Reading file in Android SDK -
i have 1 class called "global" , 2 other activities. in each activity want create instance of class global reading first line of text file called "textfile". reason, not work
here code of global class (in file global.java):
import android.app.activity; public class global extends activity { public string line; public global() { inputstream file = getresources().openrawresource(r.raw.textfile); bufferedreader input = new bufferedreader(new inputstreamreader(file)); try { line = input.readline(); } catch (ioexception e) { e.printstacktrace(); } } }
here codes antivity called "helloworld" (in file helloworld.java) has instance of class global , display of first line of "textfile"
public class helloworld extends activity{ global gb; textview mytv; protected void oncreate(bundle savedinstancestate) { // todo auto-generated method stub super.oncreate(savedinstancestate); setcontentview(r.layout.helloworld); gb=new global(); mytv = (textview) findviewbyid(r.id.textview1); mytv.settext("first line is: "+gb.line); }
}
there not need unnecessarily have global extending activity class.
what can pass context in global constructor.
the correct way be
helloworld.java
import android.app.activity; import android.os.bundle; import android.widget.textview; public class helloworld extends activity{ global gb; textview mytv; protected void oncreate(bundle savedinstancestate) { // todo auto-generated method stub super.oncreate(savedinstancestate); setcontentview(r.layout.helloworld); gb=new global(this); mytv = (textview) findviewbyid(r.id.textview1); mytv.settext("first line is: "+gb.getline()); } }
global.java
import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; public class global { private abcactivity abcactivity; public string line; public global(abcactivity abcactivity) { this.abcactivity = abcactivity; } public string getline() { inputstream file = abcactivity.getresources().openrawresource( r.raw.textfile); bufferedreader input = new bufferedreader(new inputstreamreader(file)); try { line = input.readline(); return line; } catch (ioexception e) { e.printstacktrace(); return "error reading file!"; } } }
Comments
Post a Comment