I am working on an app that uses 5 tabs and each tab has a different fragment. In all of these fragments I have from 1 up to 10 dynamically created tablelayouts and each one of them can have as many rows as the user wants. Each row may have up to 16 columns of EditText, Spinner, Checkbox. My problem is that when I rotate my phone I lose all the data inside these tablelayouts. My ViewPagerAdapter that hosts these fragments extends FragmentStatePagerAdapter. I am not losing any data outside the tables. I understand that when I rotate the phone they are recreated but I want to keep my data. I do not want to create a database because when I finish adding data in my app I want to save everything to a .txt file. This is code for one of my tables
table18 = (TableLayout) view.findViewById(R.id.blg_parameter18_table);
TableRow.LayoutParams tlparams18 = new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
//Create header
TableRow table18HeaderRow = new TableRow(view.getContext());
table18HeaderRow.setLayoutParams(tlparams18);
TextView table18HeaderColumn0 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn0, R.string.blg_parameter18_0, tlparams18);
TextView table18HeaderColumn1 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn1, R.string.blg_parameter18_1, tlparams18);
TextView table18HeaderColumn2 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn2, R.string.blg_parameter18_2, tlparams18);
TextView table18HeaderColumn3 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn3, R.string.blg_parameter18_3, tlparams18);
TextView table18HeaderColumn4 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn4, R.string.blg_parameter18_4, tlparams18);
TextView table18HeaderColumn5 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn5, R.string.blg_parameter18_5, tlparams18);
TextView table18HeaderColumn6 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn6, R.string.blg_parameter18_6, tlparams18);
TextView table18HeaderColumn7 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn7, R.string.blg_parameter18_7, tlparams18);
TextView table18HeaderColumn8 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn8, R.string.blg_parameter18_8, tlparams18);
TextView table18HeaderColumn9 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn9, R.string.blg_parameter18_9, tlparams18);
table18.addView(table18HeaderRow);
createRowTable18(table18, table18NumOfRows, tlparams18);
public void createRowTable18(TableLayout table18, int numOfRows, TableRow.LayoutParams tlparams18) {
TableRow table18Row = new TableRow(table18.getContext());
table18Row.setLayoutParams(tlparams18);
table18Row.setId(numOfRows);
CheckBox table18RowColumn1 = new CheckBox(getContext());
CheckBox table18RowColumn2 = new CheckBox(getContext());
CheckBox table18RowColumn3 = new CheckBox(getContext());
CheckBox table18RowColumn4 = new CheckBox(getContext());
CheckBox table18RowColumn5 = new CheckBox(getContext());
CheckBox table18RowColumn6 = new CheckBox(getContext());
EditText table18RowColumn7 = new EditText(getContext());
final TextView table18RowColumn8 = new TextView(getContext());
EditText table18RowColumn9 = new EditText(getContext());
Spinner spinner18 = new Spinner(getContext());
ArrayAdapter<CharSequence> adapter18 = ArrayAdapter.createFromResource(getContext(),
R.array.blg_parameter18_1_array, android.R.layout.simple_spinner_item);
adapter18.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner18.setAdapter(adapter18);
table18Row.addView(spinner18);
spinner18.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.blg_parameter_18_1_0))) {
table18RowColumn8.setText(null);
} else if (selection.equals(getString(R.string.blg_parameter_18_1_a))) {
table18RowColumn8.setText("kWh");
} else if (selection.equals(getString(R.string.blg_parameter_18_1_b))) {
table18RowColumn8.setText("lt");
} else if (selection.equals(getString(R.string.blg_parameter_18_1_c))) {
table18RowColumn8.setText("lt");
} else if (selection.equals(getString(R.string.blg_parameter_18_1_d))) {
table18RowColumn8.setText("Nm^3");
} else if (selection.equals(getString(R.string.blg_parameter_18_1_e))) {
table18RowColumn8.setText("Nm^3");
} else if (selection.equals(getString(R.string.blg_parameter_18_1_f))) {
table18RowColumn8.setText("kg");
} else if (selection.equals(getString(R.string.blg_parameter_18_1_g))) {
table18RowColumn8.setText("kWh");
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
setTableRowCheckBox(table18Row, table18RowColumn1);
setTableRowCheckBox(table18Row, table18RowColumn2);
setTableRowCheckBox(table18Row, table18RowColumn3);
setTableRowCheckBox(table18Row, table18RowColumn4);
setTableRowCheckBox(table18Row, table18RowColumn5);
setTableRowCheckBox(table18Row, table18RowColumn6);
table18RowColumn7.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
setTableRowEditView(table18Row, table18RowColumn7, tlparams18);
setTableRowTextView(table18Row, table18RowColumn8, tlparams18);
table18RowColumn7.setInputType(InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_NORMAL);
setTableRowEditView(table18Row, table18RowColumn9, tlparams18);
table18.addView(table18Row);
}
public void addRow18() {
createRowTable18(table18, table18NumOfRows, tlparams);
table18NumOfRows++;
}
public void removeRow18() {
if (table18NumOfRows > 0) {
table18.removeViewAt(table18NumOfRows);
table18NumOfRows--;
} else {
Toast.makeText(getContext(), "Δεν υπάρχουν γραμμές στον πίνακα", Toast.LENGTH_SHORT).show();
}
}
When I complete inserting data they are too many to save and recall them one by one everytime i rotate the phone. Any ideas?
When your orientation changes, Android destroys your current activity and creates a new activity again, so you must manage your state.
You can use onSaveInstanceState to save the state and then get the same it in onCreate, for example:
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("MyObject", myObject);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
final MyDataType myData = savedInstanceState.getString("MyObject"));
// fill your layout...
}
}
You can manage the state of your fragments too, please check here. Fragments can be "retain his instance" please read this or this.
Here another great post.
In some projects where I worked, when the application was not prepared for screen rotation, we had to disable this configuration.
I hope this will be useful for you.
Android will automatically save and restore your tables and the associated text views, but you need to do a couple of things.
Make sure each view you want to save has an id. Only views will an id will be saved. See generateViewId and setId.
Note: In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android:id attribute.
Even with an id set, Android will not by default save the value of a TextView presumably because TextViews tend to be static. You can force a save/restore of a TextView by using freezesText.
android:freezesText
If set, the text view will include its current complete text inside of its frozen icicle in addition to meta-data such as the current cursor position. By default this is disabled; it can be useful when the contents of a text view is not stored in a persistent place such as a content provider. For EditText it is always enabled, regardless of the value of the attribute.
There may be some odds and ends to tend to, but that should be the bulk of the changes needed.
I am programmatically creating an EditText field whose input value I need to read after. But when I try to read the text inside my OnClickListener, it says that textNewProdPrice is accessed within inner class and should be declared final. How do I get around this? This is what I have so far:
EditText textNewProdPrice = new EditText(this);
textNewProdPrice.setTextColor(Color.WHITE);
textNewProdPrice.setHint("New Value");
textNewProdPrice.setTextSize(25);
textNewProdPrice.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL);
Button buttonPriceChange = new Button (this);
buttonPriceChange.setClickable(true);
buttonPriceChange.setBackgroundResource(R.drawable.buttonmain);
buttonPriceChange.setTextColor(Color.WHITE);
buttonPriceChange.setText("Change");
buttonPriceChange.setTextSize(25);
prodDetails.addView(textNewProdPrice);
prodDetails.addView(buttonPriceChange);
buttonPriceChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newProductPrice = textNewProdPrice.getText().toString();
ContentValues values = new ContentValues();
values.put(COLUMN_PRODUCTS_PRICE, newProductPrice);
dataBase.update(TABLE_NAME_PRODUCTS, values, "_id='" + currentProductID + "'");
Intent intent = new Intent(products_details.this, products_details.class);
intent.putExtra("currentProduct", currentProductID);
startActivity(intent);
finish();
}
});
Make the EditText final
final EditText textNewProdPrice = new EditText(this);
or if you wish to refer it out of the block the use setId()
Documentation setId():
Sets the identifier for this view. The identifier does not have to be unique in this view's hierarchy. The identifier should be a positive number.
EditText textNewProdPrice = new EditText(this);
textNewProdPrice.setId(1001); //Your any random id
Just declare your EditText final, as suggested:
final EditText textNewProdPrice = new EditText(this);
Doing an ID lookup for the EditText would be a waste since you already have a reference to it.
As the title states, I am looking to find out how to create a button dynamically when another button in another activity is pressed. This is being done with the Android SDK.
Basically, I have two activities, MainActivity and SecondaryActivity, within the SecondaryActivity you enter some information, title, text, id, so on and so forth. When you click the "Save" button it sends some, information to MainActivity(not the issue). As well as sending the information, I need to create an entirely new button within the MainActivity.
Any suggestions on how this should be accomplished?
Thanks.
Edit 1
public void CreateNewButton(View view)
{
LinearLayout lineLayout = (LinearLayout)findViewById(R.id.linear_layout);
TextView newTextView = new TextView(this);
int id = rand.nextInt(100);
int newId;
newTextView.setVisibility(View.VISIBLE);
newTextView.setId( R.id.new_button + id );
newTextView.setText("New Item");
newTextView.setTextSize(35);
newTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(getBaseContext(), SecondActivity.class);
startActivity(intent);
}
});
lineLayout.addView(newTextView);
}
This code generates the new TextView( Decided to change it up ) but now the issue I have, is newTextView.setText(); needs to get the text from the other activity
newTextView.setText(i.getData().toString());
putting this in the CreateNewButton(View view) methods causes an error since technically there is no data in the field that it is trying to grab from.
The problem at hand is I need to create the new TextView field WITH the name of the new account that has yet to be created. If that makes any sense.
I'm going to assume you want to add this button to a LinearLayout:
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout1);
Button button = new Button(this);
button.setText("I'm a button!");
// add whatever other attributes you want to the button
linearLayout.addView(button);
This is my Add button code which will get the text from AutoCompleteTextView and list into ListView on each click of Add button. I am so confusing about getting text from all TextView which created by user.
Because I need to compare the user inputs in all TextViewwith symptoms column in database to diagnose the disease. Hope you guys can help me =)
private OnClickListener onClick() {
return new OnClickListener() {
#Override
public void onClick(View v) {
mLayout.addView(createNewTextView(mEditText.getText().toString()));
}
};
}
private TextView createNewTextView(String text) {
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
//textView.setText("Symptom: " + text);
textView.setText(text);
return textView;
}
You can maintain a ArrayList where you can store all the getText() if all the text views.
Just define and initialize your arraylist before you use it.
Initialize like below
ArrayList<String> arrayList = new ArrayList<String>();
And in createNewTextView() method you can have the below line to add the names to arraylist
arrayList.add(text)
later you can use these arraylist for reference and get all the text entered by user
I will try to explain my problem. The code below as you can see try to add some textviews and buttons as the array get from another class.
public class Breakfast extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
sv.addView(ll);
if (extras != null) {
String food[]=extras.getStringArray("food");
String foodCateg[]=extras.getStringArray("foodCateg");
int K=0;
for (int i = 0; i < food.length/3; i++) {
TextView foodDay = new TextView(this);
foodDay.setText("Day "+ (i+1));
ll.addView(foodDay);
for (int j=K;j<K+3;j++){
Button contfood= new Button(this);
contfood.setText(food[j]);
ll.addView(contfood);
}
K=K+3;
}
this.setContentView(sv);
}
}
My question is how can I know what of this buttons are clicked on the screen?? Because in the case of what one of them are clicked (getting the text that have write before), I will do something or other thing.
ahhhhhhhhhhhhhhhhh yes I know how to do a ListActivity. But first I think in doing by hand because I don´t think how to symplify this...
Thank you for the answers of trying to build with everything a listview and then the method OnListItemClick, but I think that isn´t the solution.
I said that because when I insert the day for example (I Don´t put hear all the code...) but I do .setgravity .setSize .setbackgroundResource etc. And with the food for that day I use a diferent .setgravity and more parameters. So I think that with listview everything would have the same specifications... and that´s what I don´t like.
so... to know what button is pressed on the screen?
You could use contfood.setId(i) and work your way from there.
But what you are doing looks like you really want to create a ListActivity and use it's OnItemClickListener.
What you should do is put an id to each button "contfood". And then when you click on a button retrieve the id back to do the action you want.
Another way is to create the button and attach the method public void onClick(View view):
for (int j=K;j<K+3;j++){
Button contfood= new Button(this);
contfood.setText(food[j]);
ll.addView(contfood);
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), xxx.class);
startActivityForResult(myIntent, 0);
}
}
and add the parameters within the method.