how can i code public class for SimpleCursorAdapter? - java

I am new to android and I need to use ListView for my project. I use a sample from the internet which has no public class for ListView so I am not able to code flexible. how can I code public class for this.
public class LIGHTS extends AppCompatActivity {
ListView users_list;
private DatabaseManager dbManager;
private SimpleCursorAdapter adapter;
private DatabaseHelper dbHelper;
final String[] from = new String[]{dbHelper._ID, dbHelper.TITLE, dbHelper.DESC};
final int[] to = new int[]{R.id.id, R.id.KEYCODE, R.id.NAME};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lights);
startconnection();
dbManager = new DatabaseManager(this);
dbManager.open();
Cursor cursor = dbManager.fetch();
users_list = findViewById(R.id.users_list);
adapter = new SimpleCursorAdapter(this, R.layout.adapter, cursor, from, to, 0);
users_list.setAdapter(adapter);}
and the fetch() is in below code in dbmanager:
public Cursor fetch() {
String[] columns = new String[]{dbHelper._ID, dbHelper.TITLE, dbHelper.DESC};
Cursor cursor = database.query(dbHelper.TABLE_NAME, columns, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}

Here's an example based upon your code that handles clicking a button for each item in the list.
If you click a switch then it displays the id of the item via a toast.
This utilises a Custom Adapter based upon (extends) the CursorAdapter class.
First the layout adapter.xml used for the item (should have the basics of your's and includes a switch who's id is the_switch) :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/id"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/KEYCODE"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/NAME"
android:layout_width="0dp"
android:layout_weight="6"
android:layout_height="wrap_content" />
<Switch
android:id="#+id/the_switch"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:focusable="false"
/>
</LinearLayout>
The Activity Lights.java is now :-
public class Lights extends AppCompatActivity {
ListView users_list, alt_users_list;
private DatabaseManager dbManager;
private MyCustomCursorAdapter adapter;
//private DatabaseManager dbHelper; //?????? a second not needed
Cursor cursor;
Context mContext;
//<<<<<<<<<< Not needed although could be passed
//final String[] from = new String[]{DatabaseManager._ID, DatabaseManager.TITLE, DatabaseManager.DESC};
//final int[] to = new int[]{R.id.id, R.id.KEYCODE, R.id.NAME};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_lights);
startconnection(); //?????? dummied out
users_list = findViewById(R.id.users_list);
alt_users_list = findViewById(R.id.alt_users_list);
dbManager = new DatabaseManager(this);
dbManager.open();
manageListView(); //Handles the ListView
}
// Moved here handles list refresh if called (e.g. in onResume)
private void manageListView() {
cursor = dbManager.fetch();
//Setup the adapter if not already setup else swaps (refreshes) the cursor
if (adapter == null) {
adapter = new MyCustomCursorAdapter(this, cursor);
users_list.setAdapter(adapter);
users_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(mContext,"You clicked on the item with an ID of " + String.valueOf(id),Toast.LENGTH_SHORT).show();
}
});
} else {
adapter.swapCursor(cursor);
}
}
private void startconnection(){}
#Override
protected void onDestroy() {
super.onDestroy();
// Close the Cursors when done with them
cursor.close();
}
#Override
protected void onResume() {
super.onResume();
// Refresh the listviews when returning to the activity
manageListView();
}
}
Comments try to explain changes (basically it is quite similar).
The biggest change is that the setting up of the listview has been moved to a method of it's own, which also handles refreshing the listview (redisplaying it after the underlying data has been changed).
The instantiation of the adapter is also simpler than for the SimpleCursorAdapter (the layout and column to view handling coded in the adapter).
The adapter myCustomAdapter.java is :-
public class MyCustomCursorAdapter extends CursorAdapter {
public MyCustomCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (position % 2 == 0) {
view.setBackgroundColor(0xFFAAAAFF);
} else {
view.setBackgroundColor(0xAAAAAAFF);
}
return view;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.adapter,parent,false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
((TextView)view.findViewById(R.id.id)).setText(cursor.getString(cursor.getColumnIndex(DatabaseManager._ID)));
((TextView)view.findViewById(R.id.KEYCODE)).setText(cursor.getString(cursor.getColumnIndex(DatabaseManager.TITLE)));
((TextView)view.findViewById(R.id.NAME)).setText(cursor.getString(cursor.getColumnIndex(DatabaseManager.DESC)));
Switch thisswitch = view.findViewById(R.id.the_switch);
thisswitch.setTag(cursor.getString(cursor.getColumnIndex(DatabaseManager._ID)));
thisswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(buttonView.getContext(),
"You clicked the switch for ID " + (String) buttonView.getTag() +
" the status is now " + (new Boolean(isChecked)).toString(),
Toast.LENGTH_SHORT)
.show()
;
}
});
}
}
bindView has primarily been used it :-
binds the values from the columns of the cursor to the views for each item
and in this case sets the tag of the switch to the id and then adds an onCheckChangedListener for the Button.
bindView has the advantage that the cursor and context are passed to it.
getView can also be used, it has the advantage of having the position of the item in the list passed.
In this case it has been used to alternate the background colour for each item.
Result
Here's a screen shot showing the toast (note testing data was added to the underlying database, so this will obviously vary from yours) :-
Additional
It might be that you need to handle the switch check change in the owning activity.
The following changes show a basic means, via an interface, of handling the switch event in the activity, rather than in the adapter.
First the interface myOnCheckedChangedInterface.java
public interface myOnCheckedChangedInterface {
void myOnCheckedChangedHandler(String id, boolean check_status);
}
Second change Lights.java by adding the handler method myOnCheckedChangedHandler
#Override
public void myOnCheckedChangedHandler(String id, boolean check_status) {
Toast.makeText(
this,
"You changed the status for the row with an id of " + id +
" the status is now " + new Boolean(check_status).toString(),
Toast.LENGTH_SHORT).show();
}
Ignore the error that the method doesn't override method from it's superclass.
Third change the Class declaration to implement the interface by adding implements myOnCheckedChangedInterface as per :-
public class Lights extends AppCompatActivity implements myOnCheckedChangedInterface {
Lastly change MyCustomCursorAdapter to be able to call the myOnCheckedChangedHandler
e.g.
public class MyCustomCursorAdapter extends CursorAdapter {
Lights calling_activity; //<<<<<<<<<<########### ADDED for interface
public MyCustomCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
this.calling_activity = (Lights) context; //<<<<<<<<<<########### ADDED for interface
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (position % 2 == 0) {
view.setBackgroundColor(0xFFAAAAFF);
} else {
view.setBackgroundColor(0xAAAAAAFF);
}
return view;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.adapter,parent,false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
((TextView)view.findViewById(R.id.id)).setText(cursor.getString(cursor.getColumnIndex(DatabaseManager._ID)));
((TextView)view.findViewById(R.id.KEYCODE)).setText(cursor.getString(cursor.getColumnIndex(DatabaseManager.TITLE)));
((TextView)view.findViewById(R.id.NAME)).setText(cursor.getString(cursor.getColumnIndex(DatabaseManager.DESC)));
Switch thisswitch = view.findViewById(R.id.the_switch);
thisswitch.setTag(cursor.getString(cursor.getColumnIndex(DatabaseManager._ID)));
thisswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
/**
Toast.makeText(buttonView.getContext(),
"You clicked the switch for ID " + (String) buttonView.getTag() +
" the status is now " + (new Boolean(isChecked)).toString(),
Toast.LENGTH_SHORT)
.show()
**/
calling_activity.myOnCheckedChangedHandler((String)buttonView.getTag(),isChecked); //<<<<<<<<<<########### ADDED for interface
}
});
}
}
See commments with //<<<<<<<<<<########### ADDED for interface for changes
The original Toast has been commented out as it is no longer needed
Note this isn't the tidiest way as the Adapter is tied to a Lights activity, it's just meant to be a simple example.

