I have setup a little example application where the idea is to navigate from one Activity to another and to study Memory consumption because I don't really understand when/where memory is released during this process.
Idea is to create an Activity which consume quite a lot of memory to see if memory is released correctly when we leave it before recreating it.
A HomeActivity only composed of a Button that call a BlogListActivity when button is clicked.
BlogListActivity is a ListActivity that contain BlogPost objects. This BlogPost contains a Bitmap in order to use some memory.
List of BlogPost is created dynamically in the onCreate method of BlogListActivity and then passed to an Adapter to display each PostBlog object in row of my ListView.
On an emulator with Android 2.3.3 and 128Mo of memory, I manage to move from HomeActivity to BlogListActivity and then come back to HomeActivity two times. On the third try, I get an OutOfMemoryError from BitmapFactory.
This mean I have a Memory Leak: objects that are not used anymore but still have a reference on it so they are not released. But I don't where I do it wrong.
Can someone help me finding it.
Thanks in advance for your help.
Bertrand
Link to complete source code and Eclipse project
Here is an extract of the code we are interested in
HomeActivity source code
public class HomeActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
public void onSecondActivityClick(View v) {
startActivity(new Intent(this, BlogListActivity.class));
}
}
BlogListActivity source code
public class BlogListActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bloglist);
List<BlogPost> items = new ArrayList<BlogPost>();
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.mn);
for (int i = 0; i < 5; i++) {
BlogPost post = new BlogPost();
post.author = String.format("Author%d", i);
post.title = String.format("Title%d", i);
post.date = new Date();
post.imageURL = "https://si3.twimg.com/profile_images/1143791319/MN_BLEU.png";
post.image = bmp;
post.image = BitmapFactory.decodeResource(getResources(), R.drawable.mn);
items.add(post);
}
setListAdapter(new LazyArrayAdapter(this, R.layout.listitem_blog, items));
}
}
LazyArrayAdapter source code
public class LazyArrayAdapter extends ArrayAdapter<BlogPost> {
public LazyArrayAdapter(Context context, int textViewResourceId, List<BlogPost> objects) {
super(context, textViewResourceId, objects);
}
#Override
public View getView(int index, View view, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
if (view == null) {
view = inflater.inflate(R.layout.listitem_blog, parent, false);
}
TextView title = (TextView)view.findViewById(R.id.listitemblog_title);
TextView date = (TextView)view.findViewById(R.id.listitemblog_date);
ImageView icon = (ImageView)view.findViewById(R.id.listitemblog_icon);
BlogPost post = this.getItem(index);
title.setText(post.title);
date.setText(new SimpleDateFormat().format(post.date));
icon.setImageBitmap(post.image);
return view;
}
}
BlogPost source code
public class BlogPost {
public String title;
public String author;
public Date date;
public String imageURL;
public Bitmap image;
}
activity_bloglist Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#android:id/list">
</ListView>
</LinearLayout>
ListItemBlog Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:weightSum="100"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout android:layout_width="0px" android:layout_weight="70"
android:id="#+id/linearLayout2"
android:orientation="vertical"
android:layout_height="fill_parent">
<TextView android:id="#+id/listitemblog_title"
android:layout_width="wrap_content"
android:text="TextView"
android:textStyle="bold"
android:layout_height="wrap_content">
</TextView>
<TextView
android:id="#+id/listitemblog_date"
android:layout_width="wrap_content"
android:text="TextView"
android:layout_height="wrap_content"
android:textStyle="bold">
</TextView>
</LinearLayout>
<ImageView
android:id="#+id/listitemblog_icon"
android:layout_width="0px"
android:scaleType="centerInside"
android:layout_weight="30"
android:src="#drawable/icon"
android:layout_height="fill_parent"/>
</LinearLayout>
HomeActivity layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_height="wrap_content"
android:onClick="onSecondActivityClick"
android:layout_width="wrap_content"
android:id="#+id/button1"
android:text="Button">
</Button>
</LinearLayout>
I have studied memory usage with DDMS + MAT. Here are screenshots of what I see in MAT for the com.webcontentlistview I create:
Memory usage after navigating to BlogListActivity one time
Memory usage after navigatin to BlogListActivity several times
As we can see, even after navigating between both Activity, we still have only one BlogListActivity object in memory (with it's associated content).
But numbers of java and android objects are increasing (lines 2 and 3).
Could it be that the garbage collector simply does not have time to clean your data before you launch the activity again? How quickly did you do the test? Does it always crash, even if you take some time between starting BlogListActivity? Maybe try to run System.gc() each time the app returns to HomeActivity and see if the crashes resume.
Related
Im developing a contacts app, and for now Ive been trying to get this drawables from the array get uploaded into the Gridview on the main screen AFTER the save mosaic button is clicked in the mosaic creation screen.
the floating action button (red plus button) on the mosaicListScreen (main screen) leads to the MosaicCreationScreen). the user hypothetically uploads the image and enters the mosaic name then saves using the save mosaic button, as can be seen in the image here
For now, before I focus on uploading image and letting the user create their own unique mosaics (groups), Im testing the Gridview updating with some drawables, which are listed in the array as can be seen in the code below.
The issue thats occuring is as soon as the user clicks the floating action button on the main screen, it updates the gridview with the drawables listed in the array of the MosaicCreation Screen, THEN it goes to the MosaicCreationScreen, and when save mosaic button is clicked on the MosaicCreationScreen, the intent goes to the main screen as its supposed to do, except the gridview will have nothing on it.
so its like its doing the opposite of whats supposed to happen in steps.
here is my code for the two screens:
public class mosaicsListScreen extends AppCompatActivity {
public static mosaicsListScreen theScreen; //this variable is used in the MosaicCreationScreen to point to this screen to find the GridView by id
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
theScreen = this;
setContentView(R.layout.activity_mosaics_list_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.createMosaicButton);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),MosaicCreationScreen.class);
startActivity(intent);
finish();
}
});
}
}
here is the code for the MosaicCreationScreen (the one that opens after user clicks floating action button from mosaicListScreen (main screen))
public class MosaicCreationScreen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mosaic_creation_screen);
final GridView mosaicList = (GridView) mosaicsListScreen.theScreen.findViewById(R.id.mosaicList);
mosaicList.setAdapter(new ImageAdapter(this)); //this line of code displays the mosaics on mosaicListScreen
Button saveNewMosaicButton = (Button) findViewById(R.id.saveNewMosaicButton);
saveNewMosaicButton.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
//mThumbIds.notify();
Intent intent = new Intent(getApplicationContext(), mosaicsListScreen.class);
startActivity(intent);
finish();
//mosaicList.setAdapter(new ImageAdapter(this)); //this displays the mosaics on mosaicListScreen, it logically should go here, however "this" causes an error saying ImageAdapter (android.content.Context) in ImageAdapter cannot be applied to (anonymous android.view.View.OnClickListener)
Toast.makeText(mosaicsListScreen.theScreen, "Mosaic Created!", Toast.LENGTH_SHORT).show();
}
});
/* mosaicList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(mosaicsListScreen.theScreen, "", Toast.LENGTH_SHORT).show();
}
});*/
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
//this array holds the drawables that would appear on the Gridview
private Integer[] mThumbIds = {
R.drawable.family,
R.drawable.project
};
}
}
Here are the XML for the layouts:
content_mosaics_list_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="codesages.mosaic.mosaicsListScreen"
tools:showIn="#layout/activity_mosaics_list_screen">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/create_a_mosaic_or_pick_from_the_mosaics_created"
android:id="#+id/textView4"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="20sp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/deleteMosaicButton"
android:src="#android:drawable/ic_menu_delete"
android:clickable="true"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:contentDescription="" />
<GridView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/textView4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="14dp"
android:id="#+id/mosaicList"
android:layout_above="#+id/textView7"
android:numColumns="auto_fit" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/holdMosaictoDeleteLabel"
android:id="#+id/textView7"
android:layout_marginBottom="16dp"
android:layout_above="#+id/deleteMosaicButton"
android:layout_centerHorizontal="true" />
</RelativeLayout>
activity_mosaics_list_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="codesages.mosaic.mosaicsListScreen">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/createMosaicButton"
android:layout_width="56dp"
android:layout_height="66dp"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_input_add" />
<include layout="#layout/content_mosaics_list_screen" />
</android.support.design.widget.CoordinatorLayout>
activity_mosaic_creation_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="codesages.mosaic.MosaicCreationScreen"
android:focusable="true">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/mosaicNametextField"
android:hint="Mosaic Name"
android:layout_marginTop="81dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save New Mosaic"
android:id="#+id/saveNewMosaicButton"
android:layout_marginTop="48dp"
android:layout_below="#+id/uploadMosaicImageButton"
android:layout_centerHorizontal="true"
android:enabled="true"
android:clickable="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upload Mosaic Image"
android:id="#+id/uploadMosaicImageButton"
android:layout_marginTop="68dp"
android:layout_below="#+id/mosaicNametextField"
android:layout_centerHorizontal="true"
android:enabled="true"
android:clickable="true" />
</RelativeLayout>
mosaicList.setAdapter(new ImageAdapter(this));
thats what appears to be creating the mosaics. if i comment this out, i wont see anything in the gridview.
however, i believe that should be inside the saveNewMosaicButton onClick, but I am getting an error that says "saying ImageAdapter (android.content.Context) in ImageAdapter cannot be applied to (anonymous android.view.View.OnClickListener)"
HERE is an image example of what the desired result should be. however whats happening right now is as ive stated, as soon as the floating action button is clicked, the mosaics are created, THEN it takes you to the creation screen, in which wehn i click save mosaics, it actually erases the mosaics...a job of the trash icon which is too soon to function for now heh.
appreciate help on this
Currently, you have
public static mosaicsListScreen theScreen;
in your first Activity which you use to fill the ListView in this first Activity. This is a dangerous approach because the Activity instance referenced by this variable may be destroyed, for example if you're doing work in your second Activity (e.g. downloading images) which uses much memory, but also if the user somehow triggers a configuration change.
As you are calling finish() after starting the second Activity, you even tell the system that the first Activity may be destroyed. The only reason you did not get a NPE is that the system destroys the finished Activity not instantly but as soon as it seems a good idea to do so.
All in all, you need a way to safely transmit information from one Activity to the other. In your case, I think you would like to send the Uri of the selected images ( or for now, send the resource id of the selected drawables). Both can be accomplished by using Intent extras.
Basically, there are two options:
use startActivityForResult() and override onActivityResult() to obtain the desired information for the first Activity
simply start the first Activity from the second Activity once you have the result and use getIntent() in the first Activity (e.g. in onCreate()) to check for results
No matter what you do, always access UI elements like the ListView in the Activity to which they belong!
If you choose the second option, your first Activity could look like this:
public class mosaicsListScreen extends AppCompatActivity {
public static final String THUMB_IDS = "someuniquestring";
private GridView mosaicList;
private ArrayList<Integer> mThumbIds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mosaics_list_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.createMosaicButton);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),MosaicCreationScreen.class);
startActivity(intent);
finish();
}
});
fillThumbIds();
mosaicList = (GridView) findViewById(R.id.mosaicList);
// Note: Adapter code in this Activity
mosaicList.setAdapter(new ImageAdapter(this));
}
private void fillThumbIds()
{
mThumbIds = new ArrayList();
// somehow get older thumb ids if necessary (from database?)
// and add to ArrayList like this:
mThumbIds.add(R.drawable.family);
mThumbIds.add(R.drawable.project);
// assuming we transmit resource id's: use an int array with the Intent
int[] newThumbIds = getIntent().getIntArrayExtra(THUMB_IDS);
if (newThumbIds != null)
{
// loop through the array to add new thumb ids
for (int i = 0; i < newThumbIds.length; i++) {
mThumbIds.add(newThumbIds[i]);
}
}
}
// Adapter code goes here
// Note: thumbIds no longer as array but as ArrayList!
}
In the second Activity, you put the selected thumb ids as Intent extra as follows:
saveNewMosaicButton.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), mosaicsListScreen.class);
// if 'myNewThumbs' is the int array with the new thumb ids
intent.putExtra(mosaicsListScreen.THUMB_IDS, myNewThumbs);
startActivity(intent);
finish();
}
});
I have a card declared in the file cardslib_item_card_view:
<it.gmariotti.cardslib.library.view.CardViewNative
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
card_view:cardCornerRadius="4dp"
style="#style/native_recyclerview_card.base"
android:id="#+id/carddemo"
android:layout_width="match_parent" android:layout_height="wrap_content">
and set as content view within onCreate() method:
public class CardMariotti extends ActionBarActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cardslib_item_card_view);
//Create a Card
Card card = new Card(this);
CardViewNative cardView = (CardViewNative) this.findViewById(R.id.carddemo);
cardView.setCard(card);
card.setOnClickListener(new Card.OnCardClickListener() {
#Override
public void onClick(Card card, View view) {
Toast.makeText(CardMariotti.this, "Clickable card", Toast.LENGTH_LONG).show();
}
});
}
Now, I'd like to customize it with my own layout, containing a narrow header and some information, as follows:
<RelativeLayout android:id="#+id/cardlayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="?android:selectableItemBackground"
android:clickable="true">
<!-- layout containing 3 TextView -->
</RelativeLayout>
What is the canonic procedure for such a process? I've tried a good deal of adjustments, i.e.:
creating a second xml file called cardslib_item_layout.xml and referencing it with the Card's constructor this way: Card card = new Card(this, R.layout.cardslib_item_layout); and then setting the setContentView(R.layout.cardslib_item_card_view)
Appending the layout inside the card and then setting the setContentView(R.layout.cardslib_item_card_view).
This way; cardslib_item_card_view:
<it.gmariotti.cardslib.library.view.CardViewNative
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
card_view:cardCornerRadius="4dp"
android:id="#+id/carddemo"
android:layout_width="match_parent" android:layout_height="wrap_content">
<RelativeLayout>
<!-- my layout containing a header and some TextViews -->
</RelativeLayout>
</it.gmariotti.cardslib.library.view.CardViewNative>
In both tests I experience the following issues:
The overall result is completely distorced
most importantly, the RelativeLayout is placed ON TOP of the card, making any operation on the card impossible (for example, setting the Card.OnCardClickListener on the card itself won't work since the user will be clicking the RelativeLayout and not the card itself)
attempt 1:
attempt 2:
What is the canonic procedure?
EDIT2: ANSWER
The contribution given by #Msk worked fine for me, although I discovered later that with some minor changes it is also possible to obtain the same results by using the original cardslib's Card class, without resorting to the creation of a new class DeviceCard extending the Card class.
I was able to adjust my layout (header and the rest of the card's layout overlapping with each other, as shown in the screenshots) with just some minor and trivial changes in the cardslib_item_layout.xml file (which I had overlooked before); at the same time I was able to eliminate the phantom padding that is automatically attached to every card, by applying Mariotti's answer to this question.
Try this
You can define your own layout for the cards-lib.
Create your custom XML:
Here is an example custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="8dp"
android:paddingRight="6dp"
android:paddingTop="7dp"
android:paddingBottom="7dp"
android:id="#+id/parentView">
<TextView
android:id="#+id/name"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="27"
android:paddingRight="8dp"
android:paddingLeft="8dp"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:text=""
android:layout_gravity="center"
android:editable="false"
/>
</LinearLayout>
In your JAVA code create a class for the custom card that you wish to use:
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.ViewToClickToExpand;
public class DeviceCard extends Card {
private String IP;
private String MAC;
private String name;
private Boolean reachable;
private Boolean editable;
Boolean markedFlag;
public DeviceCard(Context context) {
this(context, R.layout.custom_layout);
}
public DeviceCard(Context context,String param1,...,Type paramn) {
this(context, R.layout.device_card);
this.name = param1;
}
public DeviceCard(Context context, int innerLayout) {
super(context, innerLayout);
init();
Log.d("myTag", "Init called");
}
private void init(){
}
#Override
public void setupInnerViewElements(ViewGroup parent, final View view) {
Log.i("myTag","setupInnerView");
final TextView nameBox = (TextView)view.findViewById(R.id.name);
//edit name if required
}
}
Now in your JAVA code, when you need to use the card-list:
DeviceCard card = new DeviceCard(this, name);
This method has always worked for me
Trying to create custom rows in my listview (to look like this). I've created a custom row layout & derived adapter class. The data loads and shows fine, but the text is not using any format/style specified in my custom row .xml layout file. It's all just the default size/weight, etc.
Here's the custom row layout (listview_desc.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#222222">
<TextView
android:id="#+id/name"
android:text="Name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_margin="10dip"
android:textStyle="bold"
android:textSize="20dip"
/>
<TextView
android:id="#+id/description"
android:text="Description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_margin="10dip"
android:textSize="13dip" />
</LinearLayout>
Here's my main layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:theme="#android:style/Theme.NoTitleBar"
android:minWidth="25px"
android:minHeight="25px"
android:background="#drawable/gradient_darkbg">
<ListView
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView1" />
</LinearLayout>
My adapter code (I'm using Xamarin, but I don't think that's the problem...)
public class ListViewFormAdapter : BaseAdapter<Form>
{
List<Form> mForms;
Activity context;
public ListViewFormAdapter(Activity context, List<Form> items)
: base()
{
this.context = context;
this.mForms = items;
}
public override long GetItemId(int position)
{
return position;
}
public override Form this[int position]
{
get { return mForms[position]; }
}
public override int Count
{
get { return mForms.Count; }
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = mForms[position];
View view = convertView;
if (view == null) // no view to re-use, create new
view = context.LayoutInflater.Inflate(Resource.Layout.listview_desc, null);
view.FindViewById<TextView>(Resource.Id.name).Text = item.Name;
view.FindViewById<TextView>(Resource.Id.description).Text = item.Description;
return view;
}
}
And finally the main activity where I load and use the adapter:
public class HomeScreenActivity : Activity
{
List<Form> mForms;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Create your application here
SetContentView (Resource.Layout.Home);
// Load all forms and populate the main menu
mForms = Utils.FormLoader.LoadForms("Forms");
ListView listView = FindViewById<ListView>(Resource.Id.listView1);
listView.Adapter = new ListViewFormAdapter(this, mForms);
}
}
Sorry for all the code, maybe it'll help someone in the future... thanks for any help.
I'm not sure that this is the problem, but you inflating the views incorrectly. it should be
view = inflater.inflate(R.layout.listview_desc, parent, false);
instead of
view = context.LayoutInflater.Inflate(Resource.Layout.listview_desc, null);
using the 3 parameter version of inflate
What styles aren't showing correctly? I'm not sure what you're expecting or what you're seeing from the question. If it is to do with alignment, you should bear in mind that android:layout_alignParentLeft="true" is not valid in a LinearLayout
Thanks for the response guys. Turns out it was some problem with Git/Xamarin. I committed my sources at another machine, came home, synced up and all my formatting in the row layout xml were gone. Who knows... maybe a cached version was being used or something. I actually had to use the code posted on this page to get it to work (since it was lost), so maybe someone can use this as example code. It works.
I am working on android app and am trying to get fragments working but I've run into a problem.
When the app launches it loads an activity which is supposed to house the two fragments. Fragment1 contains a list of stored logins and fragment 2 will show the details associated with that login.
The list fragment is supposed to retrieve data from the SQLite database and display on the screen and once the item is clicked, it loads the second fragment, but I am having problem getting the first stage working.
In my main activity class I have the following.
public class PasswordListMain extends Activity {
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.password_management);
}
}
The password_management XML file contains the following
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:id="#+id/passwordList"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.BoardiesITSolutions.PasswordManager.PasswordListFrag">
</fragment>
</LinearLayout>
It just contains the fragment as this is the portrait screen, I thought I'd get this bit working before getting it working side by side.
The PasswordListFrag contains the following
public class PasswordListFrag extends ListFragment{
Common common;
com.BoardiesITSolutions.logic.ManagePasswordList managePasswordList;
ArrayList<String> savedPassword;
TextView txtNoRecords;
ListView myListView;
ArrayAdapter<Spanned> passwordArrayAdapter;
AdView adView;
#Override
public View onCreateView(LayoutInflater inflator, ViewGroup container, Bundle savedInstanceState)
{
View view = inflator.inflate(R.layout.password_list, container, false);
myListView = getListView();
common = new Common(getActivity().getApplicationContext());
//AdView adView = (AdView)findViewById(R.id.adView);
common.requestAdvert(adView);
managePasswordList = new ManagePasswordList(getActivity().getApplicationContext());
//txtNoRecords = (TextView)findViewById(R.id.password_noRecords);
populateListArray();
common.showToastMessage("Adapter updated", Toast.LENGTH_LONG);
//myListView.setOnItemClickListener(mListView);
return view;
}
private void populateListArray()
{
ArrayList<Spanned> passwords = managePasswordList.getPasswordList();
if (passwords != null && passwords.size() > 0)
{
passwordArrayAdapter = new ArrayAdapter<Spanned>(getActivity().getApplicationContext(),
android.R.layout.simple_list_item_1, passwords);
setListAdapter(passwordArrayAdapter);
passwordArrayAdapter.setNotifyOnChange(true);
myListView.setTextFilterEnabled(true);
txtNoRecords.setVisibility(View.GONE);
}
else
{
txtNoRecords.setVisibility(View.VISIBLE);
}
}
}
Below is the XML for the list fragment
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="#+id/password_noRecords"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"
android:text="There are currently\nno saved logins"
android:textSize="20dp"
android:textStyle="bold|italic"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/adView">
</ListView>
<com.google.ads.AdView android:id="#+id/adView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
ads:adUnitId="5555555"
ads:adSize="BANNER"
android:layout_alignParentBottom="true">
</com.google.ads.AdView>
</RelativeLayout>
When the app loads it instantly crashes when it tries to load this screen.
The error is
java.lang.RuntimeException: Unable to start activity ComponentInfo
PasswordListMain: android.view.InflatException: Binary XML file line
#7 Error inflating class fragment
I have no idea what's causing this or how to fix the problem.
Thanks for any help you can provide.
My best guess for the issue is this line (but admittedly I'm unsure):
myListView = getListView();
You're calling it before the fragment has a view - and I don't think that will work too well. I would recommend doing your initialization work of the views involved in onActivityCreated() instead of in onCreateView() and the other components (like your data store thing and Common) in onCreate()
I have an Activity that retrieves data from a web service. This data is presented in a ListView via an ArrayAdapter which inflates a RelativeLayout with three TextViews inside, nothing fancy and it work fine.
Now I want to implement a Details Activity that should be called when a user clicks an item in the ListView, sounds easy but I can't for the life of me get the onItemClickListener to work on my ArrayAdapter.
This is my main Activity:
public class Schema extends Activity {
private ArrayList<Lesson> lessons = new ArrayList<Lesson>();
private static final String TAG = "Schema";
ListView lstLessons;
Integer lessonId;
// called when the activity is first created.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// can we use the custom titlebar?
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
// set the view
setContentView(R.layout.main);
// set the title
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
// listview called lstLessons
lstLessons = (ListView)findViewById(R.id.lstLessons);
// load the schema
new loadSchema().execute();
// set the click listeners
lstLessons.setOnItemClickListener(selectLesson);
}// onCreate
// declare an OnItemClickListener for the AdapterArray (this doesn't work)
private OnItemClickListener selectLesson = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int i, long l) {
Log.v(TAG, "onItemClick fired!");
}
};
private class loadSchema extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
// ui calling possible
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Schema.this,"", "Please wait...", true);
}
// no ui from this one
#Override
protected Void doInBackground(Void... arg0) {
// get some JSON, this works fine
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
// apply to list adapter
lstLessons.setAdapter(new LessonListAdapter(Schema.this, R.layout.list_item, lessons));
}
My ArrayAdapter code:
// custom ArrayAdapter for Lessons
private class LessonListAdapter extends ArrayAdapter<Lesson> {
private ArrayList<Lesson> lessons;
public LessonListAdapter(Context context, int textViewResourceId, ArrayList<Lesson> items) {
super(context, textViewResourceId, items);
this.lessons = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
Lesson o = lessons.get(position);
TextView tt = (TextView) v.findViewById(R.id.titletext);
TextView bt = (TextView) v.findViewById(R.id.timestarttext);
TextView rt = (TextView) v.findViewById(R.id.roomtext);
v.setClickable(true);
v.setFocusable(true);
tt.setText(o.title);
bt.setText(o.fmt_time_start);
rt.setText(o.room);
return v;
}
}// LessonListAdapter
The main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="#+id/main"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent" android:layout_width="fill_parent"
android:screenOrientation="portrait"
>
<!-- student name -->
<TextView
android:id="#+id/schema_view_student"
android:text="Name" android:padding="4dip"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center_vertical|center_horizontal"
style="#style/schema_view_student"
/>
<!-- date for schema -->
<TextView
android:id="#+id/schema_view_title"
android:layout_height="wrap_content"
android:layout_margin="0dip"
style="#style/schema_view_day"
android:gravity="center_vertical|center_horizontal"
android:layout_below="#+id/schema_view_student"
android:text="Date" android:padding="6dip"
android:layout_width="fill_parent"
/>
<!-- horizontal line -->
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="#55000000"
android:layout_below="#+id/schema_view_title"
/>
<!-- list of lessons -->
<ListView
android:id="#+id/lstLessons"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_below="#+id/schema_view_title"
/>
</RelativeLayout>
The list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="60px"
android:padding="12dip">
<TextView
android:id="#+id/timestarttext"
android:text="09:45"
style="#style/LessonTimeStartText"
android:layout_width="60dip"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_height="fill_parent" android:gravity="center_vertical|right" android:paddingRight="6dip"/>
<TextView
android:id="#+id/titletext"
android:text="Test"
style="#style/LessonTitleText"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_toRightOf="#+id/timestarttext"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true" android:gravity="center_vertical|center_horizontal"/>
<TextView
android:id="#+id/roomtext"
android:text="123"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
style="#style/LessonRoomText"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:gravity="center_vertical" />
</RelativeLayout>
Been messing with this for the last couple of hours and I can't seem to get my head around what the problem is. My problem looks very similar to this question, but I'm not extending ListActivity, so I still don't know where my onListClickItem() should go.
UPDATE: Now I've puzzled with this for several days and still can't find the issue.
Should I rewrite the activity, this time extending ListActivity instead of Activity? Because it provides the onItemClick method itself and is probably easier to overwrite.
Or, should I bind a listener directly in each getView() in my ArrayAdapter? I believe I have read this is bad practice (I should do as I tried and failed in my post).
Found the bug - it seems to be this issue. Adding android:focusable="false" to each of the list_item.xml elements solved the issue, and the onclick is now triggered with the original code.
I've encountered the same issue and tried your fix but couldn't get it to work. What worked for me was adding android:descendantFocusability="blocksDescendants" to the <RelativeLayout> from the item layout xml, list_item.xml in your case. This allows onItemClick() to be called.
What worked for me :
1) Adding android:descendantFocusability="blocksDescendants" to Relative Layout tag.
The result is shown below :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants" >
2) Adding android:focusable="false" to every element in in list_item.xml
example :
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:focusable="false" />
Once I had a similar problem. Every list item had a text view and a checkbox, and just because the checkbox, the whole listitem wasn't 'enabled' to fire the event. I solved it by making a little trick inside the adapter when I was getting the view.
Just before returning the view I put:
v.setOnClickListener(listener);
(The object listener is an onItemClickListener I gave to the Adapter's constructor).
But I have to tell you, the problem is because the platform, it is a bug.
I had the same problem and I tried to solve it by adding
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
to my item.xml but it still doesn't work !!! Infact I found the issue in the relative layout witch contains
android:focusableInTouchMode="true" android:focusable="true"
And when I removed it All things is ok
protected void onPostExecute(Void result) {
progressDialog.dismiss(); stLessons.setAdapter(new LessonListAdapter(Schema.this, R.layout.list_item, lessons));
//add this
ListView lv = getListView(); lv.setOnItemClickListener(new ListView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
//do stuff
}
});
}