Fragment and Adapter in Android App Not Displaying Data - java

I'm really new in Android. I have this problem, I have an Activity (MainActivity) and there is a NavigationDrawer, this switches two fragments - ActivitiesFragment and ReportFragments.
The problem is with ActivitiesFragments, data is not displayed.
I have my adapter ready and my layouts ready and the fragment. When I debugg my app, it actually brings data, but is not shown. This is my code:
ActivitiesAdapter
public class ActivitiesAdapter extends ArrayAdapter<Activities>
{
Context mContext;
int mLayoutResourceId;
public ActivitiesAdapter(Context context, int layoutResourceId)
{
super(context, layoutResourceId);
mContext = context;
mLayoutResourceId = layoutResourceId;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
final Activities currentItem = getItem(position);
if (row == null)
{
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(mLayoutResourceId, parent, false);
}
row.setTag(currentItem);
final TextView tituloview = (TextView) row.findViewById(R.id.tituloAct);
tituloview.setText(currentItem.getTitle());
final TextView descrpview = (TextView) row.findViewById(R.id.descrAct);
descrpview.setText(currentItem.getDescription());
return row;
}
}
This is my fragment ActivitiesFragment
public class ActivitiesFragment extends Fragment
{
protected static final String TAG = "ActivitiesFragmment";
private MobileServiceClient mClient;
private MobileServiceTable<Activities> mActivitiesTable;
private ActivitiesAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.act_listfragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
try
{
mClient = new MobileServiceClient("https://site.azure-mobile.net/",
"APPLICATIONKEYAPPLICATIONKEY",
getActivity().getApplicationContext()).withFilter(new ProgressFilter());
mActivitiesTable = mClient.getTable(Activities.class);
}
catch (MalformedURLException e)
{
createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
}
mAdapter = new ActivitiesAdapter(getActivity(), R.layout.act_itemlist);
ListView listViewToDo = (ListView) getView().findViewById(R.id.activities_fragment_list);
listViewToDo.setAdapter(mAdapter);
refreshItemsFromTable();
}
private void createAndShowDialog(Exception exception, String title)
{
createAndShowDialog(exception.toString(), title);
}
private void createAndShowDialog(String message, String title)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity().getApplicationContext());
builder.setMessage(message);
builder.setTitle(title);
builder.create().show();
}
private void refreshItemsFromTable()
{
mActivitiesTable.execute(new TableQueryCallback<Activities>()
{
public void onCompleted(List<Activities> result, int count, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
mAdapter.clear();
for (Activities item : result) {
mAdapter.add(item);
Log.i(TAG, "Titulo: " + item.getTitle());
}
} else {
createAndShowDialog(exception, "Error");
}
}
});
}
}
I don't know whats wrong, but I guess this block is not working on the OnActivityCreated method:
mAdapter = new ActivitiesAdapter(getActivity(), R.layout.act_itemlist);
ListView listViewToDo = (ListView) getView().findViewById(R.id.activities_fragment_list);
listViewToDo.setAdapter(mAdapter);
refreshItemsFromTable();
And here are my Layouts:
This is my frgament's layout:
<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:background="#e1e1e1"
android:orientation="vertical" >
<TextView
android:id="#+id/tvTituloActs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/all_activities"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:textColor="#009ad2"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ListView android:id="#+id/activities_fragment_list"
android:layout_marginTop="8dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:layout_weight="1"
tools:listitem="#layout/act_itemlist"
android:drawSelectorOnTop="false"/>
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No hay datos"/>
</LinearLayout>
This is the layout act_itemlist. The row layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="64dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginLeft="8dp"
android:gravity="center_vertical"
android:src="#drawable/done"
android:layout_gravity="center_vertical"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tvTituloAct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="16dp"
android:textSize="16sp"/>
<TextView
android:id="#+id/tvDescrAct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:text="Description de la actividad" />
</LinearLayout>
</LinearLayout>
I really need help with this! Please if someone can see something that I'm missing please tell me!
Thanks!!!!

Try to swap these lines:
mAdapter = new ActivitiesAdapter(getActivity(), R.layout.act_itemlist);
ListView listViewToDo = (ListView) getView().findViewById(R.id.activities_fragment_list);
refreshItemsFromTable(); // populate first before attaching your adapter
listViewToDo.setAdapter(mAdapter);

