button not clickable when gridview added to framelayout - android

I have a framelayout with a a textview at the center and button (in included bar.xml) placed at the bottom. The button works perfectly at run time. However, I later add to it a gridview and make the textview invisible. After this, however, the button seizes to recieve and touch or click events.
Anyone know how to achieve this? Or alternative ways to create the same layout.
When I remove the button from the framelayout, it works perfectly even when the gridview shows up. Here's some of my code.
result.xml
<!-- Frame 1 -->
<FrameLayout
android:id="#+id/result_fragment_container"
android:layout_height="match_parent"
android:layout_width="match_parent">
<TextView
android:id="#+id/result_error"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:gravity="center"
android:visibility="gone"
android:padding="10dp"
android:text="No results found."
android:textColor="#color/theme_support_color"
android:textSize="25sp"
android:layout_gravity="center" />
<include
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:id ="#+id/result_bar"
layout="#layout/bar" />
</FrameLayout>
And bar.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/sl_content"
android:padding="5dp">
<TextView
android:id="#+id/search_location"
android:layout_width="0dp"
android:layout_weight="4"
android:layout_height="#dimen/address_height"
android:gravity="center"
android:textSize="16sp"
android:textColor="#fff"
android:singleLine="true"
android:ellipsize="end"
/>
<!-- Problematic Button -->
<Button
android:id="#+id/button_change_location"
android:layout_width="0dp"
android:layout_height="#dimen/address_change_button_height"
android:text="Change"
android:textSize="12sp"
android:layout_weight="1"
android:textColor="#fff"
/>
</LinearLayout>
Handling Code From MainActivity:
#Override
public void onVolleyDone(JSONObject response) {
//second frame layout
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//send the shop id
ArrayList<ListItem> listItems = new ArrayList<ListItem>();
System.out.println("Volley done counted "+counter);
counter++;
//if it returned any items
if(!response.isNull("item_0")){
//check if the error view is visible
if(errorView.getVisibility()==View.VISIBLE)
errorView.setVisibility(View.GONE);
for (int i = 0; i < response.length(); i++){
try {
JSONObject jObject = response.getJSONObject("item_"+i);
String iName = jObject.getString("item_name");
String iImage = jObject.getString("primary_image");
int iId = Integer.valueOf(jObject.getString("id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
itemsFragment.setListItems(listItems);
fragmentTransaction.add(R.id.result_fragment_container, itemsFragment);
fragmentTransaction.commit();
}else{
errorView.setVisibility(View.VISIBLE);
}
}
ItemsListFragment referenced above:
public class ItemsListFragment extends Fragment implements OnItemClickListener, OnItemLongClickListener{
//variables
private ItemsListAdapter adapter;
private ArrayList<ListItem> listItems;
private GridView gridView;
private ArrayList<ListItem> tempShopItems;
private OnListItemClickListener callBack;
public static final int GRID_NUM_COLUMNS = 2;
private static final String TAG = ItemsListFragment.class.getSimpleName();
public static final int LONG_CLICK = 2;
public static final int SHORT_CLICK = 3;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.items_list_fragment, container,false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
//initialize other variables
initVariables();
//get items to display
updateItems();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
callBack = (OnListItemClickListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnListItemClickListener");
}
}
private void initVariables(){
//shop items
listItems = new ArrayList<ListItem>();
//grid view
gridView = (GridView) getActivity().findViewById(R.id.gridView);
gridView.setOnItemLongClickListener(this);
gridView.setNumColumns(GRID_NUM_COLUMNS);
//adapter
adapter = new ItemsListAdapter(getActivity().getApplicationContext(),listItems);
//set onitemclick listener
gridView.setOnItemClickListener(this);
//set adapter
gridView.setAdapter(adapter);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
if(parent.getItemAtPosition(position) instanceof Item){
//start another activity
}else
callBack.onListItemClick(parent, view, position, id,SHORT_CLICK);
}
public void setListItems(ArrayList<ListItem> items){
tempShopItems = items;
System.out.println("Temp items after= "+tempShopItems.toString());
}
public void updateItems(){
listItems.addAll(0, tempShopItems);
adapter.notifyDataSetChanged();
}
public void removeFromList(int index){
listItems.remove(index);
adapter.notifyDataSetChanged();
}
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
callBack.onListItemClick(parent, view, position, id, LONG_CLICK);
return true;
}
public interface OnListItemClickListener{
public void onListItemClick(AdapterView<?> parent, View view, int position,long id, int type);
}
}

Related

Drawable is not printed correctly in a listview

I want to create a listview that displays the same clickable icon several times. I tried many ways, including a custom adapter with layout inflater but failed... At this point my ListView displays numbers instead of the icon. Can you help me please? here is my code
public class UserSelectionActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
static ArrayList<Integer> arrayOfIcons = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_selection);
arrayOfIcons.clear();
for (int i=0; i<3; i++) {arrayOfIcons.add(R.drawable.edit);}
ArrayAdapter<Integer> adapter2 = new ArrayAdapter<Integer>(this, android.R.layout.simple_list_item_1, arrayOfIcons);
ListView listView2 = (ListView) findViewById(R.id.usersListView2);
listView2.setAdapter(adapter2);
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//TODO
}
});
}
}
I don't do anything in onResume method, that's why I didn't share it
And my xml file :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/usersListView2"
android:layout_width="80dp"
android:layout_height="450dp"
android:layout_alignParentEnd="true"
android:paddingTop="4dip"
android:paddingBottom="3dip" />
</RelativeLayout>
Hy, I suggest you to create a custom adapter:
1) create your list_item:
In res -> layout create a new file named list_item.xml. It contains only one imageView inserted into a ConstraintLayout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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">
<ImageView
android:id="#+id/imageViewIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
app:srcCompat="#mipmap/ic_launcher" />
2) In your activity_main.xml you have to inser your listView:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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"
tools:context=".MainActivity">
<ListView
android:id="#+id/listViewIcon"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
3) Now you have to create a new class call, for example, IconAdapter, where you create your custom adapter:
public class IconAdapter extends BaseAdapter {
Context context;
List<Integer> iconIDList;
/**
*
* #param context = activity context
* #param iconIDList = list with icon's id
*/
public IconAdapter(Context context, List<Integer> iconIDList) {
this.context = context;
this.iconIDList = iconIDList;
}
#Override
public int getCount() {
//return the size of my list
return iconIDList.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
//inflate my view
if (convertView == null) {
LayoutInflater inflater;
inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.list_item, null);
}
//istantiate my imageView
ImageView imageView = convertView.findViewById(R.id.imageViewIcon);
//set imageView's icon
imageView.setImageResource(iconIDList.get(i));
//return my view
return convertView;
}
}
4) Now in your MainActivity, put all together:D
public class MainActivity extends AppCompatActivity {
List<Integer> iconIDList;
IconAdapter iconAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//istantiate my components
iconIDList = new ArrayList<>();
listView = findViewById(R.id.listViewIcon);
iconAdapter = new IconAdapter(this, iconIDList);
int myIcon = R.drawable.ic_launcher_background;
//populate the list with icon's id
for (int i = 0; i < 5; i++) {
iconIDList.add(myIcon);
}
//set my custom adapter to the listView
listView.setAdapter(iconAdapter);
//set clickListner to the elements of my listView
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//i is the index of the clicked element
Toast.makeText(MainActivity.this, "Click on element n. " + i, Toast.LENGTH_SHORT).show();
}
});
}
}
I hope that can help you!!! Good job!! If you have a question, comment my answer!!
In your comment you ask me how to add one listener for the name (textView) clicked and one for the icon clicked.
1) modify your list_item.xml file. Now we can use:
a LinearLayout instead of ConstraintLayout;
a textView;
a ImageButton instead of ImageView.
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:descendantFocusability="blocksDescendants" > <!--this is very important to detect click-->
<TextView
android:id="#+id/textViewIcon"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:gravity="left|center"
android:text="TextView"
android:textSize="24sp" />
<ImageButton
android:id="#+id/imageButtonIcon"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:layout_weight="1"
app:srcCompat="#mipmap/ic_launcher" />
</LinearLayout>
2) Is better if you create a class that contains your data. We can call this class IconData:
public class IconData {
int iconID;
String text;
//constructor
public IconData(int iconID, String text) {
this.iconID = iconID;
this.text = text;
}
//getter and setter
public int getIconID() {
return iconID;
}
public void setIconID(int iconID) {
this.iconID = iconID;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
3) Now we have to change our IconAdapter.
We'll add an Interface to detect clicks on the ImageButton;
We'll change the list's data type;
We'll instatiate the newest TextView and ImageButton:
//create custom adapter -> I extend my class using BaseAdapter
public class IconAdapter extends BaseAdapter {
//create an interface to comunicate the clicks on the imageButton
public interface MyIconAdapterInterface {
void setOnClickListnerMyImageButton (int position);
}
Context context;
//change the list's name and data type
List<IconData> iconIDTextList;
MyIconAdapterInterface myIconAdapterInterface;
/**
* #param context = activity context
* #param iconIDTextList = list with icon's id and text
* #param myIconAdapterInterface = the interface that mainActivity will implements
*/
public IconAdapter(Context context, List<IconData> iconIDTextList, MyIconAdapterInterface myIconAdapterInterface) {
this.context = context;
this.iconIDTextList = iconIDTextList;
this.myIconAdapterInterface = myIconAdapterInterface;
}
#Override
public int getCount() {
//return the size of my list
return iconIDTextList.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
//inflate my view
if (convertView == null) {
LayoutInflater inflater;
inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.list_item, null);
}
//istantiate my imageView and textView
ImageButton imageButton = convertView.findViewById(R.id.imageButtonIcon);
TextView textView = convertView.findViewById(R.id.textViewIcon);
//set imageView's button
int image = iconIDTextList.get(i).getIconID();
imageButton.setImageResource(image);
//set text
String text = iconIDTextList.get(i).getText();
textView.setText(text);
//setOnclickListner on my imageButton
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//pass the position of my clicks to the myIconAdapterInterface
myIconAdapterInterface.setOnClickListnerMyImageButton(i);
}
});
return convertView;
}
}
4) Finally we have to change the MainActivity.java's code:
implement our class with the new interface that we have create in our IconAdapter;
modify our list data type;
pass the newest list and the interface to the IconAdapter;
implement the interface's methods.
//I implement my MainActivity with IconAdapter.MyIconAdapterInterface. I create this interface
//in the iconAdapter class
public class MainActivity extends AppCompatActivity implements IconAdapter.MyIconAdapterInterface {
//change to iconIDTextList and change List data type
List<IconData> iconIDTextList;
IconAdapter iconAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//istantiate my components
iconIDTextList = new ArrayList<>();
listView = findViewById(R.id.listViewIcon);
//the second "this" is refer to the IconAdapter.MyIconAdapterInterface
iconAdapter = new IconAdapter(this, iconIDTextList, this);
int myIcon = R.drawable.ic_launcher_background;
String myText = "Hello! ";
//populate the list with icon's id and text
for (int i = 0; i < 5; i++) {
iconIDTextList.add(new IconData(myIcon, myText + i));
}
//set my custom adapter to the listView
listView.setAdapter(iconAdapter);
//set clickListner to the elements of my listView
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//i is the index of the clicked element
Toast.makeText(MainActivity.this, "Click on element n. " + i, Toast.LENGTH_SHORT).show();
}
});
}
//this is IconAdapter.MyIconAdapterInterface's method that I have to implement
#Override
public void setOnClickListnerMyImageButton(int position) {
//position = click's position
Toast.makeText(this, "Click on image n. "
+ position, Toast.LENGTH_SHORT).show();
}
}
Good Job!!

