App keeps crashing when ListView item is clicked on - java

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

Related

How to load, save, and show array to list?

I have XML layout like this:
[....textedit....][addbutton]
=======list1=========
=======list2=========
=======list3=========
=======list4=========
What to do if I want to Load and Show the list onCreate from SharePreferences, be able to Add "item" to the list, and save it to SharedPreferences? Any extra simple beginner explanation are welcome since I'm a total newb.
My code below is a big mess, and I got it 100% from stitching from one example to another example that I got from anywhere.
package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import android.widget.EditText;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ListAdapter;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.Toast;
import android.view.View;
import android.content.SharedPreferences;
import android.content.Context;
public class MainActivity extends Activity {
String FileName = "myFile";
Button BtnSave;
EditText editName;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BtnSave = findViewById(R.id.btn1);
BtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveFile();
}
});
lv = (ListView) findViewById(R.id.list1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,empty);
lv.setAdapter(adapter);
//Setting onClickListener on ListView
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(),"Item Clicked: "+i,Toast.LENGTH_SHORT).show();
}
});
editName = findViewById(R.id.edit1);
}
private void saveFile() {
String strName = editName.getText().toString();
SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", strName);
editor.commit();
Toast.makeText(this,"Data Saved Successfully",Toast.LENGTH_SHORT).show();
}
}
I think this should help you.
fun addProduct(productsItem: Product) {
sharedPreferences=context.getSharedPreferences(TAG,Context.MODE_PRIVATE)
var gson=Gson()
var cartProduct=getAllProducts()
cartProduct.add(productsItem)
var json=gson.toJson(cartProduct)
println(json)
sharedPreferences.edit().putString("cart_products",json).apply()
}
fun getAllProducts(): ArrayList<Product?> {
sharedPreferences=context.getSharedPreferences(TAG,Context.MODE_PRIVATE)
val listType =
object : TypeToken<List<Product?>?>() {}.type
var productsItemList:ArrayList<Product?> = ArrayList();
val json=sharedPreferences.getString("cart_products",null)
if (json !=null){
var gson=Gson()
productsItemList=gson.fromJson(json,listType)
}
return productsItemList
}
Okay, so you need to:
1)input some word in EditText
2) show it in ListView
3) save it to preferences
right?
I think you must do next steps:
Create private ArrayList<String> list = new ArrayList();
When you input something in EditText and clicked on button, call list.add(editName.getText.toString()); and then call saveFile and save list.toString();
When you need to load file, create function
private void loadFile() {
SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
String string = sharedPref.getString("name", "");
ArrayList<String> newList = new ArrayList<String>(Arrays.asList(string.split(", ")));
}
Load in adapter your newList.

Adapter not working inside asyncTask when notifyDataSetChanged?