In order to customize a ListAdapter, you need to create your own custom ListAdapter class that is based on, or 'extends' the built-in ListAdapter (such as SimpleListAdapter or BaseAdapter). Then, you can customize the appearance and what fields of data to display. Below is an example of a custom ListAdapter I called ClaimsListAdapter.java that 'extends' the built-in class called BaseAdapter:
package com.mycompany.myapp.adapter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import com.mycompany.myapp.ClaimListFragment;
import com.mycompany.myapp.R;
import com.mycompany.myapp.TripListFragment;
import com.mycompany.myapp.model.ClaimItem;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
// You might be able to extend SimpleListAdapter instead if you wish
public class ClaimListAdapter extends BaseAdapter {
private Context context;
private ArrayList<ClaimItem> claimItems;
ClaimListFragment fragment;
//I'm passing references to both the active Context as well as the active Fragment
//You might only need to pass the active Context
public ClaimListAdapter(ClaimListFragment fragment, Context context, ArrayList<ClaimItem> claimItems){
this.context = context;
this.claimItems = claimItems;
this.fragment = fragment;
}
#Override
public int getCount() {
return claimItems.size();
}
#Override
public Object getItem(int position) {
return claimItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//This is the layout for the list item. A SimpleListAdapter doesn't need one
//since it only has one text view, but this allows you to create multiple lines
//and/or multiple fields, buttons, checkboxes etc if you wish
convertView = mInflater.inflate(R.layout.claim_list_item, null);
}
//Get a reference to all of the items in the layout you wish to change
Button btnDelete = (Button) convertView.findViewById(R.id.claim_delete_in_list);
//Note, here I'm saving the row number in the tag of the button to tell the fragment
//which row in the array to delete.
btnDelete.setTag(position);
//Here is an example of setting a click listener for a button in the list
btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Integer position = (Integer)v.getTag();
//Call the Public method in the parent Fragment (or Activity) to delete from the
//array and refresh the list
fragment.deleteItemList(position);
}
});
btnDelete.setVisibility(View.GONE);
//Get a reference to all of the text fields in the list item
TextView txtTitle = (TextView) convertView.findViewById(R.id.claim_title);
TextView txtStatus = (TextView) convertView.findViewById(R.id.claim_status);
TextView txtDate = (TextView) convertView.findViewById(R.id.claim_date);
TextView txtDistance = (TextView) convertView.findViewById(R.id.claim_distance);
TextView txtAmount = (TextView) convertView.findViewById(R.id.claim_amount);
String claim_title = claimItems.get(position).getDocumentID();
String claim_status = claimItems.get(position).getClaimStatus();
txtTitle.setText(claim_title);
txtStatus.setText(claim_status);
return convertView;
}
}
And the claim_list_item.xml layout file:
<?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="wrap_content"
android:baselineAligned="false"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/whole_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.7"
android:background="#drawable/list_selector_light"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/top_layout"
android:layout_width="match_parent"
android:layout_height="20dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:layout_weight="0.48"
android:background="#00000000"
android:orientation="horizontal" >
<TextView
android:id="#+id/claim_title"
android:layout_width="match_parent"
android:layout_height="20dp"
android:layout_marginBottom="2dp"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:layout_marginRight="5dp"
android:layout_marginEnd="5dp"
android:layout_weight="0.73"
android:background="#00000000"
android:gravity="start|center_vertical"
android:text=""
android:textColor="#FFFFFFFF"
android:textSize="16sp" />
<TextView
android:id="#+id/claim_status"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginBottom="2dp"
android:layout_marginEnd="5dp"
android:layout_marginRight="5dp"
android:background="#00000000"
android:gravity="end|center_vertical"
android:text=""
android:textColor="#FFFFFFFF"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/bottom_layout"
android:layout_width="match_parent"
android:layout_height="20dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:layout_weight="0.48"
android:background="#00000000"
android:orientation="horizontal" >
<TextView
android:id="#+id/claim_date"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:background="#00000000"
android:gravity="start|center_vertical"
android:text=""
android:textColor="#FFFFFFFF"
android:textSize="14sp" />
<TextView
android:id="#+id/claim_distance"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="50dp"
android:layout_marginStart="50dp"
android:layout_marginRight="50dp"
android:layout_marginEnd="50dp"
android:layout_weight="1.0"
android:layout_gravity="center"
android:background="#00000000"
android:gravity="center|center_vertical"
android:text=""
android:textSize="12sp"
android:textColor="#FFFFFFFF"/>
<TextView
android:id="#+id/claim_amount"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginBottom="2dp"
android:layout_marginEnd="5dp"
android:layout_marginRight="5dp"
android:background="#00000000"
android:gravity="end|center_vertical"
android:text=""
android:textColor="#FFFFFFFF"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/claim_delete_in_list"
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_weight="0.3"
android:text="#string/delete"
android:textSize="16sp"
android:textColor="#FFFFFFFF"
android:background="#android:color/holo_red_dark"
/>
</LinearLayout>

