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) {
}
}
}
Related
The problem is the adding method is said to be null and I don't know why. All I want to do is to get the values from the expense fragment and add item to the custom recycler view, the value of the item is what I inputted in the expense fragment.
Following is the main screen Java code:
package com.example.admin.test2;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
*/
public class MainScreen extends Fragment {
private ArrayList<ExampleItem> mExampleList;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
// Spinner spinner;
EditText amountt;
EditText detailss;
EditText datee;
public MainScreen() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate (R.layout.fragment_main_screen, container, false);
mExampleList = new ArrayList <ExampleItem>();
mExampleList.add(new ExampleItem(R.drawable.others, "", "", "ADD EXPENSES"));
mRecyclerView = view.findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getContext());
mAdapter = new ExampleAdapter(mExampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
return view;
}
public void insertItem()
{
Bundle bundle = getArguments();
String deTails = bundle.getString("Details");
String aMount = bundle.getString("Amount");
mExampleList.add(0, new ExampleItem(R.drawable.food, "Food & Drink", ""+ deTails, "₱ " + aMount));
mAdapter.notifyDataSetChanged();
}
}
Following is another activity from where the value will come:
package com.example.admin.test2;
import android.app.DatePickerDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class Expense extends Fragment {
private ArrayList<ExampleItem> mExampleList;
public Expense() {
// Required empty public constructor
}
//SPINNER
Spinner sp1;
CustomAdapter adapter;
String[] names = {"Food & Drink", "Shopping", "Transportation", "Home", "Bills & Fees", "Entertainment", "Healthcare", "Education", "Beauty", "Others"};
int[] images = {R.drawable.food, R.drawable.shopping, R.drawable.transportation, R.drawable.home, R.drawable.bills, R.drawable.entertainment, R.drawable.medical, R.drawable.education, R.drawable.beauty, R.drawable.others};
//DATE PICKER
private EditText mDisplayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
FloatingActionButton fab;
EditText amounttt;
EditText detailsss;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate (R.layout.fragment_expense, container, false);
//spinner
sp1 = (Spinner)view.findViewById(R.id.customSpinner);
adapter = new CustomAdapter(getActivity(), names, images);
sp1.setAdapter(adapter);
//fab onClick - sending values to the recycler view
fab = (FloatingActionButton) view.findViewById(R.id.fabs);
detailsss = (EditText) view.findViewById(R.id.textDetailss) ;
amounttt = (EditText) view.findViewById(R.id.textAmountt);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = sp1.getSelectedItemPosition();
String descrptn = detailsss.getText().toString();
String amouunt = amounttt.getText().toString();
Bundle bundle = new Bundle();
bundle.putString("Details", descrptn);
bundle.putString("Amount", amouunt);
bundle.putInt("Position", pos);
android.support.v4.app.FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MainScreen ms = new MainScreen();
ms.setArguments(bundle);
ms.insertItem();
fragmentTransaction.replace(R.id.replaceLayout, ms);
fragmentTransaction.commit();
}
});
//date picker
mDisplayDate = (EditText) view.findViewById(R.id.datePick);
mDisplayDate.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(getActivity(),
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
mDateSetListener,
year, month, day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
//Calendar calendar = Calendar.getInstance();
//String currentDate = DateFormat.getDateInstance().format(calendar.getTime());
month = month + 1;
String date = month + "-" + day + "-" + year;
mDisplayDate.setText(date);
}
};
return view;
}
}
Following is the Adapter code:
package com.example.admin.test2;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<ExampleItem> mExampleList;
public static class ExampleViewHolder extends RecyclerView.ViewHolder
{
public ImageView mImageView;
public TextView mLabel;
public TextView mDetails;
public TextView mAmount;
public ExampleViewHolder(View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.imageIcon);
mLabel = itemView.findViewById(R.id.textLabel);
mDetails = itemView.findViewById(R.id.textDetails);
mAmount = itemView.findViewById(R.id.textAmount);
}
}
public ExampleAdapter(ArrayList<ExampleItem> exampleList)
{
mExampleList = exampleList;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.customlist, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(view);
return evh;
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
holder.mImageView.setImageResource(currentItem.getmImageResource());
holder.mLabel.setText(currentItem.getMlabel());
holder.mDetails.setText(currentItem.getMdetails());
holder.mAmount.setText(currentItem.getMamount());
}
#Override
public int getItemCount() {
if (mExampleList == null)
return 0;
else
return mExampleList.size();
}
}
And, following is the Item Java code:
package com.example.admin.test2;
public class ExampleItem {
private int mImageResource;
private String mlabel;
private String mdetails;
private String mamount;
public ExampleItem(int imageResource, String label, String details, String amount)
{
mImageResource = imageResource;
mlabel = label;
mdetails = details;
mamount = amount;
}
public int getmImageResource()
{
return mImageResource;
}
public String getMlabel() {
return mlabel;
}
public String getMdetails() {
return mdetails;
}
public String getMamount() {
return mamount;
}
}
for complete codes and the errors, please refer to this link (because the whole code does not fit and exceeded 30000 words): https://textuploader.com/15s40
For me it didn't work like that neither. I recommend you to create a method in your adapter that directly modify the list inside the adapter. So instead of doing:
mExampleList.add(0, new ExampleItem(R.drawable.food, "Food & Drink", ""+ deTails, "₱ " + aMount));
mAdapter.notifyDataSetChanged();
inside your adapter you have a method like:
public void add (ExampleItem itemToAdd) {
mExampleList.add(itemToAdd);
notifyDataSetChanged();
}
and in your activity:
mAdapter.add(new ExampleItem(R.drawable.food, "Food & Drink", ""+ deTails, "₱ " + aMount));
You have added insertItem() method in MAINSCREEN JAVA CODE, but never called in onCreateView() of MAINSCREEN JAVA CODE, I suggest you to add the code of insertItem() in onCreateView() of MAINSCREEN JAVA CODE.
Edit: i have added a demo application, please refer this link
I had a single recycler view in MainActivity.I'm adding items to that recycler view from sqlite database. The problem is that it is refreshing continuously when we press back button from app and come back to app again.It is adding duplicates of existing items.
Here is my MainActivity.java file
package bk.acs;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import bk.acs.AddingToDatabase.MyDialog;
import bk.acs.RecyclerView.Data;
import bk.acs.RecyclerView.ListItem;
import bk.acs.RecyclerView.MyAdapter;
public class MainActivity extends AppCompatActivity {
private static final int CONTACTS_PERMISSION = 10;
RecyclerView recview;
MyAdapter adapter;
Data d;
Toolbar toolbar;
NavigationDrawer drawer;
String appName;
LinearLayout main;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
appName = getResources().getString(R.string.app_name);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
recview = (RecyclerView) findViewById(R.id.recview);
drawer = (NavigationDrawer) getSupportFragmentManager().findFragmentById(R.id.navDrawer);
drawer.setUp((DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
d = new Data(this);
adapter = new MyAdapter(d.getList(), this);
recview.setLayoutManager(new LinearLayoutManager(recview.getContext()));
recview.setAdapter(adapter);
main = (LinearLayout) findViewById(R.id.MainLayout);
try {
createFolders();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int res_id = item.getItemId();
if (res_id == R.id.refresh) {
MyDialog dialog = new MyDialog();
dialog.show(getFragmentManager(), "myDialog");
}
return true;
}
public void updateRecView(long num, String subname) {
disableRecView();
adapter.listdata.add(new ListItem(subname, num + ""));
adapter.notifyItemInserted(adapter.listdata.size());
}
public void disableRecView() {
main = (LinearLayout) findViewById(R.id.MainLayout);
main.setVisibility(View.GONE);
}
public void createFolders() throws IOException {
File mainFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath(), appName);
File inputs = new File(mainFolder, "Inputs");
File outputs = new File(mainFolder, "Outputs");
if (mainFolder.exists()) {
Toast.makeText(this, "Welcome", Toast.LENGTH_SHORT).show();
File temp = new File(inputs, "temp.txt");
temp.createNewFile();
} else {
Toast.makeText(this, "Creating Folders", Toast.LENGTH_SHORT).show();
mainFolder.mkdir();
inputs.mkdir();
outputs.mkdir();
File temp = new File(inputs, "temp.txt");
temp.createNewFile();
}
}
public void fetchDataForSub(String s) {
Intent intent = new Intent(this, SubActivity1.class);
intent.putExtra("tv", s);
startActivity(intent);
}
}
Here is my Data.java file from where I'm getting items from database
package bk.acs.RecyclerView;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import bk.acs.MainActivity;
import bk.acs.databases.Main;
/**
* Created by bk on 01-03-2017.
*/
public class Data {
public static ArrayList<String> sample = new ArrayList<>();
public static List<ListItem> list = new ArrayList<>();
String[] cols = {"SubjectName"};
SQLiteDatabase db;
Context ctx;
public Data(Context context) {
this.ctx = context;
Main main = new Main(context, "subjects_db", 1, 1);
db = main.getReadableDatabase();
Cursor cursor = db.query("SubjectsTable", cols, null, null, null, null, null);
while (cursor.moveToNext()) {
sample.add(cursor.getString(0));
}
if (sample.size() != 0) {
((MainActivity) context).disableRecView();
}
}
public List getList() {
for (int i = 0; i < sample.size(); i++) {
ListItem listItem = new ListItem(sample.get(i), (i + 1) + ""); //Fixed crash
list.add(listItem);
}
return list;
}
}
This is MyAdapter.java file
package bk.acs.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import bk.acs.MainActivity;
import bk.acs.R;
import bk.acs.SubActivity1;
/**
* Created by bk on 01-03-2017.
*/
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {
public List<ListItem> listdata;
LayoutInflater inflater;
Context c;
public MyAdapter(List<ListItem> list, Context c) {
this.inflater = LayoutInflater.from(c);
listdata = list;
this.c = c;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.subjects_li, parent, false);
return new Holder(view);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
ListItem item = listdata.get(position);
holder.subjectName.setText(item.subName);
holder.serialNo.setText(item.sno);
}
#Override
public int getItemCount() {
return listdata.size();
}
class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView subjectName;
TextView serialNo;
View container;
public Holder(View itemView) {
super(itemView);
subjectName = (TextView) itemView.findViewById(R.id.subjectTitle);
serialNo = (TextView) itemView.findViewById(R.id.sno);
container = itemView.findViewById(R.id.cont_root);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
((MainActivity) c).fetchDataForSub(subjectName.getText().toString());
}
}
}
How can I prevent duplicates from getting added to this recycler view..Thanks in advance
Because public static List<ListItem> list = new ArrayList<>();,
is always added, so you need to clear the list before you add the items.
public List getList() {
list.clear();
for (int i = 0; i < sample.size(); i++) {
ListItem listItem = new ListItem(sample.get(i), (i + 1) + ""); //Fixed crash
list.add(listItem);
}
return list;
}
I create an activity and want to insert a new realm object
it always keep on error http null if i put getNextKey();
here is my activity
package com.example.rikirikmen.billsplit;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.rikirikmen.billsplit.Adapter.BillListAdapter;
import com.example.rikirikmen.billsplit.Adapter.MenuAdapter;
import com.example.rikirikmen.billsplit.Model.Bill;
import com.example.rikirikmen.billsplit.Model.DetailMenu;
import com.example.rikirikmen.billsplit.Model.DetailPerson;
import com.example.rikirikmen.billsplit.Model.PersonInMenu;
import com.example.rikirikmen.billsplit.Model.PersonMenuObj;
import org.w3c.dom.Text;
import java.util.ArrayList;
import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmList;
import io.realm.RealmObject;
public class DialogActivity extends AppCompatActivity {
Realm realm;
private RealmList<DetailPerson> person;
private RealmList<PersonInMenu> pim;
private ListView listView;
private MenuAdapter adapter;
private TextView menuName;
private TextView menuPrice;
private TextView menuQty;
private String bill;
private Button btnOke;
private Button btnCancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_add_menu);
realm = Realm.getDefaultInstance();
bill = getIntent().getStringExtra("bill_ID");
btnOke = (Button) findViewById(R.id.btnOkMenu);
btnCancel = (Button) findViewById(R.id.btnCancelMenu);
menuName = (TextView) findViewById(R.id.txtMenuName);
menuPrice = (TextView) findViewById(R.id.txtMenuPrice);
menuQty = (TextView) findViewById(R.id.txtMenuQuantity);
listView = (ListView) findViewById(R.id.listViewMenu);
Toast.makeText(this, getNextKey(), Toast.LENGTH_SHORT).show();
person = realm.where(Bill.class).equalTo("Bill_ID", bill).findFirst().getDetailperson();
if (person.isEmpty()){
}
else{
adapter = new MenuAdapter(this,R.layout.row_menu, person,bill);
listView.setAdapter(adapter);
}
btnOke.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (menuName.getText().length()==0 || menuPrice.getText().length()==0|| menuQty.getText().length()==0){
Toast.makeText(DialogActivity.this, "Please fill the menu detail", Toast.LENGTH_SHORT).show();
}
else {
CharSequence priceText = menuPrice.getText();
int Price = Integer.parseInt(priceText.toString());
CharSequence qtyText = menuQty.getText();
int Qty = Integer.parseInt(qtyText.toString());
realm.beginTransaction();
DetailMenu menu = realm.createObject(DetailMenu.class);
menu.setMenuID(getNextKey());
menu.setMenuName(String.valueOf(menuName.getText()));
menu.setMenuPrice(Price);
menu.setQuantity(Qty);
for (int i = 0; i < adapter.getPersonMenuObjList().size(); i++) {
PersonInMenu pim = realm.createObject(PersonInMenu.class);
pim.setPersonID(adapter.getPersonMenuObjList().get(i).getPersonID());
pim.setStatus(adapter.getPersonMenuObjList().get(i).isStatus());
menu.personInMenus.add(pim);
}
realm.copyToRealmOrUpdate(menu);
realm.commitTransaction();
realm.close();
}
}
});
}
int getNextKey()
{
return realm.where(DetailMenu.class).max("MenuID").intValue() + 1;
}
}
here is my DetailMenu.class
package com.example.rikirikmen.billsplit.Model;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.Required;
/**
* Created by rikirikmen on 4/24/2016.
*/
public class DetailMenu extends RealmObject {
#PrimaryKey
private int MenuID;
private int Quantity;
private String MenuName;
private int MenuPrice;
public RealmList<PersonInMenu> personInMenus;
public RealmList<PersonInMenu> getPersonInMenus() {
return personInMenus;
}
public void setPersonInMenus(RealmList<PersonInMenu> personInMenus) {
this.personInMenus = personInMenus;
}
public DetailMenu() {
super();
}
public int getMenuPrice() {
return MenuPrice;
}
public void setMenuPrice(int menuPrice) {
MenuPrice = menuPrice;
}
public int getMenuID() {
return MenuID;
}
public void setMenuID(int menuID) {
MenuID = menuID;
}
public String getMenuName() {
return MenuName;
}
public void setMenuName(String menuName) {
MenuName = menuName;
}
public int getQuantity() {
return Quantity;
}
public void setQuantity(int quantity) {
Quantity = quantity;
}
}
i dont know why is my getNextKey() is not work, because i used the same way in other activity and it works. Does anyone here have the same problem with me ?
max returns a Number or null if no objects exists. So most likely no DetailMenu objects exist and you get a NullPointerException.
Use this instead:
Number max = realm.where(DetailMenu.class).max("MenuID");
return (max != null) ? max.intValue() + 1 : 0;
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) {
}
});
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
}