I am dynamically adding views to Android and am seeing a really weird result which makes little to no sense. Here is the code that shows the bug:
private static int count = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
count++;
// Allow 'up' action for actionBar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("TEST");
setContentView(R.layout.test);
LinearLayout testLinear = (LinearLayout)findViewById(R.id.testLinear);
LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.job_step_text, null, false);
TextView title = (TextView) view.findViewById(R.id.jobStepTextTextView);
final EditText editText = (EditText)view.findViewById(R.id.jobStepEditText);
title.setText("Field 1");
editText.setText("Value 1");
testLinear.addView(view);
if(count == 1) {
View view2 = inflater.inflate(R.layout.job_step_text, null, false);
TextView title2 = (TextView) view2.findViewById(R.id.jobStepTextTextView);
final EditText editText2 = (EditText)view2.findViewById(R.id.jobStepEditText);
title2.setText("Field 2");
editText2.setText("Value 2");
testLinear.addView(view2);
}
}
First time round the Activity is as follows:
Field 1: [ Value 1 ]
Field 2: [ Value 2 ]
Then when the device rotates the following is shown:
Field 1: [ Value 2 ]
Can anyone help? It seems that after the first time round the line:
final EditText editText = (EditText)view.findViewById(R.id.jobStepEditText);
is fetching an old reference and not calling setText()? When the screen rotates the line of code which sets the text field to 'Value 2' isn't even called and yet that's the result in the Field 1 text box.
Can anyone help?
By the way - a way to fix this is to give each EditText a unique ID before adding it to the view... but that makes no sense... Surely the inflated View has no knowledge of any other views (past or present) until testLinear.addView(view); is added?
Thanks in advance.
The onSaveInstanceState in the Activity (your super class) captures information about the attached content view and reloads it for you during onCreate() So when the Activity gets recreated after the device rotates, values are put into views found by ID as soon as you call setContentView(). This can produce surprising results if you are changing your layout on-the-fly.
One approach I have used is to call findViewById to see if the child view is already present, before adding it "by hand".
Another approach would be to inflate the layout first, make your adjustments to it, then call setContentView.
[I don't quite understand Android's reason for doing this -- maybe to allow super-simple applications to skip the onSaveInstanceState/reload from bundle process??)
Related
When I select one of the items from the listview that is not visible when the activity is created it throws an exception becuase those that are not visible are null. As you see, I already know why the problem gives the exception and I would thank the one that gives me the tip for solving it. Here's the code.
public void myFunction(View view) {
int i, i2 = 0;
// get the row the clicked button is in
ListView lerroa = (ListView) view.getParent();
i = lerroa.getPositionForView(view);
System.out.println(i + 1);
LinearLayout ll = (LinearLayout) lerroa.getChildAt(i);
TextView pedido = (TextView) ll.getChildAt(0);
}
Any easier way of taking the textview at the item that has been clicked on?
I've solved the problem.
In order to show also the items of the list view that were not visible, those that caused the NullPointers, I've replaced the line of code which crashed the app. Here it is:
Replace:
LinearLayout ll = (LinearLayout) lerroa.getChildAt(i);
For this one:
LinearLayout ll = (LinearLayout) lerroa.getChildAt(i -lerroa.getFirstVisiblePosition()).findViewById(R.id.LinearLayout3);
getVisiblePosition allows us playing with the first item shown at the LinearLayout and so avoids any NullPointer.
I know this is a bit shoddy and that is not the best way to code what I want to achieve. In spite of this, I've seen so many times the same error on the internet but without any correct answare. I wish this would be usefull for others.
Have a nice code!
I'm new to android, so maybe I'm doing something horribly wrong. I want to have a particular Activity that shows details about an instance of a "Creature" class for a game. Name, damage taken, that sort of thing.
I'm having a problem getting the creature data to be properly shown in the GUI objects. Both at initial creation (where it should copy the creature's name into the name field) and when a damage mark is added (where it doesn't update to show the proper image).
Here's my mini-example of what I have:
public class CreatureDetailActivity2 extends Activity
{
Creature creature;
public void addMark(View v)
{
// connected to the button via android:onClick="addMark" in the XML
creature.getTrack().addDamage(DamageType.Normal, 1);
refreshDisplay();
new AlertDialog.Builder(this).setTitle(creature.getName())
.setMessage(creature.getTrack().toString()).show();
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_creature_detail);
creature = new Creature("Example");
refreshDisplay();
}
public void refreshDisplay()
{
final View creatureDetailView = this.getLayoutInflater().inflate(
R.layout.activity_creature_detail, null);
final EditText nameField = (EditText) (creatureDetailView
.findViewById(R.id.textbox_creature_name));
nameField.setText(creature.getName());
final ImageView damageBox0 = (ImageView) (creatureDetailView.findViewById(R.id.damageBox0));
damageBox0.setImageResource(R.drawable.__n);
// in the full program this does the same for 0 through 9, but this is a sample
// also, in the full program, this is a dynamic lookup for the correct pic
// but again, this is just a sample version.
}
}
Now the problem is that the app will load up and start, but then none of the widgets will update properly. You can click the button, and it'll show the AlertDialog, and the text of the AlertDialog will change, but the textfield in the activity won't be changed, and the ImageView doesn't change at any point from what it starts as to the one it's supposed to change to.
So I'm very stumped. I can post more about the project's setup if I'm leaving out something important, but I'm not even sure what the problem going on is so I'm not sure what else to include in my question.
final View creatureDetailView = this.getLayoutInflater().inflate(
R.layout.activity_creature_detail, null);
Inflates your Activity's layout into basically nothing, just returning the View it inflated. setContentView is what actually inflates your layout into the Activity's View hierarchy.
Once you inflate your layout you don't need to do it again. Just use findViewById without the reference to a dangling unattached View.
Change your refreshDisplay method to this:
public void refreshDisplay()
{
final EditText nameField = (EditText) findViewById(R.id.textbox_creature_name);
nameField.setText(creature.getName());
final ImageView damageBox0 = (ImageView) findViewById(R.id.damageBox0);
damageBox0.setImageResource(R.drawable.__n);
// in the full program this does the same for 0 through 9, but this is a sample
// also, in the full program, this is a dynamic lookup for the correct pic
// but again, this is just a sample version.
}
Nothing changes because You do it completely wrong.
If You wish to update any view element of current activity You do it like this
View v = findViewById(R.id.element);
v.setText("text");
this is just simple example.
You would need to cast a returned element to correct type like to be able to access all available methods.
What You do wrong is trying to inflate a layout again.
I declared an empty LinearLayout to which in my onCreate method I call a function that has a loop that repeats five times to inflate another layout and add it to my LinearLayout.
private void setupList() {
LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout itemList = (LinearLayout) findViewById( R.id.itemList );
itemList.removeAllViews();
for ( Category category :: categories ) {
View rowView = layoutInflater.inflate(R.layout.category_row, null);
initializeRow( rowView, category.percentComplete );
itemList.addView( rowView );
}
}
Then in my initializeRow method I initialize a TextView and ProgressBar that are in the view that I just inflated.
private void initializeRow( final View view, final int percentComplete ) {
TextView topicView = ((TextView) view.findViewById(R.id.topic));
topicView.setText( category.title );
ProgressBar progressBar = (ProgressBar) view.findViewById( R.id.progressBar );
progressBar.setMax( 100 );
progressBar.setProgress( percentComplete );
TextView textView = (TextView) view.findViewById( R.id.progressText );
textView.setText( percentComplete "% Complete" );
}
The first time this activity gets created the progress bar and text view are displayed with the proper values. However if I rotate my device, the TextViews get displayed with the proper values, but all the ProgressBars show the progress that corresponds to the last ProgressBar. Why does this work when onCreate gets called initially but not when the onCreate method gets called after the device has been rotated?
I realize that all the ProgressBars have the same id. But in my code I am getting the reference to the specific ProgressBar by using the findViewById of the view that I inflated. I was able to get this working by giving each ProgressBar a unique id by calling
progressBar.setId( progressBarIds[ position ] );
in my initializeRow method. I am curious if this behavior is a result of some bug in ProgressBar or if there is some rule about layoutInflaters or ProgressBars that I do not understand.
The difference between onCreate and the rotation event is that in onCreate you secuentially inflate the view that has only 1 progressbar. When you call view.findViewById( R.id.progressBar ); there's only 1 possible progressbar that can be found. Then you set its value to percentComplete.
When you rotate the phone, Android destroys and creates the activity. It also then tries to restore the values of the controls/views of the activity. It saves the view's values and ids in a bundle and then tries to restore them from there. I'm suspecting that since all the progressbars have the same id, when reading the value from the bundle there's only value assigned to that id. I.e. for every control it checks its id, and tries to find the corresponding value in the bundle. Since all of them have the same id, all of them get the same value.
Consider that this is the code to save to a bundle: bundle.putInt("valueKey", integer), probably all the progressbars end up having the same key.
But regardless of how the value is stored, the id is the very mean to tell each progressbar appart from the others. How is the system to know which one is which?
Since the number of progressbars is dependant on the number of categories, you'll probably going to have to handle the activity lifecycle on your own. Probably going to implement your own onSaveInstanceState() and onRestoreInstanceState() functions so that you can store each of the category percentages in a way that you can tell them appart when you need to restore them.
My app contains 25 edittexts. I am getting this 25 edittexts with the help of adapter class by giving count=25 and fitting in gridView by gridView.setAdapter(new TextAdapter(this)); in the activity class. So, the edittexts are dynamically generated. But the thing is I am unable to set the initial values in the edittexts. This is because the edittext objects are unavailable to set the values.
Suppose if I don't set any initial values in the edittexts and continue with my app. The same problem repeats while setting the values back in the edittexts which are entered in previous mode after changing the orientation. Because change in orientation creates new activity. Even I tried android:configChanges="orientation|keyboardHidden", but no use while I am setting the values back in the **onConfigurationChanged()**. Because I am setting the setContentView(); in the onConfigurationChanged() as I need the respective view, but still the edittext objects are unavailable to set their values.
Is there any solution to set back the values? If not, I am thinking(Might be completely wrong way, but as a newbie please go easy) to move the onCreate() method content to Application class. So the initial part goes to Application class including the creation of edittexts. and getting that edittext objects in the onCreate() method to set the values. Is it possible? Please suggest. Code snippet would be appreciated.
You will need to modify TextAdapter. Store the initial values in a String array, with the position of the String array element aligned to the position of the EditText in your GridView.
Pseudo-code (untested):
public class TextAdapter extends BaseAdapter {
String [] initial_value = {"Initial Value 1", "Initial Value 2", "Initial Value 3", ..., };
public View getView(int pos, View view, ViewGroup viewGroup) {
if (view == null) {
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.edit_text_container, null);
}
(EditText) edtTemp = (EditText) view.findViewById(R.id.edit_text_id);
edtTemp.setText(initial_value[pos]);
}
}
I create a dialog and populate it with a listview that uses a custom list adapter. It works fine, but I've noticed that when the list is long enough to scroll, doing so back and forth will cause some of my list items to randomly lose some of their data. I've noticed it is always the same list items too. For instance, each list item will have a title, image, and date on it. The dates seem to vanish on some when I scroll. They are always there when I start the dialog, and they always vanish once I scroll.
The weird thing is that my list row consists of a few TextViews in 2 rows and its only the bottom row TextViews that dissapear...Any ideas?
Code for my dialog
itemSendPickerDialog = new Dialog(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Item to Send");
ListView lv = new ListView(this);
Cursor c = mDbHelper.fetchItemsByDate(id);
c.moveToFirst();
int i = R.layout.send_item_menu_row;
MyListAdapter ia = new MyListAdapter(this, mainListBackground, c, true);
lv.setAdapter(ia);
builder.setView(lv);
itemSendPickerDialog = builder.create();
itemSendPickerDialog.show();
And my custom list adapter class:
class MyListAdapter extends ResourceCursorAdapter {
public MyListAdapter(Context context, int i, Cursor cursor, boolean...sending) {
super(context, i, cursor);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title = (TextView) view.findViewById(R.id.item_name);
title.setText(cursor.getString(cursor.getColumnIndex(TripsDbAdapter.KEY_ITEM_TITLE)));
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
width = width - 150;
ViewGroup.LayoutParams params = title.getLayoutParams();
params.width = width;
title.setLayoutParams(params);
String cat = cursor.getString(cursor.getColumnIndex(TripsDbAdapter.KEY_ITEM_CATEGORY));
if (cat.equalsIgnoreCase("trip notes")) {
LinearLayout ll = (LinearLayout) view.findViewById(R.id.item_datetime_holder);
ll.setVisibility(View.INVISIBLE);
}
TextView date = (TextView) view.findViewById(R.id.item_date);
date.setText(cursor.getString(cursor.getColumnIndex(TripsDbAdapter.KEY_DEP_DATE)));
TextView time = (TextView) view.findViewById(R.id.item_time);
time.setText(cursor.getString(cursor.getColumnIndex(TripsDbAdapter.KEY_DEP_TIME)));
ImageView iv = (ImageView) view.findViewById(R.id.image_icon);
if (iv != null) {
int index = cursor.getColumnIndex(TripsDbAdapter.KEY_ITEM_TYPE);
String type = cursor.getString(index);
if (type != null) {
} else {
type = "notes";
}
iv.setImageResource(getTypeResource(type));
}
}
}
I have faced this problem too...
The problem you are facing is due to the recycling of views by the LIstView when you scroll up/down. In your case, the ListView is giving you those recycled views , whose properties you have changed by making them invisible. Some possible solutions could be:
1) When cat.equalsIgnoreCase("trip notes")) is becoming true, you are making some views invisible. This invisible view is then recycled and given back. The recycled view is still invisible (when it is given back to you), so what you can do is make this invisible view visible in the beginning of your ListAdapter every time .
You can put this code at the beginning of bindView method where you make the layout visible first and then proceed with rest of the logic.( In short, the dates from your display are not vanishing but are just invisible).
2) Override getViewTypeCount() in you adapter . From your codesnippet, it looks like you have two types of rows( one in which R.id.item_datetime_holder is invisible and other in which it is visible) , so return 2 from this method( please do some trial and error ) . This should take care of the problem.
public int getViewTypeCount() {
return 2;
}
You will find an excellent explanation at this link http://logc.at/2011/10/10/handling-listviews-with-multiple-row-types/
3) You can inflate completely different layouts depending on your if condition. But the effeciency would be a little less.
I had a similar problem, when scrolling a list, only the items after the window height decided to get their data repeating from index 0 - so if the last visible item was 8, the next would be 0 again.
So you could try to check if the index of the view is correct, maybe this method of ListView would help
lv.getPositionForView(view);
I've figured out that the code that is doing this is in my custom list adapter class
String cat = cursor.getString(cursor.getColumnIndex(TripsDbAdapter.KEY_ITEM_CATEGORY));
if (cat.equalsIgnoreCase("trip notes")) {
LinearLayout ll = (LinearLayout) view.findViewById(R.id.item_datetime_holder);
ll.setVisibility(View.INVISIBLE);
}
I hide some of the layout items depending on what the category is, and for some reason when putting a list view in an AlertDialog builder it appears to mix up the items. I don't know exactly how I am going to fix it, but for now if I just remove the invisibility functionality, my data won't go away.
I would use two different layouts, depending on the "type" of list item. It looks like you are switching the "type" based on the cat string containing "trip notes". If it contains it, then you would have a layout that is the same as you have now, but without the item_datetime_holder view. If it doesn't contain it, then you would use the same layout as you're using now (send_item_menu_row).
Here is a good tutorial on how to use multiple layouts in a ListView: http://android.amberfog.com/?p=296
By the way, I think that the reason why some of your rows are not drawing correctly is due to view reuse by the ListView. Utilizing the multiple layouts like I've mentioned above should fix the problem since you won't be changing the visibility of views, but just utilizing two different views to render, depending on what type of list item you're rendering.