Related

How do I create an OnClickListener for a button within my list adapter that will allow me to set the visibility for an EditText view

I currently have a listview that contains a button and EditText view. How do I properly implement an OnClickListener in my list adapter so when each button is clicked, the associated EditText within the view is hidden via the setVisibility method.
Based on my current implementation of the OnClickListener in my list adapter, when I click a button to hide the corresponding EditText within the view it hides the very last EditText within the viewport and does not hide the corresponding EditText that it's in the same view as the button. Below is my listview xml file (inspection_single_row.xml), my list adapter (InspectionAdapter.java) and main activity (MainActivity).
inspection_single_row.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="vertical">
<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:text="Was the sink cleaned floors mopped"
android:id="#+id/text_id"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/check_boxes"
android:layout_marginBottom="20dp"
android:gravity="center_horizontal">
<RadioGroup
android:id="#+id/groupRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:orientation="horizontal">
<RadioButton
android:id="#+id/radioComplete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Complete"
android:checked="false"
android:textColor="#color/grey_mid"/>
<RadioButton
android:id="#+id/radioIncomplete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Incomplete"
android:checked="false"
android:textColor="#color/grey_mid"
android:layout_marginLeft="25dp"/>
</RadioGroup>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="click"
android:onClick="clickMe"
android:id="#+id/btn"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/master_linlayout"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp">
<EditText
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginBottom="20dp"
android:gravity="top"
android:padding="10dp"
android:textSize="14sp"
android:background="#drawable/border2"
android:inputType="textMultiLine"
android:textColor="#color/grey_mid"
android:id="#+id/edit_text"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
InspectionAdapter.java
public class InspectionAdapter extends ArrayAdapter<InspectionObject> {
ArrayList<InspectionObject> arrayList;
Context context;
int Resource;
LayoutInflater layoutInflater;
ProgressHolder holder;
public InspectionAdapter(Context context, int resource, ArrayList<InspectionObject> objects) {
super(context, resource, objects);
this.context = context;
arrayList = objects;
Resource = resource;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private static class ProgressHolder {
public RadioGroup radio_group;
public EditText deficiency_notes;
public TextView inspection_task;
public RadioButton radio_yes;
public RadioButton radio_no;
public LinearLayout master_layout;
public Button my_button;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View v = convertView;
holder = new ProgressHolder();
if(v == null)
{
v = layoutInflater.inflate(Resource, null);
holder.radio_group = (RadioGroup)v.findViewById(R.id.groupRadio);
holder.deficiency_notes = (EditText)v.findViewById(R.id.edit_text);
holder.inspection_task = (TextView)v.findViewById(R.id.text_id);
holder.radio_yes = (RadioButton)v.findViewById(R.id.radioComplete);
holder.radio_no = (RadioButton)v.findViewById(R.id.radioIncomplete);
holder.master_layout = (LinearLayout)v.findViewById(R.id.master_linlayout);
holder.my_button = (Button)v.findViewById(R.id.btn);
v.setTag(holder);
}else{
holder = (ProgressHolder)v.getTag();
}
final InspectionObject inspectionObject = arrayList.get(position);
holder.my_button.setTag(position);
holder.deficiency_notes.setTag(position);
holder.my_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = (Integer) v.getTag(); //the real and updated position
Log.i("ConfirmAdapter","Button # position : " + pos);
Log.i("ConfirmAdapter","EditText # position : " + holder.deficiency_notes.getTag());
}
});
return v;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView lv;
InspectionAdapter inspection_adapter;
ArrayList<InspectionObject> inspectionList;
Boolean eval;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = findViewById(R.id.listView2);
inspectionList = new ArrayList<InspectionObject>();
inspectionList = new ArrayList<InspectionObject>();
inspectionList.add(new InspectionObject(true, "", "Were the floor mopped?"));
inspectionList.add(new InspectionObject(true, "", "Were the mirrors cleaned?"));
inspectionList.add(new InspectionObject(false, "", "Were the toilets cleaned?"));
inspectionList.add(new InspectionObject(true, "", "Was high/low dusting performed?"));
inspection_adapter = new InspectionAdapter(getApplicationContext(), R.layout.inspection_single_row, inspectionList);
lv.setAdapter(inspection_adapter);
}
}
Edit:
In this part
Log.i("ConfirmAdapter","EditText # position : " + holder.deficiency_notes.getTag())
you are still referencing the holder variable that is created last. As i said before: In getView, for every view, you create a new ProgressHolder assigning it to holder variable. So holder is overwritten everytime getView is called. That's why, Log.i gives your last item.
Try the following:
Put the new ProgressHolder inside if clause.
if(v == null)
{
holder = new ProgressHolder();
This way it only creates a new instance, when the view is null.
Instead of setting the tag for the button to position you can set it to holder like this
holder.my_button.setTag(holder);
you don't need to set tag for EditText.
Then in the onClick you get the corresponding instance of ProgressHolder via getTag() and change the visibilty like this:
holder.my_button.setTag(holder);
holder.my_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProgressHolder clickedHolder = (ProgressHolder)view.getTag();
clickedHolder.deficiency_notes.setVisibility(View.GONE);
}
});