Android smoothScrollToPosition on GridView with ArrayAdapter not working at all

I am trying to scroll to the selected position after screen rotation but nothing is happening.
I have tried many suggestions, but none is working (setSelection, own smooth scroll...)
public class MovieFragment extends Fragment {
// The customised movie adapter
private MovieAdapter mMovieAdapter;
private GridView mGridView;
private static final String SELECTED_POSTER = "stored_position";
private int mPosition = GridView.INVALID_POSITION;
public interface Callback {
/**
* DetailFragmentCallback for when an item has been selected.
*/
void onItemSelectedNormal (Movie movie);
}
public MovieFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
/**
* Function that makes an Async call for the fetch function while passing the sort criteria from the shared preferences.
*/
public void updateMovies (String sortCriteria) {
FetchMoviesTask fmt = new FetchMoviesTask(getActivity(), mMovieAdapter);
fmt.execute(sortCriteria);
}
#Override
public void onStart() {
super.onStart();
}
public void onSortChange () {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String sortCriteria = prefs.getString(getString(R.string.pref_criteria_key), getString(R.string.pref_criteria_default));
updateMovies(sortCriteria);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMovieAdapter = new MovieAdapter(getActivity(), new ArrayList<Movie>());
View rootView = inflater.inflate(R.layout.fragment_movie, container, false);
mGridView = (GridView) rootView.findViewById(R.id.gridview_movie);
mGridView.setAdapter(mMovieAdapter);
// Handle a click on a poster.
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Movie movie = mMovieAdapter.getItem(i); // Get the movie object at the appropriate position.
((Callback) getActivity()).onItemSelectedNormal(movie);
mPosition = i;
}
});
if (savedInstanceState != null && savedInstanceState.containsKey(SELECTED_POSTER)) {
mPosition = savedInstanceState.getInt(SELECTED_POSTER);
}
//onSortChange();
return rootView;
}
#Override
public void onSaveInstanceState(Bundle outState) {
if (mPosition != GridView.INVALID_POSITION){
outState.putInt(SELECTED_POSTER, mPosition);
}
super.onSaveInstanceState(outState);
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (mPosition != GridView.INVALID_POSITION) {
mGridView.smoothScrollToPosition(mPosition);
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
onSortChange();
}
}
Here is my adapter:
public class MovieAdapter extends ArrayAdapter<Movie> {
private static final String LOG_TAG = MovieAdapter.class.getSimpleName();
public MovieAdapter(Activity context, ArrayList<Movie> movies) {
super(context, 0, movies);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Gets the Movie object from the ArrayAdapter at the appropriate position
Movie movie = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.movie_poster, parent, false);
}
ImageView imageView = (ImageView) convertView.findViewById(R.id.poster_view);
Picasso.with(convertView.getContext()).load(movie.getImageURL()).into(imageView);
return convertView;
}
}
My fragment layout:
<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">
<!-- TODO: Update blank fragment layout -->
<GridView
android:id="#+id/gridview_movie"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:numColumns="auto_fit"
style="#style/MovieGridStyle"
android:stretchMode="columnWidth" />
<TextView
android:id="#+id/no_data_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/empty_fav_list"
android:visibility="invisible"
android:gravity="center"
android:textColor="#bfafaf"
android:textSize="25sp" />
</RelativeLayout>
My images layout, named movie_poster:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10sp"
android:background="#drawable/touch_selector">
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:id="#+id/poster_view"
android:adjustViewBounds="true"/>
</FrameLayout>

