Android: compare string input (edittext) with arraylist - java

I want to compare my input string with an array list of another class, so I used the searchfield to compare them. As below it works fine.
Input Class
public class Suche extends Activity{
private Button zumergebnis;
final Intent zum_ergebnis = new Intent("android.intent.action.activity_ergebnis");
static String mystring;
static void setstring(String textView){
mystring = textView;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_suche);
zumergebnis = (Button) findViewById(R.id.zumergebnis);
zumergebnis.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
EditText searchinput = (EditText) findViewById(R.id.editText1);
String from = searchinput.getText().toString();
setstring(from);
startActivity(zum_ergebnis);
}
});}
}
Comparing Class
public class Ergebnis extends Suche
{
private TextView textView;
static String getstring(){
return mystring;
}
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ergebnis);
textView = (TextView) findViewById(R.id.textView2);
textView.setText(mystring);
class2 Object = new class2();
final ArrayList<String> word = Object.method2();
ListAdapter listenAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, word);
ListView mystringsView = (ListView) findViewById(R.id.listView1);
mystringsView.setAdapter(listenAdapter);
textView = (TextView) findViewById(R.id.textView2);
String searchField = (mystring);
for (String s : word)
{
if (searchField.toString().contains(s))
{
textView.setText("Your word"+mystring+"exists in the list");
}
else
{
textView.setText("Word"+mystring+"doesnt exist");
continue;
}
break;
}
}
}
list class
public ArrayList method2(){
ArrayList<String> word = new ArrayList<String>();
word.add("uno");
word.add("dos");
word.add("tres");
return word;
}
}
but when adding a second:
list class
public ArrayList method2(){
ArrayList<String> word = new ArrayList<String>();
word.add("uno; one");
word.add("dos; two");
word.add("tres; three");
return word;
}
}
'column' the app stops.
Anyone an idea how to even search for the second entry?

For everyone who is interested in the solution for that problem, the for- loop has to be changed to:
for (int i = 0; i < word.size(); i++) {
if (word.get(i).contains(searchField.trim())) {
textView.setText("Your input '" +mystring+ "' exists.");
}
else
adding some entries to the arraylist:
public ArrayList method2(){
ArrayList<String> word = new ArrayList<String>();
word.add("uno; one");
word.add("dos; two");
return word;
}
it works fine now.

Related

Java/Android : First tiny app answer always "false"

I try to create my first tiny app but i have a problem.
My tiny math app always say my answer is false.I don't understand why.
This is my first app, i don't know where i'm wrong.
private TextView problem;
private EditText question;
private Button button;
private TextView reponse;
private int aleatoire = new Random().nextInt(61) + 20;
private int aleatoire2 = new Random().nextInt(48) + 20;
private int result = aleatoire + aleatoire2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
problem = (TextView) findViewById(R.id.problem);
question = (EditText)findViewById(R.id.editText);
button = (Button)findViewById(R.id.button);
reponse = (TextView)findViewById(R.id.resultat);
problem.setText("Result = "+aleatoire+"+"+aleatoire2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str=question.getText().toString();
if (str.equals(result)) {
reponse.setText("True !");
} else {
reponse.setText("False !");
}
}
});
Answer always "False"
I'm a new student in the dev world.
The problem with code is that you are comparing string with integer, that's why it always returns false as java is strictly typed language.
problem code:
if(str.equals(result)){...}
possible solutions:
if( str.equals(""+result)){...}
or
str.equals(String.valueof(result)) // best solution
or
if(result==Integer.parseInt(str)){...}
Here is corrected code:
private TextView problem;
private EditText question;
private Button button;
private TextView reponse;
private int aleatoire = new Random().nextInt(61) + 20;
private int aleatoire2 = new Random().nextInt(48) + 20;
private int result = aleatoire + aleatoire2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
problem = (TextView) findViewById(R.id.problem);
question = (EditText)findViewById(R.id.editText);
button = (Button)findViewById(R.id.button);
reponse = (TextView)findViewById(R.id.resultat);
problem.setText("Result = "+aleatoire+"+"+aleatoire2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str=question.getText().toString();
if (str.equals(""+result)) {
reponse.setText("True !");
} else {
reponse.setText("False !");
}
}
});
As azurefrog comment says, you're comparing a String to an int. You will need to transform str to an int or result to a String. You can for example do:
String str=question.getText().toString();
if (str.equals(String.valueOf(result))) {
reponse.setText("True !");
} else {
reponse.setText("False !");
}