Null Pointer Exception when invoking setOnItemClickListener

New to Android and Java and learning by doing but I seem to be missing something fundamental on detecting item clicks in a ListView.
I have an activity that is a couple of buttons with a ListView below them. Each ListView item has an icon that can be clicked on, that will eventually go to another activity, and a timestamp (currently just indicating the click worked via Toast). Click detection on the icon is working but I am trying to implement selection of items in the ListView and that is where I am running into trouble.
I have reviewed numerous examples such as this and I think I am doing it as prescribed but I am obviously missing something, as I am receiving a runtime exception "java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference:"
Here is the layout for the view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.foo.magma.ViewPassagesActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/linearLayout">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update"
android:onClick="update"
android:id="#+id/updateButton"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
android:onClick="delete"
android:id="#+id/deleteButton"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_weight="1"/>
</LinearLayout>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/passagesListView"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_below="#+id/linearLayout" />
</RelativeLayout>
Here is the layout for an item in the ListView. As mentioned, it an icon on the left with a timestamp:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="10dp"
android:layout_marginTop="4dp"
android:src="#drawable/curve" >
</ImageView>
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Timestamp: "
android:textStyle="bold"
android:textSize="20dp"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/icon"
android:layout_toEndOf="#+id/icon">
android:layout_toRightOf="#+id/icon"
</TextView>
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="layouttesttime"
android:textSize="20dp"
android:layout_below="#+id/date"
android:layout_alignRight="#+id/date"
android:layout_alignEnd="#+id/date"
android:layout_alignLeft="#+id/date"
android:layout_alignStart="#+id/date">
</TextView>
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="layouttestdate"
android:textSize="20dp"
android:layout_alignTop="#+id/icon"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_toRightOf="#+id/label"
android:layout_toEndOf="#+id/label">
</TextView>
</RelativeLayout>
Here is he onCreate() from my activity, which sets my adapter:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_passages);
ListView passagesListView = (ListView) findViewById(R.id.passagesListView);
assert passagesListView != null;
buildPassageList();
PassagesViewAdapter adapter = new PassagesViewAdapter(this, R.layout.passages_row_layout, passages);
passagesListView.setAdapter(adapter);
}
And here is where I am having the issue. The OnClickListener for the icon works. My intent is to detect selection of a ListView item so that it can be deleted. However, when I add the invocation of setOnItemClickListener(), I receive a runtime exception.
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class PassagesViewAdapter extends ArrayAdapter<Passage>{
private int resource;
private List<Passage> passages;
public PassagesViewAdapter(Context context, int resource, List<Passage> passages) {
super(context, resource, passages);
this.resource = resource;
this.passages = passages;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater li = LayoutInflater.from(getContext());
view = li.inflate(resource, null);
}
Passage passage = this.passages.get(position);
TextView time = (TextView) view.findViewById(R.id.time);
TextView date = (TextView) view.findViewById(R.id.date);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
icon.setTag(new Integer(position));
final String positionStr = icon.getTag().toString();
// This works great!
icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "You clicked on " + positionStr, Toast.LENGTH_SHORT).show();
}
});
ListView passagesListView = (ListView) view.findViewById(R.id.passagesListView);
assert passagesListView != null;
// ** This call results in a runtime error for null pointer reference.
passagesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position,long arg3) {
Toast.makeText(getContext(), "Foo", Toast.LENGTH_SHORT).show();
}
});
time.setText(passage.getPassageTime());
date.setText(passage.getPassageDate());
return view;
}
}
That because the View you have in your adapter represents the View you see in the list, not the layout of your ViewPassagesActivity. You do not have a ListView in your ListView items so it cannot be found and findViewById returns null. If you move the part where you set the OnItemClickListener to the onCreate of your ViewPassagesActivity, everything should be working fine
Remove this part from your adapter
// ** This call results in a runtime error for null pointer reference.
passagesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position,long arg3) {
Toast.makeText(getContext(), "Foo", Toast.LENGTH_SHORT).show();
}
});
and add it to your Activity's onCreate like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_passages);
ListView passagesListView = (ListView) findViewById(R.id.passagesListView);
assert passagesListView != null;
buildPassageList();
PassagesViewAdapter adapter = new PassagesViewAdapter(this, R.layout.passages_row_layout, passages);
passagesListView.setAdapter(adapter);
// ** This call results in a runtime error for null pointer reference.
passagesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position,long arg3) {
Toast.makeText(getContext(), "Foo", Toast.LENGTH_SHORT).show();
}
});
}
Try extending your Adapter from BaseAdapter.
This
public class PassagesViewAdapter extends ArrayAdapter<Passage>{
to this
public class PassagesViewAdapter extends BaseAdapter {
Also your setOnItemClickListener needs to be in the onCreate function in your activity, not in the adapter.

Setting listeners on buttons in a ListView populated by a CursorAdapter from a Fragment

Although a developer for more years than I can remember I'm new to Java/Android and the whole OOP thing... Yes we do still exist... shambling relics of a more sequential age...!!
Anyway I have a fragment which invokes a CursorAdapter to populate a ListView.
The ListView has several TextViews and two buttons on each row.
I have been trying to set up listeners on each of the buttons so far without success...
I've searched this forum (and others) and I've used several bits of code suggested by contributors..
From my research my biggest problem seems to be that I'm doing all this from a Fragment.
My question is how do I pass the base ListView id from the Fragment to the Adapter...???
My ListView Child XML...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="60dp">
<TextView
android:layout_marginTop="#dimen/textViewMarginTop"
android:layout_marginRight="#dimen/textViewMarginRight"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="12345678"
android:id="#+id/job_id"
/>
<TextView
android:layout_marginTop="#dimen/textViewMarginTop"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="abcdef"
android:id="#+id/from_location"
android:layout_toRightOf="#+id/job_id"
/>
<TextView
android:layout_marginTop="#dimen/textViewMarginTop"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Blanchardstown"
android:id="#+id/to_location"
android:layout_toRightOf="#+id/from_location"
/>
<Button
android:layout_width="50dp"
android:layout_height="wrap_content"
android:id="#+id/job_bid"
android:text="#string/joblist_bid"
android:layout_below="#+id/job_id"
android:layout_toLeftOf="#+id/job_details"
/>
<Button
android:layout_width="80dp"
android:layout_height="wrap_content"
android:id="#+id/job_details"
android:text="#string/joblist_details"
android:layout_below="#+id/to_location"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
My ListView Parent XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="60dp">
<TextView
android:layout_marginTop="#dimen/textViewMarginTop"
android:layout_marginRight="#dimen/textViewMarginRight"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="12345678"
android:id="#+id/job_id"
/>
<TextView
android:layout_marginTop="#dimen/textViewMarginTop"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="abcdef"
android:id="#+id/from_location"
android:layout_toRightOf="#+id/job_id"
/>
<TextView
android:layout_marginTop="#dimen/textViewMarginTop"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Blanchardstown"
android:id="#+id/to_location"
android:layout_toRightOf="#+id/from_location"
/>
<Button
android:layout_width="50dp"
android:layout_height="wrap_content"
android:id="#+id/job_bid"
android:text="#string/joblist_bid"
android:layout_below="#+id/job_id"
android:layout_toLeftOf="#+id/job_details"
/>
<Button
android:layout_width="80dp"
android:layout_height="wrap_content"
android:id="#+id/job_details"
android:text="#string/joblist_details"
android:layout_below="#+id/to_location"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
My Fragment Code
public class jobListFragment extends ListFragment
{
private final String m_LogcatTag = "assignment5";
public ListView m_jobListView;
public JobDataAdpter m_jobDataAdapter;
JobsDataSource m_datasource;
private SQLiteDatabase m_database;
CursorAdapter m_cursoradaptor;
public View m_jobListFragmentBaseView;
Cursor m_cursor;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
m_jobListFragmentBaseView = inflater.inflate(layout.joblistfragment, container, false);
ListView m_jobListView = (ListView)m_jobListFragmentBaseView.findViewById(android.R.id.list);
//Declare an object to handle database I-O and open a channel to the database
m_datasource = new JobsDataSource (getActivity().getApplicationContext());
m_datasource.open();
m_cursor = m_datasource.getAllJobs();
m_jobDataAdapter = new JobDataAdpter(getActivity().getApplicationContext(), m_cursor, 0);
m_jobListView.setAdapter(m_jobDataAdapter);
return m_jobListFragmentBaseView;
}
My Adapter Code
public class JobDataAdpter extends CursorAdapter
{
private final String mLogcatTag = "assignment5";
protected ListView mListView; THIS IS THE VARIABLE IN QUESTION
public JobDataAdpter(Context context, Cursor cursor, int flags )
{
super(context, cursor, 0);
}
protected static class RowViewHolder
{
public TextView m_job_bid;
public TextView m_job_details;
}
//End New Code\
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
View view = View.inflate(context, R.layout.jobslistlayout, null);
RowViewHolder holder = new RowViewHolder();
holder.m_job_bid = (TextView) view.findViewById(R.id.job_bid);
holder.m_job_details = (TextView) view.findViewById(R.id.job_details);
holder.m_job_bid.setOnClickListener(m_OnBidClickListener);
holder.m_job_details.setOnClickListener(m_OnDetailsClickListener);
view.setTag(holder);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor)
{
TextView m_job_IdView = (TextView) view.findViewById(R.id.job_id);
TextView m_from_LocationView = (TextView) view.findViewById(R.id.from_location);
TextView m_to_LocationView = (TextView) view.findViewById(R.id.to_location);
// Extract properties from cursor
long row_id = cursor.getLong((cursor.getColumnIndexOrThrow(MySQLiteOpenHelper.m_COLUMN_ID)));
String m_job_id = cursor.getString(cursor.getColumnIndexOrThrow(MySQLiteOpenHelper.m_COLUMN_JOB_ID));
String m_From_Location = cursor.getString(cursor.getColumnIndexOrThrow(MySQLiteOpenHelper.m_COLUMN_JOB_FROM_LOCATION));
String m_To_Location = cursor.getString(cursor.getColumnIndexOrThrow(MySQLiteOpenHelper.m_COLUMN_JOB_TO_LOCATION));
// Populate fields with extracted properties
m_job_IdView.setText(m_job_id);
m_from_LocationView.setText(String.valueOf(m_From_Location));
m_to_LocationView.setText(String.valueOf(m_To_Location));
}
private View.OnClickListener m_OnBidClickListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{ HERE IS WHERE THE VARIABLE IS USED
final int position = mListView.getPositionForView((View) v.getParent());
Log.v(mLogcatTag, "Title clicked, row %d" + position);
}
};
private View.OnClickListener m_OnDetailsClickListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
final int position = mListView.getPositionForView((View) v.getParent());
Log.v(mLogcatTag, "Text clicked, row %d" + position);
}
};
}
OK guys .....That's it.... Hope you can help