Infinite Scrolling of items created in two Linear Layout in Android

I divide my screen in two parts, one of the parts contain five buttons and another part contain seven ImageView with images. Now I want that ImageView rotate infinite,means, after last image, again images start to come. My XML is
<LinearLayout 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:orientation="horizontal"
android:baselineAligned="true"
tools:context="in.example.splitapp.MainActivity" >
<ScrollView
android:id="#+id/scrollView"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
>
<RelativeLayout
android:id="#+id/linearLayout1"
android:orientation="vertical"
android:layout_weight="1"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#android:color/holo_green_dark">
<Button android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:text="DOG"/>
<Button android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/button1"
android:text="CAT"/>
<Button android:id="#+id/button3"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/button2"
android:text="COW"/>
<Button android:id="#+id/button4"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/button3"
android:text="RAT"/>
<Button android:id="#+id/button5"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/button4"
android:text="PARROT"/>
</RelativeLayout>
</ScrollView>
<ScrollView
android:id="#+id/scrollView2"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
>
<RelativeLayout
android:id="#+id/linearLayout2"
android:orientation="horizontal"
android:layout_weight="1"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#android:color/holo_purple"
>
<ImageView android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:background="#drawable/dog"
android:text="DOG"/>
<ImageView android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView1"
android:background="#drawable/cat"
android:text="CAT"/>
<ImageView android:id="#+id/imageView3"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView2"
android:background="#drawable/cow"
android:text="COW"/>
<ImageView android:id="#+id/imageView4"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView3"
android:background="#drawable/rat"
android:text="RAT"/>
<ImageView android:id="#+id/imageView5"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView4"
android:background="#drawable/parrot"
android:text="PARROT"/>
<ImageView android:id="#+id/imageView6"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView5"
android:background="#drawable/horse"
android:text="HORSE"/>
<ImageView android:id="#+id/imageView7"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView6"
android:background="#drawable/fish"
android:text="FISH"/>
</RelativeLayout>
</ScrollView>
</LinearLayout>
I want that ImageView side scrolling infinite means these five images repeated always.
This is my MainActivity:
public class MainActivity extends Activity implements OnScrollListener {
List<String> animalNameList = new ArrayList<String>();
ArrayList<Integer> animalImageList = new ArrayList<Integer>();
ImageAdapter imageAdapter;
NameAdapter nameAdapter = null;;
boolean flag = false;
ListView listView;
ListView listView1;
ListView upperListView;
RelativeLayout parentLayout;
LinearLayout childLayout;
int index = 0;
UpdateAdapter updateAdapter = null;
ArrayList<DataSplit> array = new ArrayList<DataSplit>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
animalNameList.add("CAT");
animalNameList.add("DOG");
animalNameList.add("COW");
animalNameList.add("RAT");
animalNameList.add("PARROT");
animalNameList.add("HORSE");
animalNameList.add("FISH");
animalImageList.add(R.drawable.horse);
animalImageList.add(R.drawable.parrot);
animalImageList.add(R.drawable.fish);
animalImageList.add(R.drawable.rat);
animalImageList.add(R.drawable.dog);
animalImageList.add(R.drawable.cat);
animalImageList.add(R.drawable.cow);
parentLayout = (RelativeLayout)findViewById(R.id.parentRelative);
childLayout = (LinearLayout)findViewById(R.id.childLinearLayout);
nameAdapter = new NameAdapter(MainActivity.this,
-1, animalNameList);
listView = (ListView)findViewById(R.id.listView1);
listView.setAdapter(nameAdapter);
imageAdapter = new ImageAdapter(MainActivity.this, -1, animalImageList);
listView1 = (ListView)findViewById(R.id.listView2);
CircularListAdapter circularAdapter = new CircularListAdapter(imageAdapter);
listView1.setDivider(null);
listView1.setAdapter(circularAdapter);
listView1.setOnScrollListener(this);
upperListView = (ListView)findViewById(R.id.upperListView);
listView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if(flag)
{
}
}
});
}
class NameAdapter extends BaseAdapter {
private List<String> animalName;
private Activity context;
public NameAdapter(Activity context, int textViewResourceId,
List<String> animalName) {
super();
this.animalName = animalName;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater=context.getLayoutInflater();
convertView = inflater.inflate(R.layout.animalname, parent, false);
Button button=(Button)convertView.findViewById(R.id.button);
button.setId(position);
button.setText(animalName.get(position));
}
return convertView;
}
public int getCount()
{
int size = animalName.size();
return size;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
class ImageAdapter extends ArrayAdapter<Integer> {
private ArrayList<Integer> animalImage;
private Activity context;
public ImageAdapter(Activity context, int textViewResourceId,
ArrayList<Integer> animalImage) {
super(context, textViewResourceId);
this.animalImage = animalImage;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
view = new View(MainActivity.this);
}
view.setId(position);
//view.setBackgroundResource(animalImage[position]);
view.setBackgroundResource(animalImage.get(position));
return view;
}
public int getCount()
{
int size = animalImage.size();
return size;
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int childInt = view.getChildAt(0).getId();
//String img1Text = this.getResources().getResourceEntryName(animalImage[childInt]);
String img1Text = this.getResources().getResourceEntryName(animalImageList.get(childInt));
//String buttonText = animalName[index];
String buttonText = animalNameList.get(index);
if(img1Text.equalsIgnoreCase(buttonText))
{
final String name = animalNameList.get(index);
int image = animalImageList.get(childInt);
DataSplit data = new DataSplit();
data.setAnimalName(name);
data.setAnimalImage(image);
array.add(data);
index++;
flag = true;
if(array.size() == 1)
{
updateAdapter = new UpdateAdapter(MainActivity.this,-1,array);
upperListView.setAdapter(updateAdapter);
upperListView.setVisibility(View.VISIBLE);
}
else
{
updateAdapter.notifyDataSetChanged();
}
listView.post(new Runnable() {
#Override
public void run() {
animalNameList.remove(name);
nameAdapter.notifyDataSetChanged();
}
});
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
class UpdateAdapter extends ArrayAdapter<Integer> {
ArrayList<DataSplit> dataSplit;
private Activity context;
public UpdateAdapter(Activity context, int textViewResourceId,
ArrayList<DataSplit> dataSplit) {
super(context, textViewResourceId);
this.dataSplit = dataSplit;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater=context.getLayoutInflater();
convertView = inflater.inflate(R.layout.addeddata, parent, false);
Button button=(Button)convertView.findViewById(R.id.button);
ImageView imageView=(ImageView)convertView.findViewById(R.id.imageView);
String animalName = dataSplit.get(position).getAnimalName();
int imageName = dataSplit.get(position).getAnimalImage();
button.setText(dataSplit.get(position).getAnimalName());
imageView.setBackgroundResource(dataSplit.get(position).getAnimalImage());
}
return convertView;
}
public int getCount()
{
int size = dataSplit.size();
return size;
}
}
}
I created activity_main.xml which contains a parent RelativeLayout and under this a ListView named upperListView and initially set visibility gone. Below this I created a LinearLayout and for this I created two ListView for Name DataSet and Image DataSet. When data matches I create a UpdateAdapter in which I use addeddata.xml, in which a button and ImageView created and when it is a successful match then hidden list view visibility becomes Visible and this "addeddata.xml" loaded in listview. This I perform. It will work perfectly.But when first matches,i.e, CAT name match with the Cat image, data is not deleted from both of listview and CAT name again shown in below the new ListView.
How to manage to complete matches if the application crashes.
This has been discussed in the past, with using circular Listviews:
How to create a closed (circular) ListView?
Closed or circular Horizontal ListView Android
I just want when I scroll ImageView part then if Dog image matches with the right end side Dog name then image stick with the Dog Name Button and rest of the images remain scrolling.
For this here is what you could try:
after scrolling items in list1 and list2, iterate over each item in the shortest listview and check if item1(position) [tag] = item2(position) [tag] (so, if you have a match)
if true:
redraw screen like this: add a new listview at the bottom of the screen (below both listviews). This listview with contain both item1 and item2 (so it's litviewitem xml will be a linear layout with other two linear layouts, one containing the matched pet name and the other the matched pet picture)
remove item1(position) and item2(position) from listview1, listview2 (which means you have to remove, for example, dog name from listview pet names datasource, and dog image from listview pet pictures datasource and reset adapters to listviews)
this way you will continue to be able to scroll and match items from listview1 and listview2 - without the already matching items-, and also have a bottom listview with all the matching elements that cannot be matched any more
Hope this helps!
After spend couple of days I found the perfect solution for my question. I dynamically created the ImageView and also the ListView. Image data are populating in the ListView. After matching the text with right Image, I take that ImageView from the List and set in dynamically created ImageView. Following is my code.
public class MainActivity extends Activity implements OnScrollChangedListener, OnScrollListener{
int index = 0;
ImageView imageView1;
List<Integer> spectrum = new ArrayList<Integer>();
String[] animalName;
ImageView[] imageArray;
Button[] buttonArray;
ListView listView;
SpectrumAdapter spectrumAdapter;
ListView animalImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
animalName = new String[]{"CAT","DOG","COW","RAT","PARROT","HORSE","FISH"};
imageArray = new ImageView[animalName.length];
buttonArray = new Button[animalName.length];
LinearLayout inner1 = (LinearLayout)findViewById(R.id.innerLayout1);
LinearLayout inner2 = (LinearLayout)findViewById(R.id.innerLayout2);
ListView animalList = (ListView)findViewById(R.id.animalList);
NameAdapter nameAdapter = new NameAdapter(MainActivity.this,
-1, animalName);
animalList.setAdapter(nameAdapter);
for(int i=0;i<animalName.length;i++)
{
ImageView imageView = new ImageView(this);
imageView.setId(i);
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,150);
imageView.setTag(i);
imageView.setLayoutParams(params1);
imageView.setVisibility(View.GONE);
imageArray[i] = imageView;
inner1.addView(imageView);
}
ListView listView = new ListView(this);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
listView.setLayoutParams(param);
inner2.addView(listView);
spectrum.add(R.drawable.horse);
spectrum.add(R.drawable.rat);
spectrum.add(R.drawable.cow);
spectrum.add(R.drawable.dog);
spectrum.add(R.drawable.fish);
spectrum.add(R.drawable.parrot);
spectrum.add(R.drawable.cat);
spectrumAdapter = new SpectrumAdapter(MainActivity.this,
-1, spectrum);
CircularListAdapter circularAdapter = new CircularListAdapter(spectrumAdapter);
listView.setAdapter(circularAdapter);
listView.setOnScrollListener(this);
}
class NameAdapter extends BaseAdapter {
private String[] animalName;
private Activity context;
public NameAdapter(Activity context, int textViewResourceId,
String[] animalName) {
super();
this.animalName = animalName;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater=context.getLayoutInflater();
convertView = inflater.inflate(R.layout.animalname, parent, false);
}
Button button=(Button)convertView.findViewById(R.id.button);
button.setText(animalName[position]);
return convertView;
}
public int getCount()
{
int size = animalName.length;
return size;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
class SpectrumAdapter extends ArrayAdapter<Integer> {
private List<Integer> spectrum;
public SpectrumAdapter(Context context, int textViewResourceId,
List<Integer> spectrum) {
super(context, textViewResourceId, spectrum);
this.spectrum = spectrum;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
view = new View(MainActivity.this);
}
view.setId(position);
view.setBackgroundResource(spectrum.get(position));
return view;
}
public int getCount()
{
int size = spectrum.size();
return size;
}
}
#Override
public void onScrollChanged() {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
int childInt = view.getChildAt(0).getId();
String img1Text = this.getResources().getResourceEntryName(spectrum.get(childInt));
String bb = animalName[index];
if(bb.equalsIgnoreCase(img1Text))
{
ImageView img = imageArray[index];
img.setBackgroundResource(spectrum.get(childInt));
img.setVisibility(View.VISIBLE);
index++;
}
else
{
}
}
}
This is the perfect solution for the question. Thanks all for the suggestion.