i've got problem when trying to implement loadmore, exactly problem is adapter.notifyDataSetChanged inside AsyncTask. i trying to implement from this tuts https://github.com/shontauro/android-pulltorefresh-and-loadmore
, this tuts try implementing using extend ListActivity in Class, but i'm using extend Fragment, anyway this code is working, but just data not updated when trying to get data from loadmore. i'm sorry if my language is bad :)
this is my class :
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.bye.swipetab.adapter.ViewPagerAdapter;
import com.viewpagerindicator.CirclePageIndicator;
import com.viewpagerindicator.UnderlinePageIndicator;
import java.util.Arrays;
import java.util.LinkedList;
public class Tour extends Fragment {
private static final String TAG = Tour.class.getSimpleName();
View myView;
private String[] values ;
private static final String brand_value = "brand_value";
// Array of strings...
String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry","WebOS"};
// list with the data to show in the listview
private LinkedList<String> mListItems;
// The data to be displayed in the ListView
private String[] mNames = { "Fabian", "Carlos", "Alex", "Andrea", "Karla",
"Freddy", "Lazaro", "Hector", "Carolina", "Edwin", "Jhon",
"Edelmira", "Andres" };
// Declare Variables
ViewPager viewPager;
PagerAdapter vAdapter;
String[] rank;
String[] country;
String[] population;
int[] flag;
UnderlinePageIndicator mIndicator;
ListView listView;
ArrayAdapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myView = inflater.inflate(R.layout.tour_layout, null);
View header = inflater.inflate(R.layout.tour_header_layout, null);
//View footer = inflater.inflate(R.layout.tour_footer_layout, null);
listView = (ListView) myView.findViewById(android.R.id.list);
listView.addHeaderView(header, null, false); // header will not be clickable
mListItems = new LinkedList<String>();
mListItems.addAll(Arrays.asList(mNames));
adapter = new ArrayAdapter<String>(getActivity(), R.layout.tour_listview, R.id.MobileArray, mNames);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text
String brand_text = ((TextView) view.findViewById(R.id.MobileArray)).getText().toString();
//Toast.makeText(getApplicationContext(),brand_text, Toast.LENGTH_SHORT).show();
// Starting single contact activity
Intent in = new Intent(getActivity(), TourActivity.class);
in.putExtra(brand_value, brand_text);
in.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(in);
}
});
population = new String[] {
"1,354,040,000",
"1,210,193,422",
"315,761,000",
"315,123,000",
"363,752,000" };
flag = new int[] {
R.drawable.offline_ide_4,
R.drawable.offline_ide_1,
R.drawable.offline_ide_2,
R.drawable.offline_ide_3,
R.drawable.offline_ide_5 };
// Locate the ViewPager in viewpager_main.xml
viewPager = (ViewPager) myView.findViewById(R.id.pager);
// Pass results to ViewPagerAdapter Class
vAdapter = new ViewPagerAdapter(getContext(), rank, country, population, flag);
// Binds the Adapter to the ViewPager
viewPager.setAdapter(vAdapter);
CirclePageIndicator indicator = (CirclePageIndicator)myView.findViewById(R.id.indicator);
indicator.setViewPager(viewPager);
final float density = getResources().getDisplayMetrics().density;
indicator.setRadius(5 * density);
//indicator.setBackgroundColor(0x7f0c006a);
//indicator.setPageColor(R.color.black);
//indicator.setFillColor(R.color.tab_bg_yellow_deep);
//indicator.setStrokeColor(R.color.tab_bg_yellow_deep);
//indicator.setStrokeWidth(2 * density);
// set a listener to be invoked when the list reaches the end
((LoadMoreListView) listView)
.setOnLoadMoreListener(new LoadMoreListView.OnLoadMoreListener() {
public void onLoadMore() {
// Do the work to load more items at the end of list
// here
new LoadDataTask().execute();
}
});
return myView;
}
private class LoadDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
if (isCancelled()) {
return null;
}
// Simulates a background task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
for (int i = 0; i < mobileArray.length; i++) {
mListItems.add(mobileArray[i]);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
mListItems.add("Added after load more");
// We need notify the adapter that the data have been changed
adapter.notifyDataSetChanged();
// Call onLoadMoreComplete when the LoadMore task, has finished
((LoadMoreListView) listView).onLoadMoreComplete();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
((LoadMoreListView) listView).onLoadMoreComplete();
}
}
}
please tell me why this is not working ?
mListItems is not used for anything.
mNames is the one linked to the adapter, not mListItems which you are filling in the AsyncTask, may be you should review that.
mListItems.addAll(Arrays.asList(mNames));
adapter = new ArrayAdapter<String>(getActivity(), R.layout.tour_listview, R.id.MobileArray, mNames);
and then you do
for (int i = 0; i < mobileArray.length; i++) {
mListItems.add(mobileArray[i]);
}

Issues with Searching ListView (Android)

