I have a problem with my app.
What I'm trying to do is to find rhymes to a word entered from the user into a text field.
I have a dictionary in assets folder called "words.txt".
My app is working almost correctly, but it finds only one word from my text file.
How can I find all words that rhyme with the word from the text field?
Any ideas?
Here is my code:
#Override
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_main);
editTextWord = (EditText)findViewById(R.id.editTextWord);
b_read = (Button)findViewById(R.id.buttonSearch);
tv_text = (TextView)findViewById(R.id.nameTxt);
b_clear = (Button)findViewById(R.id.buttonClear);
b_clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, MainActivity.class);
startActivity(i);
}
});
b_read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
InputStream is = getAssets().open("words.txt");
int size = is.available();
BufferedReader rd = new BufferedReader(new InputStreamReader(is,"UTF-8"));
String line;
String word = editTextWord.getText().toString();
if (word.isEmpty()){
Toast.makeText(getApplicationContext(), "Wpisz słowo", Toast.LENGTH_SHORT).show();
return;
}
while ((line = rd.readLine()) !=null ){
if (line.substring(line.length()-2).equals(word.substring(word.length()-2))){
tv_text.setText(line);
}
}
rd.close();
}catch (IOException ex){
ex.printStackTrace();
}
}
});
}
tv_text.setText overwrites anything that is already in the TextView. You need to use something like TextView.append(CharSequence)
Try:
tv_text.append(line + "\n");
Related
I am developing an android app and just need some help on selecting the correct text files and keeping a count of the number of clicks for buttons.
So basically I have two activity classes. The homepage of the app is stored in the MainActivity class and the other class is known as Content
In the MainActivity class there are three buttons:
Jokes,
Poems
and Funny Stories
Basically whichever option the user selects out of those three buttons, the content on the next page (Content class) will display the correct passage of text relating to the choice selected.
Currently my code works for jokes when the user selects jokes and the content it displays is randomly selected from the jokes.txt file.
MainActivity
public class MainActivity extends AppCompatActivity{
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button jokesButton = findViewById(R.id.button_jokes);
Button poemsButton = findViewById(R.id.button_poems);
Button funnyStoriesButton = findViewById(R.id.button_funny_stories);
jokesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openContentPage();
}
});
}
private void openContentPage(){
Intent intentContentPage = new Intent(MainActivity.this, Content.class);
startActivity(intentContentPage);
}
}
Content
public class Content extends AppCompatActivity{
Button backButton;
Button selectAnotherButton;
TextView contentText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
backButton = findViewById(R.id.button_back);
selectAnotherButton = findViewById(R.id.button_select_another);
contentText = findViewById(R.id.content_text);
contentText.setMovementMethod(new ScrollingMovementMethod());
setContent();
selectAnotherButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContent();
}
});
backButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View v){
backToMainActivity();
}
});
}
private void backToMainActivity(){
Intent intentMainActivity = new Intent(this, MainActivity.class);
startActivity(intentMainActivity);
}
private void setContent(){
String text = "";
String randomJoke = "";
try {
// file to inputstream
InputStream input = getAssets().open("files/jokes.txt");
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// byte buffer into a string
text = new String(buffer);
String[] jokes = text.split("###");
Random rand = new Random();
int randomIndex = rand.nextInt(jokes.length);
randomJoke = jokes[randomIndex];
}
catch (Exception e) {
System.out.println(e);
}
contentText.setText(randomJoke);
}
}
However this code needs to be manipulated so that it includes Poems and Funny Stories. Basically if the user selects Poems then it will grab the content from the poems.txt file, if they select Funny Stories then it will grab from the funnystories.txt file. Also if they select the Select Another button, it will randomly select a new entry from the correct text file. Like I said the code I have done works for jokes only, but I need to make it more dynamic so it would work for poems and funny stories too depending on which option the user selected from the homepage.
One final thing as well. I want a count of the number of times the user has clicked on either Jokes, Poems, Funny Stories from MainActivity and also add Select Another button to the count as well.
How can this be implemented?
UPDATE:
Trying to receive the intent I receive the following error from this code:
private void setContent(){
String text = "";
String randomText = "";
String keyPageValue = getIntent().getStringExtra("keyPage");
String fileName = "";
if(keyPageValue.equals("0")){
fileName.equals("files/jokes.txt");
}
else if (keyPageValue.equals("1")){
fileName.equals("files/poems.txt");
}
else if (keyPageValue.equals("2")){
fileName.equals("files/funnystories.txt");
}
try {
InputStream input = getAssets().open(fileName);
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// byte buffer into a string
text = new String(buffer);
String[] splitText = text.split("###");
Random rand = new Random();
int randomIndex = rand.nextInt(splitText.length);
randomText = splitText[randomIndex];
}
catch (Exception e) {
System.out.println(e);
}
contentText.setText(randomText);
}
Stack Trace:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mima.chilltime, PID: 18747
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mima.chilltime/com.mima.chilltime.Content}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3150)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3260)
...
In order to do that you can pass an int value which denotes the type of button clicked by the user:-
jokesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openContentPage(0);
}
});
poemsButton .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openContentPage(1);
}
});
funnyStoriesButton .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openContentPage(2);
}
});
private void openContentPage(int v) {
if(v == 0) {
Intent intentContentPage = new Intent(MainActivity.this, Content.class);
intent.putExtra("keyPage",0);
startActivity(intentContentPage);
}
else if(v == 1) {
Intent intentContentPage = new Intent(MainActivity.this, Content.class);
intent.putExtra("keyPage",1);
startActivity(intentContentPage);
}
else {
Intent intentContentPage = new Intent(MainActivity.this, Content.class);
intent.putExtra("keyPage",2);
startActivity(intentContentPage);
}
}
And in the next activity you can receive intent. Fetch the value and check based on that open the content page.
I have created a file chooser within the ListActivity, which lists and allows you to select a file within the TravelLogs directory within the internal storage of my device.
The Objective:
I am looking to display text from the .txt file I chose from my file chooser within a TextView, from within dispText within the activity_list.xml file.
Any suggestions or resources? I have been through every tutorial on the topic and must be misunderstanding.
Updated to the most current code as of Nov27 #1226pm pst
public class ListActivity extends AppCompatActivity {
TextView dispText;
Button buttonOpenDialog;
TextView textFolder;
String KEY_TEXTPSS = "TEXTPSS";
static final int CUSTOM_DIALOG_ID = 0;
ListView dialog_ListView;
File root;
File curFolder;
private List<String> fileList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
buttonOpenDialog = (Button) findViewById(R.id.opendialog);
buttonOpenDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(CUSTOM_DIALOG_ID);
}
});
root = new File(Environment.getExternalStorageDirectory(), "TravelLogs");
curFolder = root;
dispText = (TextView) findViewById(R.id.text_file_data);
}
public String getTextFileData(String fileName) {
StringBuilder text = new StringBuilder();
Log.d("jason", "fileName: " + fileName );
try {
FileInputStream fIS = new FileInputStream(fileName);
InputStreamReader isr = new InputStreamReader(fIS, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
text.append(line + '\n');
}
br.close();
} catch (IOException e) {
text.append("IOException: " + e.getMessage() + "\n");
Log.e("Error!", "Error occured while reading text file from Internal Storage!");
}
return text.toString();
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case CUSTOM_DIALOG_ID:
dialog = new Dialog(ListActivity.this);
dialog.setContentView(R.layout.dialoglayout);
dialog.setTitle("Select Log");
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
textFolder = (TextView) dialog.findViewById(R.id.folder);
dialog_ListView = (ListView) dialog.findViewById(R.id.dialoglist);
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("jason", "fileName: " + fileName );
File selected = new File(fileList.get(position));
if(selected.isDirectory()) {
ListDir(selected);
} else {
Toast.makeText(ListActivity.this, selected.toString() + " selected",
Toast.LENGTH_LONG).show();
dismissDialog(CUSTOM_DIALOG_ID);
String text = getTextFileData(selected.getAbsolutePath());
Toast.makeText(ListActivity.this, text.toString() + " line",
Toast.LENGTH_LONG).show();
}
}
});
break;
}
return dialog;
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
switch (id) {
case CUSTOM_DIALOG_ID:
ListDir(curFolder);
break;
}
}
void ListDir(File f) {
curFolder = f;
textFolder.setText(f.getPath());
File[] files = f.listFiles();
fileList.clear();
for(File file : files) {
fileList.add(file.getPath());
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, fileList);
dialog_ListView.setAdapter(directoryList);
}
#Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(ListActivity.this, MainActivity.class));
finish();
}
#Override
public boolean onSupportNavigateUp(){
startActivity(new Intent(ListActivity.this, MainActivity.class));
finish();
return true;
}
}
FileInputStream fIS = getApplicationContext().openFileInput(fileName);
Change to
FileInputStream fIS = new FileInputStream(fileName);
Further i consider this post solved.
For further detail questions make another post to solve them.
I found some interesting codes online. And I copy paste it into my AIDE or Android IDE. It hasn't detected any error so far but it just only saves in one file name in all files I saved. And the older file saved will be replaced by a newer one.
public class MainActivity extends Activity {
public EditText editText;
public TextView textView;
public Button save, load;
public String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyFiles";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText) findViewById(R.id.edit);
textView = (TextView) findViewById(R.id.text);
save = (Button) findViewById(R.id.save);
File dir = new File(path);
dir.mkdirs();
}
public void buttonSave (View view)
{
File file = new File (path + "/saved.txt");
String [] saveText = String.valueOf(editText.getText()).split(System.getProperty("line.separator"));
editText.setText("");
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
Save (file, saveText);
}
}
public static void Save(File file, String[] data)
{
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(file);
}
catch (FileNotFoundException e) {e.printStackTrace();}
try
{
try
{
for (int i = 0; i<data.length; i++)
{
fos.write(data[i].getBytes());
if (i < data.length-1)
{
fos.write("\n".getBytes());
}
}
}
catch (IOException e) {e.printStackTrace();}
}
finally
{
try
{
fos.close();
}
catch (IOException e) {e.printStackTrace();}
}
}
I am planning to make an edittext and name it as yourfilename and that will be its name after I saved it to prevent overwriting files. But the problem is I don't know where to add codes and for so many codes there. I am having doubt of which codes to be used.
By the way, I am very new to this so I do not know much about it.
Thank you.
Check if this helps you.
public void buttonSave(View view) {
String fileName = editText.getText().toString();
File file = new File(path + "/" + fileName + ".txt");
String[] saveText = String.valueOf(editText.getText()).split(System.getProperty("line.separator"));
editText.setText("");
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
Save(file, saveText);
}
I am trying to make a translation application from English to Bangla using Yandex API.
It works fine in the emulator but in the real device it shows result for only one word in the text view but when writing a sentence it shows null / nothing.
I think the problem is buffer overflow but don't know how to fix it for the real device. Here are some reference pictures. In the emulator the result works fine:
In the real device it shows empty in text view:
But it works fine when a single word is used in real device.
Here is the code for my Asynctask:
public class
TranslatorBackgroundTask extends AsyncTask<String, Void, String> {
//Declare Context
Context ctx;
//Set Context
TranslatorBackgroundTask(Context ctx){
this.ctx = ctx;
}
String resultString;
#Override
protected String doInBackground(String... params) {
//String variables
String textToBeTranslated = params[0];
String languagePair = params[1];
String jsonString;
try {
//Set up the translation call URL
String yandexKey = "trnsl.1.1.20170823T130435Z.79a583874abfc8ff.61e23593359fdc92452e69a3d5ec05347fc4180b";
String yandexUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + yandexKey
+ "&text=" + textToBeTranslated + "&lang=" + languagePair;
URL yandexTranslateURL = new URL(yandexUrl);
//Set Http Conncection, Input Stream, and Buffered Reader
HttpURLConnection httpJsonConnection = (HttpURLConnection) yandexTranslateURL.openConnection();
InputStream inputStream = httpJsonConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//Set string builder and insert retrieved JSON result into it
StringBuilder jsonStringBuilder = new StringBuilder();
while ((jsonString = bufferedReader.readLine()) != null) {
jsonStringBuilder.append(jsonString + "\n");
}
//Close and disconnect
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
inputStream.close();
httpJsonConnection.disconnect();
//Making result human readable
resultString = jsonStringBuilder.toString().trim();
//Getting the characters between [ and ]
resultString = resultString.substring(resultString.indexOf('[')+1);
resultString = resultString.substring(0,resultString.indexOf("]"));
//Getting the characters between " and "
resultString = resultString.substring(resultString.indexOf("\"")+1);
resultString = resultString.substring(0,resultString.indexOf("\""));
Log.d("Translation Result:", resultString);
return jsonStringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//String text = String.valueOf(resultString);
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
MainActivity.tvTranslatedText.setText(resultString);
Toast.makeText(ctx, resultString, Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
And the code for the main activity:
public class MainActivity extends AppCompatActivity{
Context context=this;
private static final int REQUEST_CODE = 1234;
static TextView tvTranslatedText;
EditText etUserText;
Button buTranslate;
Button buSpeak;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_activity_main);
tvTranslatedText = (TextView)findViewById(R.id.tvTranslatedText);
etUserText = (EditText)findViewById(R.id.etUserText);
buTranslate = (Button)findViewById(R.id.buTranslate);
buSpeak = (Button)findViewById(R.id.buSpeak);
}
public void buTranslate(View view) {
//Default variables for translation
String textToBeTranslated = "";
textToBeTranslated= etUserText.getText().toString();
String languagePair = "en-bn"; //English to bengali ("<source_language>-<target_language>")
//Executing the translation function
Translate(textToBeTranslated,languagePair);
}
//Function for calling executing the Translator Background Task
void Translate(String textToBeTranslated, String languagePair){
TranslatorBackgroundTask translatorBackgroundTask= new TranslatorBackgroundTask(context);
String translationResult = "";
translationResult = String.valueOf(translatorBackgroundTask.execute(textToBeTranslated,languagePair)); // Returns the translated text as a String
Log.d("Translation Result",translationResult); // Logs the result in Android Monitor
}
//Speak button activities
public void buSpeak(View view) {
startVoiceRecognitionActivity();
}
private void startVoiceRecognitionActivity()
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak to translate");
startActivityForResult(intent, REQUEST_CODE);
}
/**
* Handle the results from the voice recognition activity.
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
if (data != null) {
//pull all of the matches
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String topResult = matches.get(0);
EditText AutoText = (EditText) findViewById(R.id.etUserText);
AutoText.setText(topResult);
}
}
}
}
The error message:
Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
Why didn't you add a listener to your sample code?
Try adding these on onCreate in MainActivity:
buTranslate.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
buTranslate(view);
}
}
);
Update:
There was another issue. Emulators on android sdk 16 don't show Unicode properly. Thats why you don't see your results, as those are Unicodes. Try Log to print your resultString.
I am making an app where I have my school balance set and can press dedicated buttons to take away certain amounts depending on what I purchase. I am having trouble with the balance. I have a way of updating it to what I want, however after I terminate the application I want it to stay the same in a TextView. I so far was able to make it save it to a file, or at least I hope I was, with the help of a video.
How could I on opening the app read the text file and set the TextView equal to what is in the file?
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String submitAmount = amountEnter.getText().toString();
balance.setText(submitAmount);
String myBalance = balance.getText().toString();
try {
FileOutputStream fou = openFileOutput("balance.txt",
MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fou);
try {
osw.write(myBalance);
osw.flush();
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
You can save it in SharedPrefs
change it to
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String submitAmount = amountEnter.getText().toString();
balance.setText(submitAmount);
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).
edit().putString("balance", submitAmount).commit();
}
});
and you can get it by
String balance=PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.getString("balance","nothing_there");
Seeing your code, i assume that you know how to read/write a file in android. If not, then see it from here . https://stackoverflow.com/questions/12421814/how-can-i-read-a-text-file-in-android/ You can try the following code. THe readfile method is from the upper link. You just have to read the particular line/string from the file at onCreate method of the activity. Get the reference of your desired TextView and then set the text to TextView like below. I hope it helps you
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
String texts = readfile();
TextView textView = findViewById(R.id.text_view);
textView.setText(text);
}
private String readfile() {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "file.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
} catch (IOException e) {
//You'll need to add proper error handling here
}
return text.toString();
}