I finally solved my problem. Everything was Ok, the only detail was the layout. It was on the fragments layout.
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No hay datos"/>
This textview did not let to show the data so I deleted it and worked.
Thankk you for your help #LazyNinja

Related

Getting a Null Object Reference when trying to set imageview resource with checkbox

So I have an app with a listview. When you click a listview item it opens a new activity. I placed a checkbox in this new activity where when its checked, it should put a checkmark next to the listview item on the previous screen. I'm running into this error I'm guessing because I'm trying to set the checkbox from the second activity that has a different content view than the listview. I hope I explained that well.
Heres my RouteDetails.java with the checkbox code
public class RouteDetails extends AppCompatActivity {
ImageView routeImage;
String routeName;
CheckBox routeCheckBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route_details);
//back button for route details view
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
///////checkbox///////////////////////////////////////////
routeCheckBox = (CheckBox) findViewById(R.id.routeCheckBox);
final ImageView checkImageView = (ImageView) findViewById(R.id.checkImageView);
routeCheckBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
if (routeCheckBox.isChecked())
{
checkImageView.setImageResource(R.drawable.birdsboroicon);
}
}
});
/////////////////////////////////////////////
//sets actionbar title
routeName = getIntent().getExtras().getString("routeName");
getSupportActionBar().setTitle(routeName);
//TextView for route details
final TextView routeDetailsView = (TextView) findViewById(R.id.routeDetailsView);
routeDetailsView.setText(getIntent().getExtras().getCharSequence("route"));
//ImageView for route details
routeImage = (ImageView) findViewById(R.id.routeImage);
final int mImageResource = getIntent().getIntExtra("imageResourceId", 0);
routeImage.setImageResource(mImageResource);
and heres the custom_row.xml that contains the imageview im trying to set based on the checkbox state.
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="51dp"
android:id="#+id/routeText"
android:layout_weight="1"
android:textSize="18sp"
android:gravity="center_vertical"
android:textColor="#android:color/black"
android:typeface="normal"
/>
<ImageView
android:layout_width="35dp"
android:layout_height="35dp"
android:id="#+id/checkImageView" />
So I want the checkmark to be next to the listview item after the back button is pressed.
Ill include this other code if it is relavent
heres my RouteDetails.xml that contains the checkbox
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_route_details"
android:layout_width="match_parent"
android:layout_height="wrap_content"
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="com.example.zach.listview.RouteDetails">
<CheckBox
android:text="Route Climbed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/routeCheckBox"
android:gravity="center" />
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/routeDetailsView"
android:textSize="18sp"
android:textAlignment="center"
android:textColor="#android:color/black"
android:layout_below="#id/routeCheckBox"/>
<ImageView
android:layout_below="#id/routeDetailsView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/routeImage"
android:scaleType="fitCenter"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:adjustViewBounds="true" />
</RelativeLayout>
</ScrollView>
My Custom adapter.java which creates each listview row
class CustomAdapter extends ArrayAdapter<CharSequence>{
public CustomAdapter(Context context, CharSequence[] routes) {
super(context, R.layout.custom_row ,routes);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater routeInflater = LayoutInflater.from(getContext());
View customView = convertView;
if(customView == null){customView = routeInflater.inflate(R.layout.custom_row, parent, false);}
CharSequence singleRoute = getItem(position);
TextView routeText = (TextView) customView.findViewById(R.id.routeText);
routeText.setText(singleRoute);
return customView;
}
my mainavtivity.java which is where the listview is populated
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Action Bar customization
final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayOptions(android.support.v7.app.ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setCustomView(R.layout.actionbar);
setContentView(R.layout.activity_main);
///// fill listview numbers I want to add
final String[] routeListviewNumbers = getResources().getStringArray(R.array.routeNumbers);
//fill list view with xml array of routes
final CharSequence[] routeListViewItems = getResources().getTextArray(R.array.routeList);
//fills route detail text view with xml array info
final CharSequence[] routeDetail= getResources().getTextArray(R.array.routeDetail);
//fills route detail image view with xml array of images
final TypedArray image = getResources().obtainTypedArray(R.array.routeImages);
//image.recycle();
//custom adapter for list view
ListAdapter routeAdapter = new CustomAdapter(this, routeListViewItems);
final ListView routeListView = (ListView) findViewById(R.id.routeListView);
routeListView.setAdapter(routeAdapter);
routeListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CharSequence route = routeListViewItems[position];
int imageId = (int) image.getResourceId(position, -1);
if (route.equals(routeListViewItems[position]))
{
Intent intent = new Intent(view.getContext(), RouteDetails.class);
intent.putExtra("route", routeDetail[position]);
intent.putExtra("imageResourceId", imageId);
intent.putExtra("routeName", routeListViewItems[position]);
startActivity(intent);
}
}
}
);
}
}
and my activitymain.xml which is the listview
<?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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="0dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="0dp"
tools:context="com.example.zach.listview.MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/routeListView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Edit: So I added this to my RouteDetails.java
routeCheckBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
if (routeCheckBox.isChecked())
{
//checkImageView.setImageResource(R.drawable.checkmark);
Intent check = new Intent(RouteDetails.this,CustomAdapter.class);
check.putExtra("checkImageResource", R.drawable.checkmark);
startActivity(check);
}
}
});
and this to my customAdapter.java
////////trying to set checkmark/////
ImageView checkImageView = (ImageView) customView.findViewById(R.id.checkImageView);
checkImageView.setImageResource(((Activity) getContext()).getIntent().getIntExtra("checkImageResource",0));
////////////////////////////////////////
but this is not working either. It says fatal exception unable to find explicit activity class. It's doing this I guess since CustomAdapter is not an activity, but customadapter is linked to my custom_row which contains the imageview I want to add the checkbox to. How would I do this? I'm not sure what else to try
Edit: I still haven't found a solution if anyone has any suggestions!

