Created
January 1, 2020 09:29
-
-
Save ssaurel/ba5402c5f0a83d539582265053812aee to your computer and use it in GitHub Desktop.
MainActivity for the Anagram Finder App on SSaurel's Blog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.ssaurel.myanagram; | |
import android.app.Dialog; | |
import android.os.Bundle; | |
import android.view.View; | |
import android.widget.Button; | |
import android.widget.EditText; | |
import android.widget.TextView; | |
import androidx.appcompat.app.AlertDialog; | |
import androidx.appcompat.app.AppCompatActivity; | |
import java.util.List; | |
import butterknife.BindView; | |
import butterknife.ButterKnife; | |
import butterknife.OnClick; | |
public class MainActivity extends AppCompatActivity { | |
@BindView(R.id.input) | |
EditText input; | |
@BindView(R.id.validate) | |
Button validate; | |
@BindView(R.id.result) | |
TextView result; | |
private Dialog waitDialog; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
ButterKnife.bind(this); | |
// we disable validate button because words are not loaded from assets | |
validate.setEnabled(Anagram.isLoaded()); | |
// we need to load words from assets | |
loadWords(); | |
} | |
private void loadWords() { | |
new Thread(() -> { | |
Anagram.loadWords(MainActivity.this); | |
runOnUiThread(() -> { | |
validate.setEnabled(Anagram.isLoaded()); | |
}); | |
}).start(); | |
} | |
@OnClick(R.id.validate) | |
public void validate(View v) { | |
String text = input.getText().toString(); | |
if (text != null) { | |
final String text2 = text.trim(); | |
if (!"".equals(text2)) { | |
showWaitDialog(); // wait dialog for user | |
new Thread(() -> { | |
final List < String > words = Anagram.listWords(text); // we search anagrams for entered letters in separate thread | |
runOnUiThread(() -> { | |
hideWaitDialog(); | |
// we display results | |
displayResult(words); | |
}); | |
}).start(); | |
} | |
} | |
} | |
private void showWaitDialog() { | |
waitDialog = new AlertDialog.Builder(this).setMessage("Wait").create(); | |
} | |
private void hideWaitDialog() { | |
waitDialog.dismiss(); | |
} | |
private void displayResult(List < String > words) { | |
if (words.isEmpty()) { | |
result.setText("NO RESULT"); | |
} else { | |
StringBuilder sb = new StringBuilder(); | |
for (String word: words) { | |
sb.append(word).append("\n"); | |
} | |
result.setText(sb); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment