I'm trying to make a simple dictionary which searches the words from txt file. I created the txt file and stored some English words. I want to write the word to EditText. Then, this word will be found and displayed on the TextView. Here is my code. It displays the whole txt file. How can i find the specific word ?
public class MainActivity extends Activity {
//creating variables
TextView myText;
EditText myEdit;
Button myButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializing the TextView EditText and Button
myText=(TextView) findViewById(R.id.idTextView);
myEdit=(EditText) findViewById(R.id.idEditText);
myButton=(Button) findViewById(R.id.idButton);
myButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String saveData=myEdit.getText().toString();
try{
myText.setText(readfile());
}catch(IOException e){
e.printStackTrace();
}
}
});
}
private String readfile()throws IOException {
String str="";
InputStream is = getResources().openRawResource(R.raw.translate);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line=reader.readLine();
while (line!=null)
{
str = str + line + "\n";
line = reader.readLine();
}
reader.close();
return str;
}
}
It all depends on how your readFile() is implemented. I suggest that you modify it to accept a String parameter. That way, it will search for that word in the file and return its meaning as another String that you can assign to TextView via setText()
myText.setText(readFile(saveData)));
is how the suggested implementation would look like.
Inside this method, when you read the file line-by-line, check if the String you just read from the file contains the required word. This can be done using the contains() method.
Think you're after a simple contains() check:
String fileText = readFile();
Boolean textFound = fileText.contains(saveData);
If that boolean is true, then you would display the value of saveData in the box. You could put this operation in a loop and search for multiple words as well if you wanted.
Related
I am reading a text line with FileInputStream at one of its index in ArrayList which contains a Line Break and using it to display in TextView. But problem is that \n is being displayed instead of making a line break.
I also checked Whether an Arraylist can contain "\n" and it worked exactly how I wanted
but only when am declaring it within my class like -data.add(1,"xyz\nxyz"). but the same is not working when I read line from text file.
public class MainActivity extends AppCompatActivity {
public static ArrayList<String> data;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data=new ArrayList<>();
tv1=findViewById(R.id.text1);
tv2=findViewById(R.id.text2);
Reading text file
File fi = new File(Environment.getExternalStorageDirectory(), "Path /test.txt");
if (fi.exists()){
try {
FileInputStream inputStream = new FileInputStream(fi.getPath());
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
while (line != null) {
data.add(0,line);
line = bufferedReader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Displaying elements of ArrayList in TextView
tv1.setText(data.get(0)); // TextView display "\n" instead of line break.
data.add(1,"\n\nhello here is a\nline break"); // This works fine as expected, text is displayed in new line
tv2.setText(data.get(1));
Basically the code I have below does currently read from a text file, but what I want it to do is store a value so that I can use it later for a another function. So from the text file I would like to store the height (175) and weight (80) value. How would that be done?
Text File:
Name: ..........
Height: 175
Weight 80
MainActivity:
package com.example.readfromfiletest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
Button b_read;
TextView tv_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_read = (Button) findViewById(R.id.b_read);
tv_text = (TextView) findViewById(R.id.tv_text);
b_read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = "";
try {
InputStream is = getAssets().open("test.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException ex) {
ex.printStackTrace();
}
tv_text.setText(text);
}
});
}
}
Judging from your comments, it sounds like you're asking how to properly read in the values into different variables rather than reading them into one String. I think the first thing you should do to achieve this is read the file in line by line with a BufferedReader. Then for each line you read in you can determine which variable to assign the value to. For instance, you could do this:
Button b_read;
TextView tv_text;
String name = "";
int height = 0;
int weight = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_read = (Button) findViewById(R.id.b_read);
tv_text = (TextView) findViewById(R.id.tv_text);
b_read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = "";
try {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(getAssets().open("test.txt")));
String line;
while((line = bufferedReader.readLine()) != null){
text = text.concat(line + "\n");
String[] lineVals = line.split(":");
if(lineVals[0].equalsIgnoreCase("name")){
name = lineVals[1].trim();
} else if(lineVals[0].equalsIgnoreCase("height")){
height = Integer.parseInt(lineVals[1].trim());
} else if(lineVals[0].equalsIgnoreCase("weight")){
weight = Integer.parseInt(lineVals[1].trim());
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
tv_text.setText(text);
}
});
}
The BufferedReader reads in one line at a time. For example just, "Height: 175"
The line is then split on the ":", returning a String[] with two values. Continuing with our Height example, the array looks something like this: ["Height", " 175"]
The if statements (could also be case statements) then determine whether we're dealing with the name, height or weight variable.
The value is then assigned to its appropriate variable. The trim() method is called during this assignment to remove the space after the colon. You could also circumvent this by performing the split() method on ": ".
You could also stick with your current method and do some String manipulation involving splitting, Regex, or some other method, but I am of the opinion that my proposed solution will be a bit easier to read/work with in the future.
I have been trying to build a simple calculator in android studio. Everything is fine but i have a problem, when i run the calculator and i press the dot button, it shows in the textview "." instead "0."
Also, i need to check the existence of two decimal points in a single numeric value.
here is an image:
it shows "."
and i want:
how can i change this??, here is my code:
private int cont=0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display=(TextView)findViewById(R.id.display);
text="";
}
public void numero1(View view){ /*when i press a number, this method executes*/
Button button = (Button) view;
text += button.getText().toString();
display.setText(text);
}
public void dot(View view){ /*This is not finished*/
display.setText{"0."}
}
I was thinking in creating another method for the dot button, but the content of the text value disappears when i press another button, how to fix this?
try this
public void numero1(View view){ /*when i press a number, this method executes*/
Button button = (Button) view;
text += button.getText().toString();
if(text.substring(0,1).equals("."))
text="0"+text;
display.setText(text);
}
try this way
public void dot(View view){ /*This is not finished*/
String str=display.getText().toString().trim();
if(str.length()>0){
display.seText(str+".")
}else{
display.setText("0.")
}
}
Use a string builder and append all the text entered to already existing string. Before display, just use the toString() method on the string builder.
Create a class that represents your character sequence to be displayed and process the incoming characters.
For example:
class Display {
boolean hasPoint = false;
StringBuilder mSequence;
public Display() {
mSequence = new StringBuilder();
mSequence.append('0');
}
public void add(char pChar) {
// avoiding multiple floating points
if(pChar == '.'){
if(hasPoint){
return;
}else {
hasPoint = true;
}
}
// avoiding multiple starting zeros
if(!hasPoint && mSequence.charAt(0) == '0' && pChar == '0'){
return;
}
// adding character to the sequence
mSequence.append(pChar);
}
// Return the sequence as a string
// Integer numbers get trailing dot
public String toShow(){
if(!hasPoint)
return mSequence.toString() + ".";
else
return mSequence.toString();
}
}
Set such a click listener to your numeric and "point/dot" buttons:
class ClickListener implements View.OnClickListener{
#Override
public void onClick(View view) {
// getting char by name of a button
char aChar = ((Button) view).getText().charAt(0);
// trying to add the char
mDisplay.add(aChar);
// displaying the result in the TextView
tvDisplay.setText(mDisplay.toShow());
}
}
Initialize the display in onCreate() of your activity:
mDisplay = new Display();
tvDisplay.setText(mDisplay.toShow());
I have a problem with my code, I need to read EditText from a user and than put that text into another layout and do some calculations. My problem is that I don't understand how to read/write data in Android. Below is a snippet of the read/write code.
Thanks for the help!
EDIT: Should be noted that all of this is inside of my MainActivity class
public EditText editName;
public EditText editAMT;
public Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editName = (EditText) findViewById(R.id.editName);
editAMT = (EditText) findViewById(R.id.editAMT);
save = (Button) findViewById(R.id.save);
File fName = new File(name);
File fAMT = new File(AMT);
//WRITING TO THE FILE
try{
FileOutputStream test = openFileOutput(name, Context.MODE_PRIVATE);
FileOutputStream test2 = openFileOutput(AMT, Context.MODE_PRIVATE);
test.write(editName.getText().toString().getBytes());
test2.write(editAMT.getText().toString().getBytes());
test.close();
test2.close();
} catch(Exception e){
e.printStackTrace();
}
//READING FROM THE FILE
try{
BufferedReader inputReader = new BufferedReader(new InputStreamReader(openFileInput(name)));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null){
stringBuffer.append(inputString + "\n");
}
} catch (IOException e){
e.printStackTrace();
}
}
EDIT: Here is my action plan.
1) Get information from EditText called (eAMT). 2) Get information from EditText called (eName). 3) Put the information of eAMT into a file called eName.txt 4) In another activity, search for the file called eName. 5) Once search is completed, pull the contents of that file and display onto another activity (Main activity).
Instead of writing to a file, use Android's SharedPreferences:
SharedPreferences preferences = getSharedPreferences("com.example.myapp", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("UniqueEditNameKey", editName.getText().toString);
From another activity, you can do the following to retrieve the value:
SharedPreferences preferences = getSharedPreferences("com.example.myapp", MODE_PRIVATE);
String name = preferences.getString("UniqueEditNameKey", ""); // second argument is default value if key does not exist
The title is a little confusing so let me explain further. An application I am trying to make has multiple buttons opening a new activity that look the same, but the text is different depending on the button clicked (Like a dictionary). So instead of recreating the activity 50+ times, I made a new method for onClick() in the first activity with a new Intent, and added a getIntent() to the second activity.
//first activity method
public final static String TRANSFER_SYMBOL = "com.engineering.dictionary.MESSAGE";
public void openView(View view)
{
Intent open = new Intent(this,displayCharHB.class);
Button setBtn = (Button) findViewById(view.getId());
String grabText = setBtn.getText().toString();
String thisChar = "sym_hira_" + grabText;
open.putExtra(TRANSFER_SYMBOL,thisChar);
startActivity(open);
}
//second Activity method
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent grabChar = getIntent();
String thisChar = grabChar.getStringExtra(hira_basic.TRANSFER_SYMBOL);
//String strValue = "R.string." + thisChar;
TextView displaySym = (TextView) findViewById(R.id.charDisplay);
displaySym.setText(thisChar);
}
sym_hira_ + whatever is stored in grabText is the name of a String in strings.xml (For example, grabText = "ro", sym_hira_ro is a String name). Is it possible to get it to reference that string name with setText() and not actually set the text to "sym_hira_..."?
Is it possible to get it to reference that string name with setText()
Use getIdentifier to get value from strings.xml using name:
int resId = getResources().getIdentifier(thisChar, "string",getPackageName());
displaySym.setText(getResources().getString(resId));
you can using BeanShell execute the "R.string.xxxx" command to get the string resource id.
this is my code example;
String str = "";
Interpreter i = new Interpreter();
i.set("context", MainActivity.this);
Object res = i.eval("com.example.testucmbilebase.R.string.hello_world");
if(res != null) {
Integer resI = (Integer)res;
str = MainActivity.this.getResources().getString(resI);
}