Custom GridView Adapter not displaying

I'm creating a list of "channels" on an app that users can select. I want them in a grid view, (kind of like clickable tiles). There are supposed to be two separate Grids on this Fragment - default channels (channelListSupplied) and ones that the user will have to request subscriptions to (channelListEarned).
I used a custom adapter that I got from another answer here on SO, but I can't get it to work because it's in a Fragment instead of in the Activity, and I'm sure there's some reference I'm not passing correctly.
Below is a list of the relevant pieces of Java and XML...
FragmentChannels.java: (fragment to MainActivity.java)
public class FragmentChannels extends Fragment implements FragmentManager.OnBackStackChangedListener {
ViewGroup container;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
final JSONObject channelList = data.getJSONObject("channels");
final JSONArray channelListSupplied = channelList.getJSONArray("supplied");
final JSONArray channelListEarned = channelList.getJSONArray("earned");
GridView channelViewSupplied = (GridView) view.findViewById(R.id.channel_grid_supplied);
GridView channelViewEarned = (GridView) view.findViewById(R.id.channel_grid_earned);
if (Session.getSessionVar("canHasSpecial").equals("1")) {
FragmentChannels.this.createGridView(channelViewEarned, channelListEarned, FragmentChannels.this.container);
}
FragmentChannels.this.createGridView(channelViewSupplied, channelListSupplied, FragmentChannels.this.container);
...
return view;
}
public void createGridView(final GridView gridView, JSONArray list, final ViewGroup container) throws JSONException {
final String[] gridList = new String[list.length()];
final Activity activity = getActivity();
for (int i = 0; i < list.length(); i++) {
JSONObject channelData = (JSONObject) list.get(i);
gridList[i] = channelData.getString("source_name");
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
gridView.setAdapter(new GridViewAdapter(activity, gridList, container));
}
});
}
public boolean createChannelMenu(Menu menu) {
MenuInflater inflater = this.getActivity().getMenuInflater();
inflater.inflate(R.menu.menu_channels, menu);
super.onCreateOptionsMenu(menu, inflater);
return true;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
final Activity activity = getActivity();
}
#Override
public void onBackStackChanged() {
}
}
GridViewAdapter.java:
public class GridViewAdapter extends BaseAdapter {
private Context context;
private final String[] textViewValues;
private ViewGroup container;
public GridViewAdapter(Context context, String[] textViewValues, ViewGroup container) {
this.context = context;
this.textViewValues = textViewValues;
this.container = container;
}
#Override
public int getCount() {
return this.textViewValues.length;
}
#Override
public Object getItem(int position) {
return textViewValues[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("CDFF", position+": "+this.textViewValues[position]);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = inflater.inflate(R.layout.grid_item_layout, this.container);
TextView titleView = (TextView) gridView.findViewById(R.id.grid_item_title);
titleView.setText(textViewValues[position]);
}
else {
gridView = convertView;
}
return gridView;
}
}
fragment_channels.xml:
<FrameLayout 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:name="FragmentChannels"
android:id="#+id/fragment_channel_container"
tools:context="xx.xxx.xxxx.FragmentChannels"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:text="My Channels"
android:background="#color/peach"
android:textSize="20sp"
android:textColor="#color/midnightBlue"
android:gravity="center"
android:textAppearance="#style/TextAppearance.FontPath"
/>
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/channel_grid_earned"
android:layout_margin="5dp"
android:columnWidth="180dp"
android:drawSelectorOnTop="true"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="spacingWidthUniform"
android:verticalSpacing="5dp"
android:focusable="true"
android:clickable="true"/>
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/channel_grid_supplied"
android:layout_margin="5dp"
android:columnWidth="180dp"
android:drawSelectorOnTop="true"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="spacingWidthUniform"
android:verticalSpacing="5dp"
android:focusable="true"
android:clickable="true"/>
</LinearLayout>
</FrameLayout>
grid_item_layout.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="#color/white"
android:orientation="vertical"
android:padding="5dp">
<ImageView
android:id="#+id/grid_item_image"
android:layout_width="150dp"
android:layout_height="100dp"
android:scaleType="centerCrop"/>
<TextView
android:id="#+id/grid_item_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:gravity="center"
android:maxLines="2"
android:ellipsize="marquee"
android:textSize="12sp" />
</RelativeLayout>
As of now, nothing displays on the Fragment except the "My Channels" TextView.
I greatly appreciate any help!
Fixed.
I changed the line:
gridView = inflater.inflate(R.layout.grid_item_layout, this.container);
To:
gridView = inflater.inflate(R.layout.grid_item_layout, null);
in the GridViewAdapter.java class.