How do I access an ArrayList with user input using 2 classes?

I have an object class called "Services" as shown below...
public class Services {
private ArrayList<Double> costDATA = new ArrayList<>();
private ArrayList<Double> costWLAN = new ArrayList<>();
private ArrayList<Double> costUTILITY = new ArrayList<>();
private ArrayList<String> dimensions = new ArrayList<>();
private ArrayList<String> serviceNames = new ArrayList<>();
private double solution;
private double battery;
public void addServiceName(String services) {
this.serviceNames.add(services);
}
public void addDimensions(String services) {
this.dimensions.add(services);
}
public int getDimensionSize(){
return dimensions.size();
}
public void addDataCost(double dataCost){
costDATA.add(dataCost);
}
public void addWlanCost(double wlanCost){
costWLAN.add(wlanCost);
}
public void addUtilityCost(double utilityCost){
costUTILITY.add(utilityCost);
}
public void setSolution(double solution){
this.solution = solution;
}
public double getSolution(){
return solution;
}
public void setBattery(double battery){
this.battery = battery;
}
public double getBattery() {
return battery;
}
public ArrayList<Double> getCostDATA() {
return costDATA;
}
public ArrayList<Double> getCostWLAN() {
return costWLAN;
}
public ArrayList<Double> getCostUTILITY() {
return costUTILITY;
}
public ArrayList<String> getServiceNames() {
return serviceNames;
}
}
I use this class to store user input data from the MainActivity of my UI. Here is my MainActivity.
public class MainActivity extends AppCompatActivity {
//declare variables
private EditText name;
private EditText data;
private EditText wlan;
private EditText utility;
private Button addservice;
ListView lv;
ListView lv2;
ListView lv3;
ListView lv4;
Services services = new Services();
public ArrayList<String> servicenames;
public ArrayList<String> dimensions;
private ArrayAdapter<String> namesAdapter;
private ArrayAdapter<Double> dataAdapter;
private ArrayAdapter<Double> wlanAdapter;
private ArrayAdapter<Double> utilityAdapter;
private ArrayList<Double> costDATA;
private ArrayList<Double> costWLAN;
private ArrayList<Double> costUTILITY;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//map the components to the variables
name = (EditText) findViewById(R.id.servicename);
data = (EditText) findViewById(R.id.data);
wlan = (EditText) findViewById(R.id.wlan);
utility = (EditText) findViewById(R.id.utility);
addservice = (Button) findViewById(R.id.addservice);
lv = (ListView) findViewById(R.id.lv);
lv2 = (ListView) findViewById(R.id.lv2);
lv3 = (ListView) findViewById(R.id.lv3);
lv4 = (ListView) findViewById(R.id.lv4);
//create arraylists for each component
servicenames = services.getServiceNames();
costDATA = services.getCostDATA();
costWLAN = services.getCostWLAN();
costUTILITY = services.getCostUTILITY();
//create adapters to pass on the arraylist
namesAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, servicenames);
dataAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, costDATA);
wlanAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, costWLAN);
utilityAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, costUTILITY);
//display each arraylist in the listviews
lv.setAdapter(namesAdapter);
lv2.setAdapter(wlanAdapter);
lv3.setAdapter(dataAdapter);
lv4.setAdapter(utilityAdapter);
services.addDimensions("DATA");
services.addDimensions("WLAN");
onClickBtn();
}
public void onClickBtn() { //when user clicks button, the user input is added to the listview, and cleared for the next service
addservice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String namesOfService = name.getText().toString(); //user input for service names
String costOfData = data.getText().toString(); //user input for data costs
String costOfWLAN = wlan.getText().toString(); //user input for wlan costs
String costOfUtility = utility.getText().toString(); //user input for utility costs
double doubleWLAN = Double.parseDouble(costOfWLAN); //convert user input into double
double doubleData = Double.parseDouble(costOfData);
double doubleUtility = Double.parseDouble(costOfUtility);
//costDATA.add(doubleData); //add the double costs to each resource arraylist
//costWLAN.add(doubleWLAN);
//costUTILITY.add(doubleUtility);
services.addDataCost(doubleData);
services.addWlanCost(doubleWLAN);
services.addUtilityCost(doubleUtility);
services.addDimensions(namesOfService);
services.addServiceName(namesOfService);
namesAdapter.notifyDataSetChanged();
dataAdapter.notifyDataSetChanged();
wlanAdapter.notifyDataSetChanged();
utilityAdapter.notifyDataSetChanged();
name.setText(""); //empty the edit text fields when button is clicked
wlan.setText("");
data.setText("");
utility.setText("");
}
});
}
public void nextButton(View view) //next button, onto the next activity
{
Intent intent = new Intent(MainActivity.this, ParticleActivity.class);
startActivity(intent);
}
Now my mainActivity works fine, the UI displays the user input costs and service names just the way I need it to. After this is done, the user then goes to an activity called "ParticleActivity" which then executes two other java classes called "CustomUseCase" and "CustomService". In my "CustomUseCase" class, I always get nullpointerexception and it states that my arrayLists are empty. What am I doing wrong here? I am trying to access the arraylist from the services object as that is where I thought the values will be stored?
public class CustomServiceSelection implements Goodness {
Services services;
private ArrayList<Double> costData = services.getCostDATA();
private ArrayList<Double> costWlan = services.getCostWLAN();
private ArrayList<Double> costUtilities = services.getCostUTILITY();
private double batteryCost = services.getBattery();
public CustomServiceSelection(double costOfBattery, ArrayList<Double> costOfData, ArrayList<Double> costOfWlan,
ArrayList<Double> costOfUtilities) {
if (costUtilities == null || costUtilities.size() < 1 || costData.size() < 1 || costWlan.size() < 1) {
throw new RuntimeException("Please add atleast 1 cost to Data, WLAN and Utility");
}
if (batteryCost < 1) {
throw new RuntimeException("Please enter a battery cost more than 1");
}
this.batteryCost = costOfBattery;
this.costData = costOfData;
this.costWlan = costOfWlan;
this.costUtilities = costOfUtilities;
}
You get a nullpointerexception because you are trying to immediately access an unassigned variable
Services services; // null
// These are all null references
private ArrayList<Double> costData = services.getCostDATA();
private ArrayList<Double> costWlan = services.getCostWLAN();
private ArrayList<Double> costUtilities = services.getCostUTILITY();
private double batteryCost = services.getBattery();
You need to pass some initialized instance of the Services class into a constructor of CustomServiceSelection, then initialize the lists and other things

How to display ArrayList Strings in TextView

I need to display current values in TextView (after removing String). I'm adding String when button is On and I need to remove it, when it's Off ( I don't know if I do it well), next I need to display Strings in TextView without deleted String. I need to display only Strings from On buttons.I don't know how to display ArrayList in TextView - this code display.setText(mActiveToggles.toString()); doesn't work. Here is my code:
public class Calc extends ActionBarActivity {
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
display = (TextView)findViewById(R.id.textView2);
display.setText("Add item");
}
static boolean isempty=true;
public void changeButton(View sender) {
ToggleButton btn = (ToggleButton) sender;
ArrayList<String> mActiveToggles = new ArrayList<String>();
String b = btn.getText().toString();
boolean on = ((ToggleButton) sender).isChecked();
if(on) {
if (isempty) {
if (b.equals("0")) return;
display.setText(btn.getText());
mActiveToggles.add(b);
isempty = false;
} else {
display.append(btn.getText());
mActiveToggles.add(b);
}
}
else
{
if (b.equals(btn.getText()))
{
mActiveToggles.remove(b);
display.setText(mActiveToggles.toString());
}
}
}
Use a loop. Iterate over each element in the ArrayList to add it to a String (or if you prefer you can use a StringBuilder instead). It would look something like the following:
String activeToggles = "";
for (String s : mActiveToggles) {
activeToggles += s + " ";
}
display.setText(activeToggles);

ASyncTask and returning an ArrayList

Im trying to return an ArrayList from the AsyncTask class back to the MainAcitivity class and then use this arraylist to fill the gridview in MainActivity.
The parseURL takes a String paramater to parse the url. And parseURL is executed when the user clicks the button. The code i have compiles and run but the gridview is not populated after triggering the button event and pressing the button twice crashes the app.
EDIT: After adding loop callback, it stops crashing but it still wont populate the gridview. The ArrayList object that i want to populate the gridview is in this format 10,John,Smith
Here is my code for MainActivity (using Stanislav Bodnar suggestion)
private GridView grid1;
private ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initalized the grid and adapter
grid1 = (GridView)findViewById(R.id.gridView1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
grid1.setAdapter(adapter);
}
public void onButtonClick(View v) {
EditText textInput = (EditText) findViewById(R.id.editText1);
String code = textInput.getText().toString();
new parseURL() {
#Override
protected void onPostExecute(List<String> list) {
//use the list from parseURL to fill grid view
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
gridView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}.execute(code);
ParseURL class
public class parseURL extends AsyncTask<String, Void, List<String>> {
protected List<String> doInBackground(String... params) {
List<String> str = new ArrayList<String>();
try {
Document doc = Jsoup.connect("http://www.mywebsite.com/id/" + params).get();
Elements row1 = doc.select("table");
Elements row2 = doc.select("td");
Elements row3 = doc.select("td");
for (int i = 0; i < row1.size(); i++) {
str.add(row1.get(i).text() + "," + row2.get(i).text() + "," + row2.get(i).text());
}
return str;
} catch (Exception e) {
return new ArrayList<String>();
}
}
You can add loading callback.
public void onButtonClick(View v) {
EditText textInput = (EditText) findViewById(R.id.editText1);
String code = textInput.getText().toString();
new parseURL() {
#Override
protected void onPostExecute(List<String> list) {
//use the list from parseURL to fill grid view
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
gridView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}.execute(code);
}
Asynctask:
public class parseURL extends AsyncTask<String, Void, List<String>> {
protected List<String> doInBackground(String... params) {
List<String> str = new ArrayList<String>();
try {
Document doc = Jsoup.connect("http://www.mywebsite.com/id/" + params).get();
Elements row1 = doc.select("table");
Elements row2 = doc.select("td");
Elements row3 = doc.select("td");
for (int i = 0; i < row1.size(); i++) {
str.add(row1.get(i).text() + "," + row2.get(i).text() + "," + row2.get(i).text());
}
return str;
} catch (Exception e) {
return new ArrayList<String>();
}
}
}
Supplement
If array list that returns by onPostExecute is not empty your grid will be populated in the next way each cell will have string 10,John,Smith. Please check that method doInBackground does not catch some exception and fills array list correctly.
Next if you want to do a table view where 1 row will contain 3 columns 10 | John | Smith then parse data into object structure:
class Person {
private int id;
private String firstName;
private String lastName;
}
Then change method doInBackground to return array list of Person objects.
Create custom adapter (extend BaseAdapter) where init view using Person object.
View will be as LinearLayout with horizontal orientation which will contain 3 TextView with Layout Weight (android:layout_weight="0.3" - set in each TextView, you can change this value). Then use ListView instead of GridView. Each row of list view will contain 1 Person.
The AsyncTask is by definition asynchronous. Your code handles it like it was synchronous.
Move
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
gridView.setAdapter(adapter);
adapter.notifyDataSetChanged();
into the setList method.
Also, passing around the MainActivity feels a bit shaky. What happens if the Activity is destroyed during the async-task?
Instead, make the AsyncTask a private inner class or an anonymous class in MainActivity
And of course you will need to initialize your list before you populate it.
Don't do gridview.setAdapter() twice. There are a few problems with that code. As P-a Bäckström wrote:
Also, passing around the MainActivity feels a bit shaky. What happens if the Activity is destroyed during the async-task? Instead, make the AsyncTask a private inner class or an anonymous class in MainActivity
You need to fix that too. Now comes the updating part:
Declare a global Handler like this:
private final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if(msg.what == 1) {
List<String> list = (List) msg.obj;
adapter.insert(list);
adapter.notifyDataSetChanged();
}
}
};
Then in onPostExecute() send your data to the UI thread using the handler and update the gridview:
protected void onPostExecute(List<String> list) {
handler.obtainMessage(1, list);
}
try this:
Mainactivity.class
private GridView grid1;
private ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initalized the grid and adapter
grid1 = (GridView)findViewById(R.id.gridView1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
grid1.setAdapter(adapter);
}
public void onButtonClick(View v) {
EditText textInput = (EditText) findViewById(R.id.editText1);
String code = textInput.getText().toString();
new parseURL(this).execute(code);
}
public void onBackgroundTaskCompleted(List<String> result) {
// TODO Auto-generated method stub
Log.i(TAG, "onBackgroundTaskCompleted List: "+result);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
gridView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
Asynctask:
public class parseURL extends AsyncTask<String, Void, List<String>> {
MainActivity caller;
public Scheduler(MainActivity mainActivity) {
// TODO Auto-generated constructor stub
this.caller = mainActivity;
}
protected void onPostExecute(List<String> result) {
caller.onBackgroundTaskCompleted(result);
}
protected List<String> doInBackground(String... params) {
List<String> str = new ArrayList<String>();
try {
Document doc = Jsoup.connect("http://www.mywebsite.com/id/" + params).get();
Elements row1 = doc.select("table");
Elements row2 = doc.select("td");
Elements row3 = doc.select("td");
for (int i = 0; i < row1.size(); i++) {
str.add(row1.get(i).text() + "," + row2.get(i).text() + "," + row2.get(i).text());
}
return str;
} catch (Exception e) {
return new ArrayList<String>();
}
}
}

removing words from a string in java

Could anyone tell me what is wrong in my code?
I am trying to pass a string to function removeWords() and this function removes some information from the String.
For example if I pass:
"I Have a Headach"
the function should return:
"Headach"
However, my function is not working:
public class WordChosen extends Activity {
private TextView wordsList;
private String symptom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_word_chosen);
//Getting String from VoiceRecognition Activity and displaying it
Intent intent = getIntent();
String wordChosen = intent.getExtras().getString("wordChosen");
//casting the string with TextView to display the result
wordsList = (TextView) findViewById(R.id.wordChosen);
Log.v("Word List:", "+++++"+wordChosen);
//Setting text to be displayed in the textView
removeWords(wordChosen);
Log.v("removewords:", "------- message is displayed");
}
public void removeWords(String wordList)
{
ArrayList<String> stopList = null;
stopList.add("i");
stopList.add("have");
stopList.add("a");
ArrayList<String> result = new ArrayList<String>(Arrays.asList(wordList.split(" ")));
for(int i=0; i<result.size();i++)
{
for(int j=0; j<stopList.size();j++)
{
if (result.get(i).equals(stopList.get(j))) {
break;
}
else {
if(j==stopList.size()-1)
{
wordsList.setText(result.get(i));
}
}
}
}
}
}
public static void main(String[] args) {
String word = "I Have a Headach";
String remove = "I Have a ";
System.out.println(removeWords(word, remove));
}
public static String removeWords(String word ,String remove) {
return word.replace(remove,"");
}
output : Headach

Categories