I have made a java class 'store' which simply stores the values that I give through 2 spinners n one edittext...I pass the object of this class using parcelable to the intermediate class Spinpizza.java followed by Bill.java....It is showing the correct output till SpinPizza..(displays the values entered through spinner n edittext) but it gives NULL POINTER EXCEPTION IN Bill.java :-( Please help me...I m stuck with this for over 4 days..
Here is my code...
Store.java
package com.Lak;
import android.os.Parcel;
import android.os.Parcelable;
public class store implements Parcelable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String pizzaname;
private String pizzasize;
private int n;
public void setOrder(String name,String size,int qty)
{
pizzaname = name;
pizzasize = size;
n = qty;
}
public String getPizzaName()
{
return pizzaname;
}
public int getQuantity()
{return n;}
public String getPizzaSize() {
// TODO Auto-generated method stub
return pizzasize;
}
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#SuppressWarnings("rawtypes")
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public store createFromParcel(Parcel in) {
return new store(in);
}
public store[] newArray(int size) {
return new store[size];
}
};
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(n);
dest.writeString(pizzaname);
dest.writeString(pizzasize);
}
public store()
{}
public store(Parcel source){
/*
* Reconstruct from the Parcel
*/
n = source.readInt();
pizzaname = source.readString();
pizzasize = source.readString();
}
/** Called when the activity is first created. */
}
(SpinPizza.java)
package com.Lak;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class SpinPizza extends Activity{
/**
*
*/
private static final long serialVersionUID = 1L;
store B[]= new store[10];
Spinner s=null,s1=null;
EditText edittext=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drop);
s = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(
this, R.array.pizzaarray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<?> adapter1 = ArrayAdapter.createFromResource(
this, R.array.sizearray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter1);
edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) {
// Perform action on key press
int i=0;
B[i]=new store();
int n=Integer.parseInt(edittext.getText().toString());
B[i].setOrder(s.getSelectedItem().toString(), s1.getSelectedItem().toString(),n );
TextView objText=(TextView) findViewById(R.id.pl);
TextView objText1=(TextView) findViewById(R.id.pl2);
objText.setText(B[i].getPizzaName());
objText1.setText(B[i].getPizzaSize());
i++;
Toast.makeText(SpinPizza.this, edittext.getText(), Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
Button next1 = (Button) findViewById(R.id.bill);
next1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Bill.class);
for(int i =0;i<B.length;i++)
{
myIntent.putExtra("myclass"+i,B[i]);
}
myIntent.putExtra("length",B.length);
startActivityForResult(myIntent, 0);
}
});
}
}
(Bill.java)
package com.Lak;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class Bill extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.calc);
store B[] = new store[10];
Bundle bj=getIntent().getExtras();
int length = bj.getInt("length");
for(int i = 0 ;i<length;i++)
{
B[i] = (store)bj.getParcelable("myClass"+i);
}
// B = (store[]) bj.get("myClass");
/* Find Tablelayout defined in main.xml */
TableLayout tl = (TableLayout)findViewById(R.id.myTable);
/* Create a new row to be added. */
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
/* Create TEXTVIEWS to be the row-content. */
for(int i=0;i<length;i++)
{ TextView b = new TextView(this);
b.setText(B[i].getPizzaName()); // NULL POINTER EXCEPTION :(
TextView b1 = new TextView(this);
b1.setText(B[i].getPizzaSize());
TextView b2 = new TextView(this);
b2.setText(B[i].getQuantity());
b.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
b1.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
b2.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
/* Add TextViews to row. */
tr.addView(b);
tr.addView(b1);
tr.addView(b2);
/* Add row to TableLayout. */
tl.addView(tr,new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
}}
}
Well, if this line is throwing the exception:
b.setText(B[i].getPizzaName());
Then the options are:
b is null (definitely not; it's assigned a non-null value in the previous line)
B is null
B[i] is null
My money's on the last one. Here's how you initialize the array:
for(int i = 0 ;i<length;i++)
{
B[i] = (store)bj.getParcelable("myClass"+i);
}
Is there anything to say that getParcelable won't return null?
From the documentation for Bundle.getParcelable():
Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.
So my guess is that getParcelable is returning null. Now you need to find out why, and fix it. I'd also suggest using more conventional and descriptive names for your classes and variables.
Very old question indeed, but I got here in 2018 via a simple search and am using Kotlin so am gonna answer this for the future.
you can't actually do pacel on a final\val fields as the Parcelable interface can't write and re-write the values in it, either drop the final\val fields or don't incorporate them with your parceling scenarios.
This post is old, but the most common problem here is implementing the Parcelable interface for your class and then touching the fields and the methods, which may require you to re-implement the Parcelable interface or just add the missing.
I recommend you to install the Parcelable plugin for Android Studio or Eclipse and recreate the boiler plate.
Related
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]);
}
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) {
}
});
on the homepage of my app i have edittexts that represent counters for each row in my list. whenever i change activity and return back to my main screen all the numbers disappear, the same happens when I close the app and open it again. How do i make the numbers stay?
My main activity where I call the row layout with the edittexts
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MyActivity extends Activity implements MyAdapterInterface{
private CustomCursorAdapter customAdapter;
public ListView list1;
//instantiating the database class
com.example.rory.dripdrop.DBAdapter db = new com.example.rory.dripdrop.DBAdapter(this);
public MyActivity mMyActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
list1 = (ListView)findViewById(R.id.data_list);
db.open();
mMyActivity = this;
//button and listener for add activity
Button addBtn = (Button)findViewById(R.id.add);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Add.class);
startActivity(i);
}
});
//button and listener for delete activity
Button deleteBtn = (Button)findViewById(R.id.delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Delete.class);
startActivity(i);
}
});
//button and listener for update activity
Button updateBtn = (Button)findViewById(R.id.update);
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Update.class);
startActivity(i);
}
});
try {
String destPath = "/data/data/" + getPackageName() + "/databases/AssignmentDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB( getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//handler function for custom adapter, found example online to help with this
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomCursorAdapter(MyActivity.this, db.getAllRecords(), mMyActivity);
list1.setAdapter(customAdapter);
}
});
}
public void onResume()
{
super.onResume();
//update list
addData();
}
//refreshes data base when main page is resumed
public void addData()
{
//handler function for custom adapter, found example online to help with this
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomCursorAdapter(MyActivity.this, db.getAllRecords(), mMyActivity);
list1.setAdapter(customAdapter);
}
});
}
//chaning the running total
public void updateLitres(int value)
{
EditText editLitres = (EditText)findViewById(R.id.edit1);
//EditText myEditText2 = (EditText)findViewById(R.id.edit2);
editLitres.setText(String.valueOf(value));
//myEditText2.setText(String.valueOf(value));
}
public void updateCost(double value)
{
EditText editCost = (EditText)findViewById(R.id.edit2);
String.format("%.2f", value);
editCost.setText("€" + String.valueOf(value));
}
private class DBAdapter extends BaseAdapter {
private LayoutInflater mInflater;
//private ArrayList<>
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
return null;
}
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
}
My custom adapter for the rows
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomCursorAdapter extends CursorAdapter {
//public int counter = 0;
public ArrayList<Integer> counter;
public ArrayList<Integer> counter2;
private MyAdapterInterface mMyInterface;
public CustomCursorAdapter(Context context, Cursor cursor, MyAdapterInterface myInterface) {
//instantiating the values
super(context, cursor);
this.context = context;
this.mMyInterface = myInterface;
//array to sort each value per row
counter = new ArrayList<Integer>();
counter2 = new ArrayList<Integer>();
//default all counters to 0
for(int i=0; i<cursor.getCount(); i++)
{
counter.add(0);
counter2.add(0);
}
}
Context context;
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.row, parent, false);
return retView;
}
public void bindView(View view, Context context, final Cursor cursor) {
//getting the first value for the custom row (the item name)
TextView textViewItemName = (TextView) view.findViewById(R.id.item1);
textViewItemName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
final int litres = Integer.parseInt(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2))));
//editText for custom row
final EditText runningTotal = (EditText) view.findViewById(R.id.runningTotal);
//setting up the plus button
final Button plusButton = (Button)view.findViewById(R.id.plusButton);
plusButton.setOnClickListener(new View.OnClickListener() {
private int counterPos;
private int counter2;
public void onClick(View v) {
//code to change the value of the editText and the array, not working
//cursor.getPosition() returns the position in the list
counterPos = counter.get(cursor.getPosition());
//increments the number at counterPos
counterPos = counterPos + litres;
//incrementing the edittext
//counter2 = counter.get(cursor.getPosition());
counter2++;
//set the new value to the array position
counter.set(cursor.getPosition(), counterPos);
//changes the editText in middle of row
runningTotal.setText(Integer.toString(counter2));
//sends counterPos to the interface for the running total
mMyInterface.updateLitres(counterPos);
mMyInterface.updateCost(counterPos * 0.00488);
}
});
//setting up the minus button
final Button minusButton = (Button)view.findViewById(R.id.minusButton);
minusButton.setOnClickListener(new View.OnClickListener() {
private int counterPos = 0;
private int counter2;
public void onClick(View v) {
//code to change the value of the editText and the array, not working
counterPos = counter.get(cursor.getPosition());
//increments the number at counterPos
counterPos = counterPos + litres;
//incrementing the edittext
//counter2 = counter.get(cursor.getPosition());
counter2--;
//set the new value to the array position
counter.set(cursor.getPosition(), counterPos);
//changes the editText in middle of row
runningTotal.setText(Integer.toString(counter2));
//sends counterPos to the interface for the running total
mMyInterface.updateLitres(counterPos);
mMyInterface.updateCost(counterPos * 0.00488);
}
});
}
}
You should have a look here You should take a look at the shared preferences, http://developer.android.com/reference/android/content/SharedPreferences.html, I used this and helped me get through it, You need to save each edit text that you want to save. and as for each row I would suggest making an array or loop for saving the edit boxes in the rows
didn't read your code bro, but answering in concern to your question title :
override onStop and save the data to Shared Preferences, its very easy to use:
//To save your data
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
//to extract your data in onCreate or whenever you feel like:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
You will want to look into SharedPreferences, once you do you will basically be saving your values in SharedPreferences in an onPause() / onDestroy() method, and then in your onResume() / onCreate() methods you will retrieve the previously stored data
Edit: You can retrieve a string from an EditText in the following way
String toStore = EditText.getText().toString();
and then store it
getSharedPreferences("PREFERENCE",MODE_PRIVATE).edit().putString("KEY", toStore);
so...
public void onPause(){
super.onPause();
String toStore = EditText.getText().toString();
getSharedPreferences("PREFERENCE",MODE_PRIVATE).edit().putString("KEY", toStore);
}
public void onResume(){
super.onResume();
String toStore = PreferenceManager.getDefaultSharedPreferences(context).getString("KEY", "defaultStringIfNothingFound");
EditText.setText(toStore);
}
You may use onSavedInstanceState and onRestoreInstanceState methods of activity !
So in onSavedInstanceState (called before your activity pauses) you may save your `EditText' values to the bundle,
And restore them back in onRestoreInstance state.
You can use the link by #Kaique for more reference,
and also this answer https://stackoverflow.com/a/16769864/826657 and all related answers here.
You should take a look at the shared preferences, http://developer.android.com/reference/android/content/SharedPreferences.html
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
}
This is my code:
package com.testotspeech;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class AndroidTestToSpeechActivity extends Activity implements
TextToSpeech.OnInitListener, OnItemSelectedListener {
/** Called when the activity is first created. */
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;
private ArrayList<String> itemsList;
private Spinner spinner;
private String contry_name;
private ArrayAdapter<String> dataAdapter;
private TextView textview;
private Iterator itr;
private String[] t = {"Please Select An Item"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i("----------",Arrays.toString(Locale.getAvailableLocales()));
itemsList = new ArrayList<String>();
itemsList.add(Arrays.toString(Locale.getAvailableLocales()));
spinner = (Spinner)findViewById(R.id.spinner1);
spinner.setOnItemSelectedListener(this);
dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,t);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner.setAdapter(dataAdapter);
textview = (TextView)findViewById(R.id.textView1);
tts = new TextToSpeech(this, this);
btnSpeak = (Button) findViewById(R.id.btnSpeak);
txtText = (EditText) findViewById(R.id.txtText);
// button on click event
btnSpeak.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
speakOut();
}
});
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.ENGLISH);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
btnSpeak.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
if (position == 0)
{
}
else
{
}
}
public void onNothingSelected(AdapterView<?> parent) {
textview.setText("");
}
}
EDITED:
What i want to do is when i click on thw spinner it will collapse/open down and i will have for each item and box of it self and it will be in row for example i clicked on the spinner i will see now under it:
Hello
Bye
Daniel
and now if i click on Hello it will put the Hello in the textView1 if i click on the Bye it will put it also in textView1 and so on.
But the graphics the designing of the spinner i want it to be that when i click on it it will collapse down and show me the items in a row so i can click and select each item in a single click.
Now what i did is just adding the spinner a text "Please Select An Item"
I uploaded image of how i wanted it to be like for example:
That is the behavior of the spinner, there is always a selected item.
You can create a flag and use that in an override of the onItemSelected, put a counter in there and use that to ignore the first time in.
Like this:
private int spinnerSelectCount = 0;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(spinnerSelectCount == 0) {
// Do nothing... initial item on spinner display is the selected item
} else {
// your code to process spinner selection here
}
}
});
EDIT
You need to put your string as the first item in your array, not a separate string.
itemsList = new ArrayList<String>();
itemsList.add("Please Select An Item");
itemsList.add(Arrays.toString(Locale.getAvailableLocales()));
Then call the spinner using the array:
dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,itemsList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner.setAdapter(dataAdapter);
And since you're doing that you should change the filter to be based on position, not count.
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(pos == 0) {
// Do nothing... initial item on spinner display is the selected item
} else {
// your code to process spinner selection here
textview.setText(itemsList.get(pos));
}
}
});
EDIT 2
Are you looking for multi-selection? That's not possible with a standard spinner, it is set up to select one item only. If you are really looking to select multiple items you need to use a list or create a custom spinner.
Fortunately, it looks like someone has already done that. You can find the code in this SO Answer
EDIT 3
The MultiSpinner does not need a new project. You merely create a new class and use that to populate your spinner.
1) Create a new class called MultiSpinner
2) Copy the code from link (leave out the package name as you'll want to use your own)
3) In your xml call out the spinner like so (replacing com.yourpackage.name with your actual package name):
<com.yourpackage.name.MultiSpinner android:id="#+id/multi_spinner" />
4) Call the spinner as shown in the link:
MultiSpinner multiSpinner = (MultiSpinner) findViewById(R.id.multi_spinner);
multiSpinner.setItems(items, getString(R.string.for_all),
this);
An easy solution would be to set the first item of the spinner to a text like "Please select a value..". Then in the code..
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(pos == 0) {
// do nothing..
} else {
// your code..
}
}
});