How to code in java for real time output which displayed on the screen,as soon as user inputs some value with keyboard, with out a calculate button in activity in a simple conversion program? I have given the code below. In that it takes one input value and "FROM" and "TO" to convert the value and showed in the display with press of "calculate" button
Now I want to eliminate the "calculate" button and as soon as user inputs the numbers want to show the answer to the display
My code given below. Please let me know any additional information required
package sujaynambiar.textilecalculation;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class LengthConverter extends AppCompatActivity {
private Spinner spinner11, spinner21;
private EditText from;
private TextView to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lenght_converter);
Button btnSubmit = (Button) findViewById(R.id.btnSubmit1);
from = (EditText) findViewById(R.id.InputEditText1);
to = (TextView) findViewById(R.id.OutputTextView1);
spinner11 = (Spinner) findViewById(R.id.spinner11);
List<String> list1 = new ArrayList<String>();
list1.add("Kilometer");
list1.add("Meter");
list1.add("Centimeter");
list1.add("Millimeter");
list1.add("Feet");
list1.add("Yard");
list1.add("Inch");
list1.add("Mile");
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list1);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner11.setAdapter(dataAdapter1);
spinner21 = (Spinner) findViewById(R.id.spinner21);
List<String> list2 = new ArrayList<String>();
list2.add("Kilometer");
list2.add("Meter");
list2.add("Centimeter");
list2.add("Millimeter");
list2.add("Feet");
list2.add("Yard");
list2.add("Inch");
list2.add("Mile");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list2);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner21.setAdapter(dataAdapter2);
}
public void onClick(View v)
{
int index1 = spinner11.getSelectedItemPosition();
int index2 = spinner21.getSelectedItemPosition();
double value = 0;
if (from.getText().toString().isEmpty())
Toast.makeText(getApplicationContext(), getResources().getString(R.string.toastmessage1),
Toast.LENGTH_LONG).show();
else {
value = Double.parseDouble(from.getText().toString());
}
//From Kilometer
if (index1 == 0 && index2 == 0 )//N
{
double result = value*1;
to.setText(result+"");
}
You are looking for a text change listener.
from.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
calculateNewResult(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
You may also want to use an item select listener on the spinners.
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
updateTheCalculation();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Related
Hello I am new to Java and coding in general.
I am using a ListView to display different sets of words which are stored in array. Clicking an item in the list will display the words in the array according to which item has been clicked. I have added the lines of the code that display the text and display a hint into an if statement and now my app keeps crashing when I click on the item 0.
Could someone please give me some advice?
Here is my code :
package com.example.anotherapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
int i = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chooseGame();
}
public void chooseGame() {
final ArrayList<String> arrayList = new ArrayList<String>();
final TextView wordTextView = findViewById(R.id.wordTextView);
final EditText editTextView = findViewById(R.id.enterEditText);
final Button nextButton = findViewById(R.id.nextButton);
ArrayList<String> gamesArrayList = new ArrayList<String>();
gamesArrayList.add("A Vegan's Worst Nightmare");
gamesArrayList.add("The Wet Floor Sign");
gamesArrayList.add("The Meaning of life");
gamesArrayList.add("Campfire Story");
gamesArrayList.add("The Crocobearamouse");
final ListView gamesListView = findViewById(R.id.gamesListView);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
gamesArrayList);
gamesListView.setAdapter(arrayAdapter);
gamesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
gamesListView.setVisibility(View.INVISIBLE);
editTextView.setVisibility((View.VISIBLE));
wordTextView.setVisibility((View.VISIBLE));
nextButton.setVisibility(View.VISIBLE);
String[] zeroArray = {"Food", "Adjective", "Proper Noun", "Name"};
String displayHint = "";
String displayText = "";
displayText = enterWord() + zeroArray[i];
displayHint = zeroArray[i];
wordTextView.setText(displayText);
editTextView.setHint(displayHint);
}
}
}
);
}
public String enterWord() {
String[] zeroArray = {"Food", "Adjective", "Proper Noun", "Name"};
String entry;
if (zeroArray[i].equals("Adjective")) {
entry = "Enter an ";
} else {
entry = "Enter a ";
}
return entry;
}
public void nextWord(View view) {
i++;
}
}
Your variable i start from -1, and your codes call array[i], I think it is main reason to make your app crash
I have a problem with my code and still confused about intent which each item have their own layout like a product with their own description
Anybody know how to solve my problem? thank you before
and this is my main_activity code
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import static com.example.vinznolimit.herbindonesia.R.id.theList;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private ArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list= (ListView) findViewById(theList);
EditText theFilter = (EditText) findViewById(R.id.searchFilter);
Log.d(TAG, "onCreate: Started.");
ArrayList<String> names = new ArrayList<>();
names.add("Mitch");
names.add("Blake");
names.add("Blade");
names.add("Bruno");
names.add("Joe");
names.add("Barry");
adapter = new ArrayAdapter(this,R.layout.list_item,names);
list.setAdapter(adapter);
theFilter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
(MainActivity.this).adapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
Try this one
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent myIntent = new Intent(v.getContext(), UserSubmissionLog.class);
startActivity(myIntent);
}
}
);
I just need som minor help now. The app runs great but when you enter for ex. USD, 2 TO SEK it results 13,38. But if i change the amount to 3 nothing happens. I would have to change the currencys back and forth to make a change. I would like the app to change the result as soon as i change the value. Please help!:)
package com.example.currencyconverter;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity {
private String [] currency_name;
private ArrayAdapter<String> adapter;
private Spinner spin1, spin2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpTheSpinners();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
private void setUpTheSpinners() {
currency_name = getResources().getStringArray(R.array.currency_name);
adapter= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, currency_name);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
OnItemSelectedListener listener = new CurrencySelectedListener();
spin1 = (Spinner)findViewById(R.id.spinner1);
spin1.setAdapter(adapter);
spin1.setOnItemSelectedListener(listener);
spin2 = (Spinner)findViewById(R.id.spinner2);
spin2.setAdapter(adapter);
spin2.setOnItemSelectedListener(listener);
}
private void calculateSum() {
String [] rates = getResources().getStringArray(R.array.currency_rate);
int index1 = spin1.getSelectedItemPosition();
int index2 = spin2.getSelectedItemPosition();
double rate1 = Double.parseDouble( rates[index1] );
double rate2 = Double.parseDouble( rates[index2] );
EditText editAmount = (EditText) findViewById(R.id.editText1);
if (!TextUtils.isEmpty(editAmount.getText().toString())) {
double amount = Double.valueOf(editAmount.getText().toString());
double totalRate = amount * rate1 / rate2;
TextView totalRateText = (TextView)findViewById(R.id.editText2);
totalRateText.setText("" + totalRate);
}
}
private class CurrencySelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
calculateSum();
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
}
Your editAmount.getText().toString() value is NULL(empty). And you still trying to convert this value into DOUBLE so you got NumberFormatException .
Check editText value before parsing like:
if(!editAmount.getText().toString().equals(""))
{
//Do your job
}
Or another way is
if (!TextUtils.isEmpty(editAmount.getText().toString())) {
//Do your job
}
The error is solved and the app runs. The problem is how do i add a listener to the amound field in the app aswell? As the app is now it just sums up for ex "sek 1" + "usd 6.69" = "7.69".
Any good ideas how to make this work?
And here is my code:
package com.example.currencyconverter;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity {
private String [] currency_name;
private ArrayAdapter<String> adapter;
private Spinner spin1, spin2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpTheSpinners();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
private void setUpTheSpinners() {
currency_name = getResources().getStringArray(R.array.currency_name);
adapter= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, currency_name);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
OnItemSelectedListener listener = new CurrencySelectedListener();
spin1 = (Spinner)findViewById(R.id.spinner1);
spin1.setAdapter(adapter);
spin1.setOnItemSelectedListener(listener);
spin2 = (Spinner)findViewById(R.id.spinner2);
spin2.setAdapter(adapter);
spin2.setOnItemSelectedListener(listener);
}
private void calculateSum() {
String [] rates = getResources().getStringArray(R.array.currency_rate);
int index1 = spin1.getSelectedItemPosition();
int index2 = spin2.getSelectedItemPosition();
double rate1 = Double.parseDouble( rates[index1] );
double rate2 = Double.parseDouble( rates[index2] );
double totalRate = rate1 + rate2;
TextView totalRateText = (TextView)findViewById(R.id.textView4);
totalRateText.setText("" + totalRate);
}
private class CurrencySelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
calculateSum();
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
}
Im having trouble with my listview and search box. Searching works fine, except for the fact that it is case sensitive. However, my problem is, starting an activity right after clicking.
The start activity is based on the position of the text. Therefore, if I dont conduct any research the links work fine. Yet, if i research for specifics the listview works but the links are wrong, because they are based on the initial position of the listview and not sorted by categories.
import greendroid.app.GDActivity;
import greendroid.widget.ActionBarItem;
import greendroid.widget.NormalActionBarItem;
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class m_m_aeritalia extends GDActivity {
EditText edittext;
ListView listview;
Button search;
String[] text = { "(Lockheed) F-104S Starfighter",
"Aermecchi / EMBRAER AMX", "G-222" };
int[] image = { R.drawable.tf1, R.drawable.tf7, R.drawable.ts26 };
int textlength = 0;
ArrayList<String> text_sort = new ArrayList<String>();
ArrayList<Integer> image_sort = new ArrayList<Integer>();
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setActionBarContentView(R.layout.m_listgeneral);
addActionBarItem(
getActionBar().newActionBarItem(NormalActionBarItem.class)
.setDrawable(R.drawable.ic_title_back),
R.id.action_bar_back);
edittext = (EditText) findViewById(R.id.EditText01);
listview = (ListView) findViewById(R.id.ListView01);
listview.setAdapter(new MyCustomAdapter(text, image));
listview.setClickable(true);
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if ("(Lockheed) F-104S Starfighter".equals(text[position])) {
// code specific to 2nd list item
Intent myIntent = new Intent(view.getContext(),
mcomingsoon.class);
startActivityForResult(myIntent, 0);
}
if ("Aermecchi / EMBRAER AMX".equals(text[position])) {
// code specific to 2nd list item
Intent myIntent = new Intent(view.getContext(),
mcomingsoon.class);
startActivityForResult(myIntent, 0);
}
if ("G-222".equals(text[position])) {
// code specific to 2nd list item
Intent myIntent = new Intent(view.getContext(),
fa_f4.class);
startActivityForResult(myIntent, 0);
}
}
});
edittext.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
textlength = edittext.getText().length();
text_sort.clear();
image_sort.clear();
for (int i = 0; i < text.length; i++) {
if (textlength <= text[i].length()) {
if (text[i].indexOf(edittext.getText().toString()) != -1) {
text_sort.add(text[i]);
image_sort.add(image[i]);
}
}
}
listview.setAdapter(new MyCustomAdapter(text_sort, image_sort));
}
});
}
class MyCustomAdapter extends BaseAdapter {
String[] data_text;
int[] data_image;
MyCustomAdapter() {
}
MyCustomAdapter(String[] text, int[] image) {
data_text = text;
data_image = image;
}
MyCustomAdapter(ArrayList<String> text, ArrayList<Integer> image) {
data_text = new String[text.size()];
data_image = new int[image.size()];
for (int i = 0; i < text.size(); i++) {
data_text[i] = text.get(i);
data_image[i] = image.get(i);
}
}
public int getCount() {
return data_text.length;
}
public String getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.listview, parent, false);
TextView textview = (TextView) row.findViewById(R.id.TextView01);
ImageView imageview = (ImageView) row
.findViewById(R.id.ImageView01);
textview.setText(data_text[position]);
imageview.setImageResource(data_image[position]);
return (row);
}
}
#Override
public boolean onHandleActionBarItemClick(ActionBarItem item, int position) {
switch (item.getItemId()) {
case R.id.action_bar_back:
startActivity(new Intent(this, mbymanufacturers.class));
break;
}
return true;
}
Hope I made myself clear,
Any suggestions?
Thank You
Tiberio Bozotti
You shouldn't query the String array directy, but get the item from the Adapter.
Try this...
Create a custom private class to hold the String and integer value pair, such as:
private class DataPair { String text; int value; }
Then, instead of using your MyCustomAdapter, create an ArrayList of DataPair objects and assign it to an ArrayAdapter, such as:
new ArrayAdapter<DataPair>(this, R.layout.ListView01, new ArrayList<DataPair>);
Now, for getting your data, you only have to do:
getItem(position).text
or
getItem(position).value
In case of the setOnItemClickListener use:
((DataPair)listview.getAdapter().getItem(position)).text