How to use buttons from different xml files in one class

I have a listview with multiple items and one button to start a new activity. I'm getting Null Pointer Exception when I run my app. How and where shoud I set the OnClickListener to run properly?
Also, how can I pass with Intent the arraylist named listaIngrediente?
Here is my code
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.radu.fridgecheck.MainActivity"
android:orientation="vertical">
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</ListView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/find_recipies"
android:id="#+id/find"
android:layout_weight="0"/>
</LinearLayout>
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="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:focusableInTouchMode="false"/>
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkBox"
android:layout_alignBottom="#+id/checkBox"
android:layout_toRightOf="#+id/checkBox"
android:text="TextView" />
</RelativeLayout>
Adapter
public class Adapter extends ArrayAdapter<Ingredient> {
public LayoutInflater inflater;
public ArrayList<Ingredient> listaIngrediente;
ArrayList<String> ingredienteDisponibile;
private Activity activity;
public Adapter(Activity activity, int textResourceId, ArrayList<Ingredient> ingrediente) {
super(activity, textResourceId, ingrediente);
this.activity=activity;
this.listaIngrediente=ingrediente;
try {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
} catch (Exception e) {
e.printStackTrace();
}
}
public int getCount() {
return listaIngrediente.size();
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (convertView == null) {
v = inflater.inflate(R.layout.list_item, null);
}
final Ingredient ingredients = getItem(position);
final TextView display_ingredients = (TextView) v.findViewById(R.id.name);
display_ingredients.setText(ingredients.getNameI());
final CheckBox checkBox = (CheckBox) v.findViewById(R.id.checkBox);
ListView listView = (ListView) v.findViewById(R.id.listView1);
Button button = (Button) v.findViewById(R.id.button);
listView.addFooterView(button);
Button find = (Button) v.findViewById(R.id.find);
find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getContext(), ShowRecipes.class);
Bundle args = new Bundle(); /// nu reusesc sa transfer obiectele
args.putSerializable("ARRAYLIST",listaIngrediente);
i.putExtra("BUNDLE",args);
activity.startActivity(i);
}
});
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!ingredients.isSelected()) {
checkBox.setChecked(true);
ingredients.setSelected(true);
}
else{
checkBox.setChecked(false);
ingredients.setSelected(false);
}
}
});
return v;
}
}
You have to write that in MainActivity class, because your button is in main_activity.xml
In MainActivity, write this method
public void showRecipes(View view) {
Intent i = new Intent(getContext(), ShowRecipes.class);
Bundle args = new Bundle(); /// nu reusesc sa transfer obiectele
args.putSerializable("ARRAYLIST",listaIngrediente);
i.putExtra("BUNDLE",args);
startActivity(i);
}
In Xml add onClick
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/find_recipies"
android:id="#+id/find"
android:onClick="showRecipes"
/>`
More Information on click Events
http://developer.android.com/guide/topics/ui/controls/button.html#HandlingEvents

ListView and Adapter with a large number of items

I am a newbie of android programming. After some study of ListView and ArrayAdapter, i decided to write a simple demo program just for practicing.
I want to display my custom view style ListView, so I override ArrayAdapter's getView() function. I know that for preventing memory leak, parameter convertView should be checked, and only inflate new object when convertView is null. I Also make a AsyncTask to keep adding data into ArrayAdapter in background(in doInBackground), and keep notifyDataChanged to ListView(in onProgressUpdate() ).
Here is the problem: when I set MAX_ITEM=50 (which means how many data i will add in AsyncTask), everything works fine. But when I set MAX_ITEM=500, logcat shows error message: "Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views." and application shut down. Can anyone tell me where the problem is? The following is my source code "MyTest.java" and my layout xml file "main.xml" and "layout_row.xml", thanks for your watching and helping.
MyTest.Java:
public class MyTest extends Activity {
private static final String TAG="Tany";
private static final int MAX_ITEM = 50;
private MyArrayAdapter adapter;
private ListView listview;
private int addCounter = 0;
public class MyData implements Comparable<MyData>{
public String str1;
public String str2;
public String str3;
public MyData(String str1, String str2, String str3){
this.str1 = str1;
this.str2 = str2;
this.str3 = str3;
}
#Override
public int compareTo(MyData data) {
// TODO Auto-generated method stub
int result = this.str1.compareTo(data.str1);
return result;
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listview = (ListView)findViewById(R.id.listview);
adapter = new MyArrayAdapter(this, R.layout.layout_row);
//set adapter
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Log.d(TAG, "position "+position+" is clicked");
Toast.makeText(parent.getContext(), adapter.getItem(position).str1+", "+adapter.getItem(position).str2, Toast.LENGTH_SHORT).show();
}
});
listview.setTextFilterEnabled(true);
}
public void onStart(){
super.onStart();
MyTask newTask = new MyTask();
newTask.execute();
}
public class MyTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
for(int i = addCounter; i<MAX_ITEM; i++)
{
adapter.add(new MyData("str1="+i,"str2="+i,"str3="+i));
addCounter++;
publishProgress();
}
return null;
}
#Override
protected void onProgressUpdate(Void... progress ){
adapter.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Void result){
Log.d(TAG, "AsyncTask MyTask finsish its work");
}
}
public class MyArrayAdapter extends ArrayAdapter<MyData>{
public MyArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.layout_row, parent, false);
}else{
Log.d(TAG,"recycle view, pos="+position);
row = convertView;
}
TextView tv1 = (TextView) row.findViewById(R.id.textView1);
tv1.setText( ((MyData)getItem(position)).str1 );
TextView tv2 = (TextView) row.findViewById(R.id.textView2);
tv2.setText( ((MyData)getItem(position)).str2 );
TextView tv3 = (TextView) row.findViewById(R.id.textView3);
tv3.setText( ((MyData)getItem(position)).str3 );
return row;
}
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/vertical_container"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:text="#string/list_title_start"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</ListView>
<TextView
android:text="#string/list_title_end"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
layout_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="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/linearLayout1"
android:orientation="horizontal">
<ImageView
android:layout_height="wrap_content"
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:src="#drawable/ic_launcher">
</ImageView>
<TextView
android:text="TextView1"
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dip"
android:layout_marginTop="6dip"
android:textAppearance="?android:attr/textAppearanceLarge">
</TextView>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/linearLayout1"
android:orientation="horizontal">
<TextView
android:id="#+id/textView2"
android:text="TextView"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall">
</TextView>
<TextView
android:text="TextView"
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_marginLeft="6dip">
</TextView>
</LinearLayout>
</LinearLayout>
as Selvin rightly says You're modifying your Views from the method doInBackground which runs on another thread. In android this is forbidden, instead you should modify the views from the onPostExecute method also.

Adding Custom Header to List Fragment in Android

I am trying to add a custom header that isnt clickable but will have a checkbox that will "check all" checkboxes under it.
This is my List Fragment
public class AssesmentListFragment extends ListFragment {
private static String BUNDLE_KEY_APPLICATION = "LIST_ITEM";
FastAssesmentListAdapter adapter;
View listHeader;
public AssesmentListFragment() {}
public AssesmentListFragment(Data[] data) {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Data[] assestments = {new Data("Assesment ID","Name", "Date"), new Data("123456", "Assestment 2", "9/12/12"),
new Data("345672", "Assesment 3", "9/13/12"), new Data("566893", "Assesment 4", "9/14/12")};
//This is the part that makes the app crash
View header = getActivity().getLayoutInflater().inflate(R.layout.list_adapter_assesments, null);
ListView listView = getListView();
listView.addHeaderView(header);
adapter = new FastAssesmentListAdapter(getActivity(), assestments);
setListAdapter(adapter);
updateList(assestments);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
private void updateList(Data[] assestments) {
// NOTE: addAll is not being used to support pre-honeycomb devices
synchronized(adapter) {
adapter.clear();
adapter.addAll(assestments);
adapter.notifyDataSetChanged();
}
}
#Override
public void onListItemClick(ListView parentView, View selectedItemView, int position, long id) {
String model = (String) parentView.getItemAtPosition(position);
((FacilityActivity) getActivity()).onItemSelected(model);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//outState.putInt("curChoice", mCurCheckPosition);
}
}
This is the layout I am trying to use for header
<?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="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="25dp"
android:paddingRight="10dp"
android:orientation="horizontal">
<TextView android:id="#+id/adapter_header_textview_column1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textColor="#color/defaultTextColor"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="28sp"
android:text="Assesment ID" />
<TextView android:id="#+id/adapter_header_textview_column2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textColor="#color/defaultTextColor"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="28sp"
android:text="Name" />
<TextView android:id="#+id/adapter_header_textview_column3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:textColor="#color/defaultTextColor"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="28sp"
android:text="Date"/>
<CheckBox
android:id="#+id/header_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:color="#color/defaultTextColor"
android:layout_weight=".5"
android:gravity="center" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="5dp"
android:background="#color/BPGreenColor" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Then this is the array adapter I am using:
public class FastAssesmentListAdapter extends ArrayAdapter<Data> {
private static int LAYOUT_ID = R.layout.list_adapter_with_checkbox_three_column;
private final Data[] assesments;
private final Context context;
LinearLayout listHeader;
static class ViewHolder {
protected TextView column1;
protected TextView column2;
protected TextView column3;
protected CheckBox checkbox;
}
public FastAssesmentListAdapter(Context context, Data[] assesments) {
super(context, LAYOUT_ID, assesments);
this.context = context;
this.assesments = assesments;
}
//ListFragment and array adapter will automatically call this over and over to auto populate the list
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Data item = getItem(position);
// Formulate row view (create if it does not exist yet)
View view = convertView;
if(view == null) {
LayoutInflater inflater = ((Activity) getContext()).getLayoutInflater();
view = inflater.inflate(LAYOUT_ID, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.column1 = (TextView) view.findViewById(R.id.adapter_textview_column1);
viewHolder.column2 = (TextView) view.findViewById(R.id.adapter_textview_column2);
viewHolder.column3 = (TextView) view.findViewById(R.id.adapter_textview_column3);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check_box);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Clicked",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getContext(), FacilityActivity.class);
getContext().startActivity(intent);
}
});
if(viewHolder.checkbox != null) {
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked) {
item.setSelected(isChecked);
Toast.makeText(getContext(), "Checked",
Toast.LENGTH_SHORT).show();
}
}
});
}
view.setTag(viewHolder);
viewHolder.checkbox.setTag(position);
}
ViewHolder viewHolder = (ViewHolder) view.getTag();
viewHolder.checkbox.setTag(position);
viewHolder.column1.setText(item.getColumn1());
viewHolder.column2.setText(item.getColumn2());
viewHolder.column3.setText(item.getColumn3());
viewHolder.checkbox.setChecked(item.isSelected());
return view;
}
}
on a side note, the onlistitemclicked in the fragment doesnt work, i have to set a listener in the adapter and then it works. any ideas on that? but mainly I need to figure out how to use a custom header and custom rows in the list view. Here is the layout for the rows
<?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="wrap_content"
android:paddingLeft="25dp"
android:paddingRight="10dp"
android:orientation="horizontal">
<TextView android:id="#+id/adapter_textview_column1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25sp" />
<TextView android:id="#+id/adapter_textview_column2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25sp" />
<TextView android:id="#+id/adapter_textview_column3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25sp" />
<CheckBox
android:id="#+id/check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:gravity="center" />
</LinearLayout>

Categories

Resources