Reading from a text file in android - java

I'm trying to read a random line from a file. My code doesn't have error, just comes up with a force close as soon as it runs in the emulator and I can't work out why!
public class filereader extends Activity {
TextView t = (TextView)findViewById(R.id.text);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
Scanner s = new Scanner(getResources().openRawResource(R.raw.lev1)); {
try {
while (s.hasNext()) {
String word = s.next();
t.setText(word);
}
}
finally {
s.close();
}
}
}

TextView t = (TextView)findViewById(R.id.text);
you can not run findViewById until the setContentView has been called:
TextView t = null; #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView)findViewById(R.id.text);
}
please be sure that you declare text inside the main.xml

do this
BufferedReader myReader = null;
try
{
fIn = openFileInput("customer_number.txt");
myReader = new BufferedReader(new InputStreamReader(fIn));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String aDataRow = "";
//String aBuffer = "";
try
{
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
// TO display Whole Data of File
Toast.makeText(getBaseContext(),aBuffer,Toast.LENGTH_SHORT).show();
}
// To display Last Entered Number
Toast.makeText(getBaseContext(),last_number,Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

public void readfromfile(){
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
String s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
It will read the text file named "mytext.txt" string by string and store it by appending it to string variable s. So the variable "s" contains final string taken from file.

Related

JSON error loading

I am trying to save a simple name and load it – just to make everything clear to myself – there is no error, but when it loads it loads something different. It has something to do with Android itself.
Here is the class where I save and load (I don't use any libraries):
public class Serializer
{
private Context context;
private String fn;
public Serializer(Context con , String filename){
this.context = con;
this.fn = filename;
}
public void save(ArrayList<String> usernames) throws JSONException, IOException {
JSONArray JsonArray = new JSONArray();
JSONObject obj = new JSONObject();
for(String s : usernames){
obj.put("username" , s);
JsonArray.put(obj);
}
Writer writer = null;
OutputStream out = context.openFileOutput(fn , 0);
writer = new OutputStreamWriter(out);
writer.write(JsonArray.toString());
if(writer != null){
writer.close();
}
}
public ArrayList<String> load () throws IOException, JSONException {
ArrayList<String > strings = new ArrayList<>();
InputStream in = context.openFileInput(fn);
InputStreamReader reader = new InputStreamReader(in);
BufferedReader Reader = new BufferedReader(reader);
StringBuilder builder = new StringBuilder();
String Line;
while((Line = Reader.readLine() ) != null){
builder.append(Line);
}
JSONArray array = (JSONArray)new JSONTokener(builder.toString()).nextValue();
for(int i = 0 ; i < array.length() ; i++){
String jack = (String) array.getJSONObject(i).get("username");
strings.add(jack);
}
if(reader!=null){
reader.close();
}
return strings;
}
}
Here is my main activity whose layout is a simple layout with one TextEdit:
public class MainActivity extends AppCompatActivity {
Serializer serializer;
ArrayList<String> usernames;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serializer = new Serializer(this,"Jacop");
TextView txtView = findViewById(R.id.txt);
usernames = new ArrayList<>();
usernames.add(txtView.toString());
try {
ArrayList<String> username = serializer.load();
txtView.setText(username.get(0));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onResume(){
super.onResume();
try {
serializer.save(usernames);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The output (e.g what the text view shows after I close and reopen the app).
android.support.v7.widget.AppCompatEditText{73d0e9d VFED..CL. ......I. 0,0-0,0 #7f07007b app:id/txt}
You are adding an Object as String .
usernames.add(txtView.toString());
Change it to
usernames.add(txtView.getText().toString());
toString() is a method of Object class so each class have it . and android.support.v7.widget.AppCompatEditText{73d0e9d VFED..CL. ......I. 0,0-0,0 #7f07007b app:id/txt} is the string representation of the TextView object .

After I load a file with Hebrew text from raw folder it is not displayed correctly, how did I fix it?

This is my code
public class Blogs extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.seriously);
String line = "";
StringBuilder finalString = new StringBuilder();
InputStream iStream = getResources().openRawResource(R.raw.minzelostam);
BufferedReader bReader = new BufferedReader (new InputStreamReader(iStream));
try {
while ((line = bReader.readLine())!=null){
finalString.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView tv = (TextView)findViewById(R.id.tvLongText);
tv.setText(finalString);
}
}
And this is the result on the screen
The problem is writing in Hebrew, I just don't know how to solve it.
I had a similar task to resolve a few years ago. I downloaded a hebrew font and added to the assets of the project. Then loaded that font file and set the returned typeface to the textview I was setting the hebrew text on. Try a similar approach. Here's a font that might help you
package com.dolev.jinjer;
public class Blogs extends Activity{
Typeface tf;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.seriously);
tf = Typeface.createFromAsset(getAssets(), "DroidSansHebrew.ttf‬");
String line = "";
StringBuilder finalString = new StringBuilder();
InputStream iStream = getResources().openRawResource(R.raw.minzelostam);
BufferedReader bReader = new BufferedReader (new InputStreamReader(iStream));
try {
while ((line = bReader.readLine())!=null){
finalString.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView tv = (TextView)findViewById(R.id.tvLongText);
tv.setTypeface(tf);
tv.setText(finalString);
}
}
still dosent work :(

OnPostExecute not getting string

The contents of the string descript is showing up in logcat with no problems but won't display on the textview in the dialog located in OnPostExecute. It's a nullpointer exception. I'm not sure why since the episode string works just fine. Can anyone tell me why?
class getDescContent extends AsyncTask<Void, Void, Void> {
FileInputStream input = null;
String episode = null;
String descript = null;
#Override
protected Void doInBackground(Void... arg0) {
try {
input = new FileInputStream(descFile);
BufferedReader br = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = br.readLine()) != null) {
if (line.length() < 50) {
episode = line;
continue;
}
descript = line;
Log.i("", descript);
}
input.close();
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.info_dialog);
dialog.setTitle(episode);
TextView descrip = (TextView) findViewById(R.id.dialog_text);
descrip.setText(descript);
dialog.show();
}
}
You should use
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.info_dialog);
dialog.setTitle(episode);
TextView descrip = (TextView) dialog.findViewById(R.id.dialog_text); //change in this line
descrip.setText(descript);
dialog.show();
Since the textview is not in the layout of the activity but in the layout of the dialog.
In your code, descrip is null, because it cannot be found.

An error connecting to Android Spinner

I am working on an Android app where I have a Spinner, and on the base of which item I choose, the app will read in text file number 1 or number 2, etc... I have written a code, but when I run it on my device, it says that "The application has stopped unexpectedly".
Here is my code:
public class MainActivity extends Activity implements OnClickListener, OnItemSelectedListener {
Spinner spinner;
String textSource = "";
TextView textMsg;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textMsg = (TextView) findViewById(R.id.textmsg);
spinner=(Spinner) findViewById(R.id.spinner1);
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
URL textUrl;
String stringText = "";
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(textUrl.openStream(), "ISO-8859-1"));
//ISO-8859-1
String StringBuffer;
//String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
//textMsg.setText(string123);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
long arg3) {
// TODO Auto-generated method stub
String Text = parent.getSelectedItem().toString();
if(Text.equals("list 1")) {
textSource = "path/to/textfile 1";
}
else if(Text.equals("list 2")){
textSource = "path/to/textfile 2";
}
else {
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
How should I solve this problem?
Thanks for helping
I would suggest you to use
String Text = spinner.getSelectedItem().toString();
instead of
String Text = parent.getSelectedItem().toString();
So that it becomes :
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
long arg3) {
String Text = spinner.getSelectedItem().toString();
if(Text.equals("list 1")) {
textSource = "path/to/textfile 1";
}
else if(Text.equals("list 2")){
textSource = "path/to/textfile 2";
}
else {
}
// then put your URL code here as follows
URL textUrl;
String stringText = "";
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(textUrl.openStream(), "ISO-8859-1"));
//ISO-8859-1
String StringBuffer;
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
//textMsg.setText(string123);
} catch (MalformedURLException e) {
e.printStackTrace();
textMsg.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
}
}
Since you are calling textUrl = new URL(textSource); inside oncreate() method textSource will be always " ". Better create a method and pass the new textSource value based on onItemSelected .
Sample for Your reference: By Default Link1 will be passed
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
long arg3) {
String Text = parent.getSelectedItem().toString();
if (Text.equals("list 1")) {
Method("path/to/textfile 1");
} else if (Text.equals("list 2")) {
Method("path/to/textfile 2");
} else {
}
// TODO Auto-generated method stub
}
Method :
public void Method(String textSource) {
URL textUrl;
String stringText = "";
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(textUrl.openStream(), "ISO-8859-1"));
// ISO-8859-1
String StringBuffer;
// String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
// textMsg.setText(string123);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
}
}

Convert Text File to String in java

i have a written a code to send a text file by converting it into string and sending it into a web service. Please can someone tell me other available methods for sending the string as stream to Web Service.
public class MainActivity extends Activity {
Button b1;
String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
File upfile=new File("sdcard/text/testfile.txt");
try {
FileInputStream fin=new FileInputStream(upfile);
byte[] buffer= new byte[(int)upfile.length()];
new DataInputStream(fin).readFully(buffer);
fin.close();
s=new String(buffer,"UTF-8");
System.out.print(buffer);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, s, 20).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
try this.
public void mReadJsonData() {
try {
File f = new File("sdcard/text/testfile.txt");
FileInputStream is = new FileInputStream(f);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String text = new String(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Use this code to read the data from file and get it into string and do your process ahead according to your need--
File upfile=new File("sdcard/text/testfile.txt");
try {
final BufferedReader reader = new BufferedReader(new FileReader(upfile));
String encoded = "";
try {
String line;
while ((line = reader.readLine()) != null) {
encoded += line;
}
}
finally {
reader.close();
}
System.out.print(encoded);
}
catch (final Exception e) {
}

Categories

Resources