ViewPagers and PagerAdapters

I am new to Android and am trying a sample application for showing ViewPagers in a Master-Detail Flow using custom PagerAdapters and FragmentStatePagerAdapters. My application has a list of dummy items managed by a SQLiteDatabase which contain a title String, a description String, a Boolean like status, and a list of images (I plan to implement them as downloading from String urls but presently I'm just trying with a single image resource). I am having two problems in the Detail View.
My intention is to use a ViewPager with a FragmentStatePagerAdapter to show the detail view, which consists of a ViewPager with a custom PagerAdapter for showing the list of images, TextView for title and description, a ToggleButton for the like status and a delete button for deleting items from the list.
Issues:
The ViewPager with the custom PagerAdapter does not display the image. It occupies the expected space and swipes performed on it also behave as expected. Only the image is not visible.
[RESOLVED] On using the delete button, I am able to delete the item from the database, and also update the Master View accordingly, but I am not able to update the Detail View, and the app crashes.
Here is my code:
Code that calls ItemDetailActivity.java
#Override
public void onClick(View v) {
Intent detailIntent = new Intent(getContext(), ItemDetailActivity.class);
detailIntent.putExtra(ItemDetailFragment.ARG_LIST_POSITION, holder.position);
getContext().startActivity(detailIntent);
}
ItemDetailActivity.java
public class ItemDetailActivity extends FragmentActivity {
static ItemDetailPagerAdapter idpa;
static ViewPager detailPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_detail);
idpa = new ItemDetailPagerAdapter(getSupportFragmentManager());
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
detailPager = (ViewPager) findViewById(R.id.item_detail_container);
detailPager.setAdapter(idpa);
detailPager.setCurrentItem(getIntent().getIntExtra(ItemDetailFragment.ARG_LIST_POSITION, 0));
}
}
activity_item_detail.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/item_detail_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.trial.piclist.ItemDetailActivity"
tools:ignore="MergeRootFrame" />
ItemDetailFragment.java
public class ItemDetailFragment extends Fragment {
public static final String ARG_ITEM_ID = "item_id";
public static final String ARG_LIST_POSITION = "list_index";
public static final String ARG_TWO_PANE = "is_two_pane";
int position = -1;
long id = -1;
boolean twoPane = false;
ViewPager pager;
private PicItem mItem;
public ItemDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
twoPane = getArguments().getBoolean(ARG_TWO_PANE, false);
position = getArguments().getInt(ARG_LIST_POSITION, -1);
id = getArguments().getLong(ARG_ITEM_ID, -1);
if (id == -1)
id = ItemListFragment.getIdByPosition(position);
setmItem(id);
}
public void setmItem(long id) {
if (id >= 0) {
try {
ItemListActivity.lds.open();
mItem = ItemListActivity.lds.getById(id);
ItemListActivity.lds.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
if (mItem != null) {
List<String> pics = new ArrayList<String>();
pics.add("1");
pics.add("2");
pics.add("3");
pics.add("4");
pics.add("5");
mItem.setPics(pics);
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item_detail,
container, false);
DetailViewHolder holder = new DetailViewHolder();
pager = (ViewPager) rootView.findViewById(R.id.pager);
ImagePagerAdapter adapter = new ImagePagerAdapter(mItem, getActivity(),
inflater, position);
pager.setAdapter(adapter);
holder.position = getArguments().getInt(ARG_LIST_POSITION);
holder.ttv = (TextView) rootView.findViewById(R.id.item_title);
holder.dtv = (TextView) rootView.findViewById(R.id.item_detail);
holder.likeButton = (ToggleButton) rootView
.findViewById(R.id.item_like);
holder.deleteButton = (Button) rootView.findViewById(R.id.item_delete);
rootView.setTag(holder);
if (mItem != null) {
holder.ttv.setText(mItem.getTitle());
holder.dtv.setText(mItem.getDescription());
holder.likeButton.setChecked(mItem.getIsLiked());
holder.likeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ItemListActivity.lds.open();
ItemListActivity.lds.toggleLike(mItem.getId());
mItem.toggleIsLiked();
ItemListActivity.lds.close();
ItemListFragment.listDisplayHelper.toggleLiked(position);
}
});
holder.deleteButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ItemListActivity.lds.open();
ItemListActivity.lds.removeItem(mItem.getId());
ItemListActivity.lds.close();
ItemListFragment.listDisplayHelper.remove(position);
ItemListActivity.idpa.notifyDataSetChanged();
// What do I do so that the FragmentStatePagerAdapter is
// updated and the viewpager shows the next item.
}
});
}
return rootView;
}
static private class DetailViewHolder {
TextView ttv;
TextView dtv;
ToggleButton likeButton;
Button deleteButton;
int position;
}
}
fragment_item_detail.xml
<LinearLayout 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:orientation="vertical"
android:padding="16dp"
tools:context="com.trial.piclist.ItemDetailFragment" >
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="200dip">
</android.support.v4.view.ViewPager>
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/item_title"
style="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello"
android:textIsSelectable="true" />
<Space
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1" />
<include
android:layout_width="wrap_content"
android:layout_height="wrap_content"
layout="#layout/controls_layout" />
</TableRow>
<ScrollView
android:id="#+id/descScrollView"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/item_detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello" />
</LinearLayout>
</ScrollView>
</LinearLayout>
controls_layout.xml
<?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="horizontal" >
<ToggleButton
android:id="#+id/item_like"
android:layout_width="30dip"
android:layout_height="30dip"
android:layout_gravity="right"
android:background="#android:drawable/btn_star"
android:gravity="center"
android:text="#string/like_list_item"
android:textOff="#string/empty_text"
android:textOn="#string/empty_text" />
<Button
android:id="#+id/item_delete"
style="?android:attr/buttonStyleSmall"
android:layout_width="30dip"
android:layout_height="30dip"
android:background="#android:drawable/ic_menu_delete"
android:text="#string/empty_text" />
</LinearLayout>
Custom PagerAdapter
ImagePagerAdapter.java
public class ImagePagerAdapter extends PagerAdapter {
LayoutInflater inflater;
List<View> layouts = new ArrayList<>(5);
// Constructors.
#Override
public Object instantiateItem(ViewGroup container, int position) {
if (layouts.get(position) != null) {
return layouts.get(position);
}
View layout = inflater.inflate(R.layout.detail_image,
((ViewPager) container), true);
try {
ImageView loadSpace = (ImageView) layout
.findViewById(R.id.detail_image_view);
loadSpace.setBackgroundColor(0x000000);
loadSpace.setImageResource(R.drawable.light_grey_background);
loadSpace.setAdjustViewBounds(true);
} catch (Exception e) {
System.out.println(e.getMessage());
}
layout.setTag(images.get(position));
layouts.set(position, layout);
return layout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (((View) object).findViewById((view.getId())) != null);
}
}
FragmentPagerAdapter
ItemDetailPagerAdapter.java
public class ItemDetailPagerAdapter extends FragmentStatePagerAdapter {
public ItemDetailPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new ItemDetailFragment();
Bundle args = new Bundle();
args.putLong(ItemDetailFragment.ARG_ITEM_ID, ItemListFragment.getIdByPosition(position));
args.putInt(ItemDetailFragment.ARG_LIST_POSITION, position);
args.putBoolean(ItemDetailFragment.ARG_TWO_PANE, ItemListActivity.mTwoPane);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
openDatabase();
int c = database.getCount();
closeDatabase();
return c;
}
#Override
public int getItemPosition(Object object) {
long mId = ((ItemDetailFragment) object).getmId();
int pos = POSITION_NONE;
openDatabase();
if (database.contains(mId)) {
pos = database.getPositionById(mId);
}
closeDatabase();
return pos;
}
}
Any help is much appreciated. Thanks :)
In your ItemDetailFragment, remove the viewpager from the holder, it should be directly into the returned view, something like this:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item_detail,
container, false);
pager = (ViewPager) rootView.findViewById(R.id.pager);
ImagePagerAdapter adapter = new ImagePagerAdapter(mItem, getActivity(),inflater, position);
pager.setAdapter(adapter);
return rootView;
}
and the ViewHolder pattern should be applied inside your PagerAdapter.
In ImagePagerAdapter.java, correct the isViewFromObject method -
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == (View) object);
}
This will correct the issue of the ImageView.
In ItemDetailPagerAdapter.java, override the getItemPosition method -
#Override
public int getItemPosition(Object object) {
int ret = POSITION_NONE;
long id = ((ItemDetailFragment) object).getId();
openDatabase();
if (databaseContains(id)) {
ret = positionInDatabase(id);
}
closeDatabase();
return ret;
}
On deleting call the FragmentStatePagerAdapter.NotifyDataSetChanged() method. This will make the Adapter update itself on deleting.
Although, the FragmentStatePagerAdapter uses a list of Fragments and of stored states to implement the adapter. That is also causing trouble. To remove that, implement your own list of Fragments.