Spinner Item leads to Activity (Android Studio)

I started programming a few month ago and stackoverflow always was a a good dite for solving my problems. So my codes are getting better but now I´m on a point that I Need your help again.
Programm: In my App you can choose items from a spinner, then it goes to next page and so on. You have to choose from several Spinners until you get a result...
Some Code preview (Code works, but i now have to ad some more Action and I don´t know how...
package com.sio.fmf;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Button;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.TextView;
public class Koerperform extends AppCompatActivity {
String[] koerperform = {" ", "spindel- oder torpedoförmig", "langgestreckt", "hochrückig", "schlangenförmig", "welsartig", "grundelartig"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.koerperform);
Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
mySpinner.setAdapter(new MyCustomAdapter(Koerperform.this,R.layout.spinner_layout, koerperform));
}
public void onClick(View v){}
public class MyCustomAdapter extends ArrayAdapter<String> {
public MyCustomAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
}
private Button getSwtitchact;
{
final Button switchact = (Button) findViewById(R.id.button3);
switchact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent act = new Intent(view.getContext(), Maulstellung.class);
startActivity(act);
}
});
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.spinner_layout, parent, false);
TextView label = (TextView) row.findViewById(R.id.koerper);
label.setText(koerperform[position]);
if (position == 0) {
label.setTextColor(0xFFF00000);
}
return row;
}
}
}
So in this state of the app you can choose the string from the spinner and then if you press Botton 3 it changes to class Maulstellung
My Problem: I want that when string "a" is choosen it goes to page xy after Button 3 is pressed and when string "b" is choosen it goes to page xyz after Button 3 is pressed,..., and so on for each string...
Hope you can help me and sorry for my bad English
I will do in this way:
Not sure is this what you need.
Declare String selectedValue and Spinner mySpinner in global(add after line String[] koerperform).
Remove Spinner beside mySpinner:
Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
Inside getSwtitchact, change to this
private Button getSwtitchact;
{
final Button switchact = (Button) findViewById(R.id.button3);
switchact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedValue=mySpinner.getSelectedItem().toString(); // here you get the selected items from spinner
if(selectedValue.equals("a"))
{
Intent act = new Intent(view.getContext(), xy.class);
startActivity(act);
}
else if(selectedValue.equals("B"))
{
Intent act = new Intent(view.getContext(), xyZ.class);
startActivity(act);
}
else
{
......
}
}
});
}
maybe this layout file helps
<pre>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android: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=".Koerperform"
android:background="#023738">
<ImageView
android:layout_width="fill_parent"
android:layout_height="100dp"
android:id="#+id/imageView1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/header" />
<ImageView
android:layout_width="400dp"
android:layout_height="100dp"
android:id="#+id/imageView5"
android:background="#drawable/frageeins"
android:layout_below="#+id/space4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="fill_parent"
android:layout_height="120dp"
android:id="#+id/imageView6"
android:background="#drawable/fischeins"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/imageView5" />
<Spinner
android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView6"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:clickable="false"
android:contextClickable="false"
/>
<Button
android:layout_width="220dp"
android:layout_height="60dp"
android:id="#+id/button3"
android:layout_marginTop="69dp"
android:background="#drawable/costum_button_weiter_gehts"
android:layout_below="#+id/imageView6"
android:layout_centerHorizontal="true" />
<Space
android:layout_width="30dp"
android:layout_height="20dp"
android:layout_below="#+id/imageView1"
android:layout_centerHorizontal="true"
android:id="#+id/space4" />
</RelativeLayout>