I have been having trouble trying to get my Searchbox working to search the Listview for appropriate rows, and then displaying as required.
Basically, when I type in the searchbox, either the app crashed or gives me 'null object reference' errors from various files (ListView.java, TextView.java etc..)
I suspect it has a lot to do with inexperience on comparing strings between the EditText and the array created from JSON values. Displaying the listview is fine, searching it has been a frustrating hurdle. Would appreciate any help possible, thanks!
My code sections are as below,
ListViewActivity.java
package com.example.myapplication;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.util.Log;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.example.myapplication.WaterWellRigsJsonUrl;
import com.example.myapplication.Rig;
public class ListViewActivity extends Activity {
private ListView listview;
private ArrayList<Rig> Rigs;
private ArrayList<Rig> RigsTemp;
private ArrayAdapter<Rig> adapter;
private ArrayAdapter<Rig> adapter2;
private EditText et;
String searchString = "";
private final static String TAG = ListViewActivity.class.getSimpleName();
private final static String url = "http://www.world-rigs.com/waterwellrigs/json.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
listview = (ListView) findViewById(R.id.listview);
setListViewAdapter();
getDataFromInternet();
final EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.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) {
//adapter.getFilter().filter(s);
String searchString = s.toString();
if (s.length() > 0) {
for (int i = 0; i < Rigs.size();i++) {
if (searchString.equalsIgnoreCase(Rigs.get(i).getName())) {
Rig rigtemp = new Rig();
rigtemp.setName(Rigs.get(i).getName());
rigtemp.setImageUrl(Rigs.get(i).getImageUrl());
rigtemp.setRigId(Rigs.get(i).getRigId());
RigsTemp.add(rigtemp);
Log.e("myTag2", "value:" + RigsTemp.size());
}
}
}
adapter2 = new CustomListViewAdapter(ListViewActivity.this, R.layout.item_listview, RigsTemp);
listview.setAdapter(adapter2);
}
});
}
private void getDataFromInternet() {
new WaterWellRigsJsonUrl(this, url).execute();
}
private void setListViewAdapter() {
Rigs = new ArrayList<Rig>();
adapter = new CustomListViewAdapter(this, R.layout.item_listview, Rigs);
listview.setAdapter(adapter);
listview.setTextFilterEnabled(true);
}
//parse response data after asynctask finished
public void parseJsonResponse(String result) {
Log.i(TAG, result);
try {
JSONObject json = new JSONObject(result);
JSONArray jArray = new JSONArray(json.getString("rig_array"));
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
Rig rig = new Rig();
rig.setName(jObject.getString("name"));
rig.setImageUrl(jObject.getString("image"));
rig.setRigId(jObject.getString("rigid"));
Rigs.add(rig);
Log.e("myTag", Rigs.get(i).getRigId());
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
CustomListViewAdapter.java
package com.example.myapplication;
import java.util.List;
import android.app.Activity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.myapplication.Rig;
import com.loopj.android.image.SmartImageView;
import com.squareup.picasso.Picasso;
public class CustomListViewAdapter extends ArrayAdapter<Rig> {
private Activity activity;
public CustomListViewAdapter(Activity activity, int resource, List<Rig> rigs) {
super(activity, resource, rigs);
this.activity = activity;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.item_listview, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
Rig rig = getItem(position);
holder.name.setText(rig.getName());
holder.authorName.setText("WR" + rig.getRigId());
Picasso.with(activity).load(rig.getImageUrl()).into(holder.image);
return convertView;
}
private static class ViewHolder {
private TextView name;
private TextView authorName;
private ImageView image;
public ViewHolder(View v) {
name = (TextView) v.findViewById(R.id.title);
image = (SmartImageView) v.findViewById(R.id.thumbnail);
// SmartImageView image = (SmartImageView) v.findViewById(R.id.my_image);
authorName = (TextView) v.findViewById(R.id.author);
}
}
}
Also getting the following errors, which do get frustrating but I think it has something to do with null reference in my Adapter or RigsTemp array while searching...
01-30 13:17:45.300 16835-16835/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 16835
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
at android.widget.ListView.setAdapter(ListView.java:487)
at com.example.myapplication.ListViewActivity$1.onTextChanged(ListViewActivity.java:84)
at android.widget.TextView.sendOnTextChanged(TextView.java:7663)
at android.widget.TextView.handleTextChanged(TextView.java:7723)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:9440)
at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:964)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:515)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:454)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:33)
at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:685)
at android.view.inputmethod.BaseInputConnection.setComposingText(BaseInputConnection.java:445)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:340)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:78)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
You don't need to create two adapters and initialize them again and again. Create just one adapter and use notifyDataSetChanged to change data and update ListView
private ArrayList<Rig> RigsTemp;
private ArrayAdapter<Rig> adapter;
Change your function as follows:
private void setListViewAdapter() {
Rigs = new ArrayList<Rig>();
RigsTemp = new ArrayList<Rig>();
adapter = new CustomListViewAdapter(ListViewActivity.this, R.layout.item_listview, RigsTemp);
listview.setAdapter(adapter);
listview.setTextFilterEnabled(true);
}
And Change the TextWatcher code with following code:
public void onTextChanged(CharSequence s, int start, int before, int count) {
String searchString = myFilter.getText().toString();
RigsTemp.clear();
if (s.length() > 0) {
for (int i = 0; i < Rigs.size(); i++) {
if (searchString.equalsIgnoreCase(Rigs.get(i).getName())) {
Rig rigtemp = new Rig();
rigtemp.setName(Rigs.get(i).getName());
rigtemp.setImageUrl(Rigs.get(i).getImageUrl());
rigtemp.setRigId(Rigs.get(i).getRigId());
RigsTemp.add(rigtemp);
}
}
} else {
// Only if you want to show all results when user has not entered anything in EditText
// Else remove this line to show empty ListView at start
RigsTemp.addAll(Rigs);
}
adapter.notifyDataSetChanged();
}

"Real time" answer in a conversion program

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) {
}
});

Currency app needs update

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
}

Categories