Failing to populate a ListView with an AsyncTask

Trying to get this working... it loads up fine, even tells the application that it completed getting all the data. It does not populate the listview though.
The data response inside mArrayList.toString(): [A, B, C, D]
public class MainActivity extends ActionBarActivity {
private static final String DEBUG_TAG = "MainActivity";
private boolean mAlternateTitle = false;
ListView lv;
private ArrayList<Show> mArrayList;
ShowsAdapter adapter;
AlertDialog mAlertDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mArrayList = new ArrayList<Show>();
lv = (ListView) findViewById(R.id.list);
adapter = new ShowsAdapter(MainActivity.this, android.R.layout.simple_list_item_1, mArrayList);
ShowsList show_list = new ShowsList();
show_list.execute();
lv.setAdapter(adapter);
lv.setOnItemClickListener(new ListClickListener());
}
private class ShowsList extends AsyncTask<Void, Void, List<Show>> {
#Override
protected void onPreExecute() {
mAlertDialog = new AlertDialog.Builder(MainActivity.this).setIcon(R.drawable.ic_action_refresh).setTitle(R.string.fetching_new).show();
}
#Override
protected List<Show> doInBackground(Void... voids) {
final String DEBUG_TAG = "MainActivity$ShowList$doInBackground";
try {
for (Show show : Show.getShows()) {
Log.d(DEBUG_TAG, show.toString());
mArrayList.add(show);
};
return mArrayList;
} catch (Exception e) {
new AlertDialog.Builder(MainActivity.this.getApplicationContext()).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.server_down_title).setMessage(R.string.server_down_message).setPositiveButton(R.string.app_quit, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.this.finish();
}
}).show();
return null;
}
}
#Override
protected void onPostExecute(final List<Show> show_list) {
if (mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
adapter.notifyDataSetChanged();
}
}
private class ListClickListener implements AdapterView.OnItemClickListener {
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Show show = mArrayList.get(i);
Toast.makeText(MainActivity.this, "Clicked on a list item: " + show.title, Toast.LENGTH_LONG).show();
}
}
private class ShowsAdapter extends ArrayAdapter<Show> {
final String DEBUG_TAG = "MainActivity$ShowsAdapter";
public ShowsAdapter(Context context, int textViewResourceId, List<Show> shows) {
super(context, textViewResourceId, shows);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Show show = this.getItem(position);
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_row_show, parent, false);
}
((TextView) convertView.findViewById(R.id.show_title)).setText(show.title);
//Log.d(DEBUG_TAG, (String)((TextView) convertView.findViewById(R.id.show_title)).getText());
//((TextView) convertView.findViewById(R.id.episode_number)).setText(episode.getGrayLine());
return convertView;
}
}
Just in case it could be an issue with the layout [main.xml]:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
</FrameLayout>
list_show_row.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">
<TextView
android:textSize="17.0dip"
android:textStyle="bold"
android:textColor="#ff000000"
android:gravity="center_vertical"
android:id="#+id/show_title"
android:layout_width="fill_parent"
android:layout_height="0.0dip"
android:text="Show Title"
android:layout_weight="1.0"
/>
<TextView
android:textStyle="italic" android:textColor="#ff666666"
android:id="#+id/episode_number"
android:layout_width="fill_parent" android:layout_height="0.0dip" android:text="Episode Number" android:layout_weight="1.0" />
</LinearLayout>
Don't set fill_parent on the layout_height of the root element of list_row_show.xml layout.

Categories

Resources