Android: Replacing activity view with fragment view

I've been searching for hours and hours on trying to understand the relationship between Fragments and Activities and I still cant get it right with my code.
I have a mainScreen class that loads actvity_main.xml. This main screen has a layout with a graph and sidebar etc.
I have a button that is on the side bar that is supposed to launch a sidebar fragment that has a checkbox listview in it so I can select data to show on my graph etc. But that fragment is not showing no matter what I do. It shows the "Bing~!" Toast but no other view is launched.
Perhaps I shouldn't be using a fragment? I don't want to start a new activity as the checkbox is supposed to interact with the graph and another fragment with a dynamic table in it and it will interact back and forth and so on.
I'm not too sure what to do here. I have about 3 weeks of Android experience so I'm not exactly knowledgeable about the whole shebang of it just yet. Really appreciate any ideas or help I can get. I am completely stumped and hence had to post my own question.
I really really appreciate any kind of help! Thanks!
mainScreen.java
public class mainScreen extends Activity {
private TextView text_display;
private Button button_list;
private Button button_table;
private String[] dataHolder;
public boolean listClicked = false;
public void loadData () {
//loaddata stuff here
}
public void createGraph () {
//graph create stuff here
}
public void buttonClick () {
button_list.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
sideFragment sf = new sideFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.side_fragment, sf);
ft.commit();
Toast.makeText(mainScreen.this, "Bing~!", Toast.LENGTH_SHORT).show();
}
}
);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = getIntent();
dataHolder = i.getStringArrayExtra("dataHolder");
button_list = (Button)findViewById(R.id.button_list);
loadData();
createGraph();
buttonClick();
}
}
activity_main.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"
tools:context=".mainScreen"
android:id="#+id/mainlayout"
android:orientation="horizontal"
android:weightSum="1">
<LinearLayout
android:orientation="vertical"
android:layout_width="85dp"
android:layout_height="match_parent">
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="85dp"
android:layout_height="85dp"
android:text="Select"
android:id="#+id/button_list" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="85dp"
android:layout_height="85dp"
android:text="Table"
android:id="#+id/button_table" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:text=" "
android:id="#+id/text_display"
android:textSize="26dp"
android:layout_margin="5dp" />
<com.jjoe64.graphview.GraphView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/graph" />
</LinearLayout>
<fragment
android:name="xabre.mobileicip.sideFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/side_fragment" />
</LinearLayout>
sideFragment.java
public class sideFragment extends Fragment implements android.widget.CompoundButton.OnCheckedChangeListener {
ListView listviewFrag;
ArrayList<sideFrag> sideFragList;
sideFragAdapter sfAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.side_fragment, container, false);
listviewFrag = (ListView) view.findViewById(R.id.side_listview);
//displayList();
return view;
}
private void displayList() {
sideFragList = new ArrayList<sideFrag>();
sideFragList.add(new sideFrag("SPO2"));
sideFragList.add(new sideFrag("O2 Flow Rate"));
sideFragList.add(new sideFrag("Resp."));
sideFragList.add(new sideFrag("Cardiac Output"));
sideFragList.add(new sideFrag("Cardiac Index"));
sideFragList.add(new sideFrag("SVR"));
sideFragList.add(new sideFrag("Wedge Pressure"));
listviewFrag.setAdapter(sfAdapter);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int pos = listviewFrag.getPositionForView(buttonView);
if (pos != ListView.INVALID_POSITION) {
sideFrag sf = sideFragList.get(pos);
sf.setSelected(isChecked);
Toast.makeText(getActivity(),"" + sf.getName(), Toast.LENGTH_SHORT).show();
//Toast.makeText(sideFragment.this, "Clicked on sideFrag: " + sf.getName() + ". State: is " + isChecked, Toast.LENGTH_SHORT).show();
}
}
}
side_fragment.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".sideFragment"
android:id="#id/side_fragment">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="HELLO WORLD"
android:id="#+id/helloTester"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp">
<ListView
android:id="#+id/side_listview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
</LinearLayout>
side_list.xml
<?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">
<CheckBox android:id="#+id/check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onCheckboxClicked"
android:layout_marginBottom="15dp" />
<TextView
android:id="#+id/check_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/check_box"
android:textStyle="bold"/>
</RelativeLayout>
sideFragAdapter.java
package xabre.mobileicip;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.List;
class sideFrag {
String name;
boolean selected = false;
public sideFrag(String name) {
super();
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class sideFragAdapter extends ArrayAdapter<sideFrag> implements CompoundButton.OnCheckedChangeListener {
private List<sideFrag> sideList;
private Context context;
public sideFragAdapter (List<sideFrag> sideList, Context context) {
super(context, R.layout.side_list, sideList);
this.sideList = sideList;
this.context = context;
}
private static class sideHolder {
public CheckBox check_box;
public TextView check_name;
/* public CheckBox check_O2FR;
public CheckBox check_Resp;
public CheckBox check_Carout;
public CheckBox check_Carind;
public CheckBox check_svr;
public CheckBox check_resprate;
public CheckBox check_Peep;
public CheckBox check_O2AF;
public CheckBox check_FIO2;
public CheckBox check_PO2;
public CheckBox check_HCO3;
public CheckBox check_Urea;
public CheckBox check_Potassium;
public CheckBox check_Sodium;
public CheckBox check_Creatinine;
public CheckBox check_FluidIn;
public CheckBox check_FluidOut;
*/
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
sideHolder holder = new sideHolder();
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.side_list, parent, false);
holder.check_box = (CheckBox) v.findViewById(R.id.checkbox);
holder.check_name = (TextView) v.findViewById(R.id.check_name);
holder.check_box.setOnCheckedChangeListener(this);
} else {
holder = (sideHolder) v.getTag();
}
sideFrag p = sideList.get(position);
holder.check_name.setText(p.getName());
holder.check_box.setChecked(p.isSelected());
holder.check_box.setTag(p);
return v;
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
}
}
You can only replace elements added from code. side_fragment is added in XML and as such is part of, let's say "read only" structure. You need to remove <fragment> element it from XML, and add it from code if you want to replace it later.

Categories