findViewById returns null. BUT WHY? - android

I have an Adroid Activity and I want to introduce a custom list view. This is my onCreate() activity method.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoadListView();
ListView lvw = (ListView)findViewById(android.R.id.list);
lvw.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String element = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), AddEntryActivity.class);
// sending data to new activity
i.putExtra("entryToEdit", element);
long idToEdit = Long.parseLong(hEntries.get(position).toString());
i.putExtra("idToEdit", idToEdit);
startActivity(i);
}
});
DbAccess oDb = new DbAccess(this);
}
As you can see LoadListView() method is called to load listview items:
private void LoadListView()
{
oDb = new DbAccess(this);
oDb.open();
List<cAttivita> entries = oDb.getAttivita();
CustomListAdapter listAdapter = new CustomListAdapter(MainActivity.this, android.R.layout.simple_list_item_1 , entries);
ListView lvwAttivita = (ListView)findViewById(android.R.id.list);
lvwAttivita.setAdapter(listAdapter);
hEntries = new HashMap();
for(int i = 0; i < entries.size(); i++)
{
hEntries.put(i, entries.get(i).getId());
}
}
CustomListAdapter class:
public CustomListAdapter(Context context, int textViewResourceId , List<cAttivita> list )
{
super(context, textViewResourceId, list);
mContext = context;
id = textViewResourceId;
items = list ;
}
#Override
public View getView(int position, View v, ViewGroup parent)
{
View mView = v ;
if(mView == null){
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(id, null);
}
TextView text = (TextView) mView.findViewById(R.id.textView);
if(items.get(position) != null )
{
text.setTextColor(Color.WHITE);
text.setText(items.get(position).toString());
text.setBackgroundColor(Color.RED);
int color = Color.argb( 200, 255, 64, 64 );
text.setBackgroundColor( color );
}
return mView;
}
This is activity_main.xml code:
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:textSize="20px"
android:paddingTop="10dip"
android:paddingBottom="10dip"/>
<ListView xmlns:android="schemas.android.com/apk/res/android";
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Attività"/>
The problem is in the line:
TextView text = (TextView) mView.findViewById(R.id.textView);
Why text returns null?

Change the following line of code inside your getView() of your CustomAdapter.
TextView text = (TextView) mView.findViewById(android.R.id.text1);
as you are taking android.R.layout.simple_list_item_1 as layout it should be android.R.id.text1 which is declared internally in Android library.
Change my line of code inside getView() and it works for you.

Related

Listview with Checkbox in android studio

I am trying to create a custom listview with a checkbox and a string list of "observations" retrieved from my sqlite database. The idea is that when I click on the "retrieve" button, all checked items are shown in a toast message.
I can populate the listview through my customadapter just fine, but it doesnt seem to recognise the status of each checkbox, as no toast messages are shown, regardless of whether they are checked.
Please can someone show me where I am going wrong?
Here is my custom listview xm that I have called list_o:
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:id="#+id/obsgrid">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chkbx"
android:layout_row="0"
android:layout_column="0" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/obs"
android:layout_row="0"
android:layout_column="1" />
Here is my custom adapter:
class CustomAdObs extends ArrayAdapter<String> {
private String [] observation;
private Boolean [] checked;
private Context context;
public CustomAdObs(Context context, String[] observation) {
super(context, R.layout.list_o, observation);
this.observation = observation;
this.checked = checked;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater siteInflater = LayoutInflater.from(getContext());
View customView = siteInflater.inflate(R.layout.list_o, parent, false);
TextView observationTV = (TextView) customView.findViewById(R.id.obs);
CheckBox checkCB = (CheckBox) customView.findViewById(R.id.chkbx);
checkCB.setTag(Integer.valueOf(position));
observationTV.setText(observation[position]);
checkCB.setChecked(checked[position]);
return customView;
}
}
Finally here is my activity:
public class selobs extends Activity {
List< List<String> > listArray = new ArrayList< List<String> >();
List<String> array1 = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode. setThreadPolicy(policy);
setContentView(R.layout.activity_selobs);
final Button retrieve= (Button) findViewById(R.id.btnret);
final EditText txtob = (EditText) findViewById(R.id.editText23);
filladapter();
retrieve.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
ListView obsListView = (ListView) findViewById(R.id.obsList);
View v;
for (int i = 0; i < obsListView.getCount(); i++) {
v = obsListView.getAdapter().getView(i, null, null);
CheckBox check = (CheckBox) v.findViewById(R.id.chkbx);
TextView obsItem = (TextView) v.findViewById(R.id.obs);
if (check.isChecked()) {
String p = obsItem.getText().toString();
Toast.makeText(selobs.this, p, Toast.LENGTH_LONG).show();
}
}
}
}
);
}
public void filladapter(){
myDBhandler1 dbHandler;
dbHandler = new myDBhandler1(selobs.this, null, null, 1);
listArray = dbHandler.databaseToStringObs();
List array1 = listArray.get(0);
String[] observ = (String[]) array1.toArray(new String[0]);
Boolean[] checked = new Boolean[0];
Arrays.fill(checked, Boolean.FALSE);
final ListAdapter ObsAdapter = new CustomAdObs(this, observ, checked);
final ListView obsListView = (ListView) findViewById(R.id.obsList);
obsListView.setAdapter(ObsAdapter);
obsListView.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(selobs.this, item, Toast.LENGTH_LONG).show();
TextView txtobs = (TextView) findViewById(R.id.editText23);
txtobs.setText(item);
}
}
);
}
}
your constructor
public CustomAdObs(Context context, String[] observation) {//here the Boolean[] checked ->is messing
super(context, R.layout.list_o, observation);
this.observation = observation;
this.checked = checked;
}
so you replace it with this
public CustomAdObs(Context context, String[] observation, Boolean[] checked) {
super(context, R.layout.list_o, observation);
this.observation = observation;
this.checked = checked;
}
why ?
because you call it like this
new CustomAdObs(this, observ, checked);
while you have just the 2 params in your constructor(Context context,String[] observation)

setVisibility(View.GONE) not removing space in listview item

I am making a question that could be like a duplicated question, but i have tried everything and nothing worked for me. I have created a listview witch every item has two views, one textview and one checkbox. Its like a multiselect listview. Every item has a level on its own: easy, normal, hard. When a level is chosen from a dropdown: All, Easy, Normal, Hard.. the list changes, just like a filter system.
But when i write listView.getChildAt(i).setVisibility(View.GONE); the content of the row is removed but the space occupied is not released.
Any help?
This is my code:
public class CreatePresentation extends Activity
{
DatabaseHelper db = new DatabaseHelper(this);
MyCustomAdapter dataAdapter = null;
List<Slider> list;
ListView listView;
String Text;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.create_presentation);
displayListView();
checkButtonClick();
}
private void displayListView()
{
list = new ArrayList<Slider>();
ArrayList<Slider> oldList = db.getAllSliders();
for (Slider anOldList : oldList) {
String s = anOldList.toString();
int in = anOldList.getId();
String lev = anOldList.getLevel();
Slider slider = new Slider(in, s, lev, false);
list.add(slider);
}
dataAdapter = new MyCustomAdapter(this, R.layout.list_check_box, list);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(dataAdapter);
}
private class MyCustomAdapter extends ArrayAdapter<Slider> {
private ArrayList<Slider> list;
public MyCustomAdapter(Context context, int textViewResourceId, List<Slider> list) {
super(context, textViewResourceId, list);
this.list = new ArrayList<Slider>();
this.list.addAll(list);
}
private class ViewHolder {
TextView text;
CheckBox checkbox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
final Slider slider = list.get(position);
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_check_box, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.sliderTitle);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
Spinner dropdown = (Spinner)findViewById(R.id.spinner);
String[] items = new String[]{"Tutto", "Facile", "Medio", "Difficile"};
ArrayAdapter<String> adapter = new ArrayAdapter<String (CreatePresentation.this, android.R.layout.simple_spinner_item, items);
dropdown.setAdapter(adapter);
Text = dropdown.getSelectedItem().toString();
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Slider slider = (Slider) cb.getTag();
slider.setSelected(cb.isChecked());
}
});
try {
if (list.get(position).getLevel().equals("Facile"))
convertView.setBackgroundColor(Color.parseColor("#477C3D"));
else if (list.get(position).getLevel().equals("Medio"))
convertView.setBackgroundColor(Color.parseColor("#936019"));
else if (list.get(position).getLevel().equals("Difficile"))
convertView.setBackgroundColor(Color.parseColor("#A02307"));
} catch (Throwable e) {
e.printStackTrace();
}
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, final int position, long id) {
Text = parentView.getItemAtPosition(position).toString();
try {
if (Text.equals("All")){
Runnable run = new Runnable(){
public void run(){
for (int i = 0; i < list.size(); i++) {
listView.getChildAt(i).setVisibility(View.VISIBLE);
}
}
};
runOnUiThread(run);
}
if (Text.equals("Easy")){
Runnable run = new Runnable(){
public void run(){
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getLevel().equals("Easy")) {
listView.getChildAt(i).setVisibility(View.VISIBLE);
}
else {
listView.getChildAt(i).setVisibility(View.GONE);
}
}
}
};
runOnUiThread(run);
}
if (Text.equals("Normal")){
Runnable run = new Runnable(){
public void run(){
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getLevel().equals("Normal"))
listView.getChildAt(i).setVisibility(View.VISIBLE);
else {
listView.getChildAt(i).setVisibility(View.GONE);
}
dataAdapter.notifyDataSetChanged();
}
}
};
runOnUiThread(run);
}
if (Text.equals("Hard")){
Runnable run = new Runnable(){
public void run(){
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getLevel().equals("Hard"))
listView.getChildAt(i).setVisibility(View.VISIBLE);
else
listView.getChildAt(i).setVisibility(View.GONE);
}
}
};
runOnUiThread(run);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Slider slider = (Slider) cb.getTag();
slider.setSelected(cb.isChecked());
}
});
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(slider.getQuestion());
holder.checkbox.setChecked(slider.isSelected());
holder.checkbox.setTag(slider);
return convertView;
}
}
the best way to do this is to remove the item from the list and call dataAdapter.notifyDataSetChanged()
As you want to remove your view but keep your item inside your List I suggest you to use a different method. When the user choose a value that will cause the item to be hide just set that value to your item and then call
dataAdapter.notifyDataSetChanged();
Doing this you have to modify the logic inside your getView(), I mean if you find an item that is eligible to get hide instead of return convertView inside the getView() method of your customAdapter just return an empty view, like this you item won't be shown but it will still be in your list;)
You can use a parent Layout for Yuor item to resolve the issue:
For example:
<LinearLayout ...>
<!-- Here Your item content starts -->
<LinearLayout android:id="#+id/content">
...
</LinearLayout>
<!-- Here Your content ends -->
</LinearLayout>
Java code:
listView.getChildAt(i).getChildAt(0).setVisibility(View.GONE);
just like a filter system. Why "like", why not make it actually filterable? There are two options. Easier one is overriding toString of your slider. Other one is creating custom filter, which wouldn't use object's toString method. However, I don't remember how exactly to do second one, only that it's possible.
Slider:
String toString(){
return this.type;
}
When spinner selection changes:
adapter.getFilter().filter(selectedDifficulty);
This will automatically display items you want to see.
You shouldnt change visibility of views generated by adapter - they change every time when you scroll listview. Instead you should change the behaviour of underlying adapter.
You can try this layout instead of the ListView since there's only 4 filters:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<include
android:id="#+id/filter_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/<your_listview_adapter>"
android:visibility="visible" />
<include
android:id="#+id/filter_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/<your_listview_adapter>"
android:visibility="visible" />
<include
android:id="#+id/filter_3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/<your_listview_adapter>"
android:visibility="visible" />
<include
android:id="#+id/filter_4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/<your_listview_adapter>"
android:visibility="visible" />
</LinearLayout>
When you want to hide one of the filters you can just do something like:
findViewById(R.id.filter_4).setVisibility(View.GONE);
EDIT:
For instance, if you want to add information to a TextView inside the first include you just have to call the View like this:
View filter1 = findViewById(R.id.filter_1);
TextView tv1 = (TextView) filter1.findViewById(R.id.<the_id_of_the_textview);
tv1.setText("StackOverflow filter");
To prevent add another layout in outside of your layout. You just hide the item's all child views, not item itself.
For example:
if(i == 1){ // assume we need hide the first item.
//item itself
ViewGroup parent = ((ViewGroup) holder.convertView);
for (int j = 0; j < parent.getChildCount(); j++) {
parent.getChildAt(j).setVisibility(View.GONE);
}
}
And i have test this code, works fine for me.

arrayadapter error when created outside onCreate

I have an ArrayAdapter that I use to fill a listview, but I'm unable to create it outside the oncreate event, but at that time I don't have the data.
public class CusPickup extends Activity {
private OrdersReady orderready_data[];
private ListView lView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.orders);
Here I will get a null point exception.
OrderReadyAdapter adapter = new OrderReadyAdapter(this,R.layout.listview_item_row, orderready_data);
lView = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
lView.addHeaderView(header);
lView.setAdapter(adapter);
getData();
}
}
Here I get the data from HTTP get.
private final Handler handler = new Handler() {
#Override
public void handleMessage(final Message msg) {
progressDialog.dismiss();
String bundleResult = msg.getData().getString("RESPONSE");
int TotalRecords = myResult.d.results.size();
for (int i = x; i < TotalRecords; i++ ) {
orderready_data[i] = new OrdersReady(myResult.d.results.get(i).myStr, myDate ,invResult.d.results.get(i).numberStr, invResult.d.results.get(i).qtyInt, myAmount)
}
}
}
If I place the OrderReadyAdapter her I get a code error with a fix "change OrderReadyAdapter(Context, Int, OrdersReady[]) to OrderReadyAdapter(Handle, Int, OrdersReady[]) if I change it I will get more errors.
Also I'm not sure if my declaration of the private OrdersReady orderready_data[] is correct, because if I declare it in code I would declare it like this: OrdersReady orderready_data[] = new OrdersReady[TotalRecords];
Thanks for any help.
New Adapter
public class OrderReadyAdapter extends ArrayAdapter<OrdersReady>{
Context context;
int layoutResourceId;
ArrayList<OrdersReady> data = null;
public OrderReadyAdapter(Context context, int layoutResourceId, ArrayList<OrdersReady> orderReadyArray) {
super(context, layoutResourceId, orderReadyArray);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = orderReadyArray;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
OrderHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new OrderHolder();
holder.mytxt1 = (TextView)row.findViewById(R.id.mytxt1);
holder.mytxt2 = (TextView)row.findViewById(R.id.mytxt2);
holder.mytxt3 = (TextView)row.findViewById(R.id.mytxt3);
holder.mytxt4 = (TextView)row.findViewById(R.id.mytxt4);
holder.mytxt5 = (TextView)row.findViewById(R.id.mytxt5);
row.setTag(holder);
}
else
{
holder = (OrderHolder)row.getTag();
}
OrdersReady orderready = data.get(position);
holder.mytxt1.setText(orderready.place);
holder.mytxt2.setText(orderready.Date);
holder.mytxt3.setText(orderready.invoice);
holder.mytxt4.setText(String.valueOf(orderready.Qty));
holder.mytxt5.setText(String.valueOf(orderready.Amount));
return row;
}
static class OrderHolder
{
TextView mytxt1;
TextView mytxt2;
TextView mytxt3;
TextView mytxt4;
TextView mytxt5;
}
}
I suggest you change the OrdersReady[] into ArrayList. Initialize it in your onCreate method. Also make the orderReady adapter into a class field.
orderReadyArray = new ArrayList<OrderReady>();
ordersReadyAdapter = new OrderReadyAdapter(this,R.layout.listview_item_row, orderReadyArray);
lView = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
lView.addHeaderView(header);
lView.setAdapter(ordersReadyAdapter);
This should initialize an empty listview as you don't have the data yet.
When you receive OrdersReady data from the server, update orderReadyArray as such:
orderReadyArray.clear(); // remove old data
for (int i = x; i < TotalRecords; i++ ) {
orderReadyArray.add(data); // add new data one by one
}
ordersReadyAdapter.notifyDataSetChanged(); // this forces the listview to repaint
Alternatively:
You can create a new adapter and assign it to the listview once you receive the data:
List<OrderReady> orderReadyArray = new ArrayList<OrderReady>(); // create a new array to hold data
for (int i = x; i < TotalRecords; i++ ) {
orderReadyArray.add(data); // add new data one by one
}
OrderReadyAdapter ordersReadyAdapter = new OrderReadyAdapter(this,R.layout.listview_item_row, orderReadyArray);
lView.setAdapter(ordersReadyAdapter);
This should update your list. If you still do not see the items, the problem is in the adapter, perhaps you are inflating the row incorrectly in getView() method.

How to print data in a ListView using ListAdapter

Updated
I'm trying to print the data retrieved from the database on a list view. For a while my application print for each data in the database, a row on the list view. So if there are 10 data in the database, the app prints 10 rows, corresponding to each row of the database. Here is a view of how it is being printed.
The new image of how it looks now:
But, it is not printing the data as I want. I want to print a column of the row in a specific text view, but it doesnt show anything.
So the activity RatedCalss calls the method selectTopCalls() and makes a List receive the list that this method returns. And then I pass this list to the listAdapter.
Well I have this activity named RatedCalls.java:
public class RatedCalls extends Activity {
private static final String LOG_TAG = "RatedCalls";
private CallDataHelper cdh;
private ListView listview;
private ArrayList<String> ratedCallsList;
private MyListAdapter listAdapter;
private View view;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(LOG_TAG, "calling from onCreate()");
cdh = new CallDataHelper(this);
startService(new Intent(this, RatedCallsService.class));
setBasicContent();
}
public void setBasicContent() {
listview = (ListView) findViewById(R.id.list_view);
ratedCallsList = this.cdh.selectTopCalls();
Log.i(LOG_TAG, "ratedCallsList size: " + ratedCallsList.size());
listAdapter = new MyListAdapter(this, this, R.id.list_view, ratedCallsList);
listview.setAdapter(listAdapter);
}
}
I have this class, a ListAdapter class named MyListAdapter.java:
public class MyListAdapter extends ArrayAdapter { //--CloneChangeRequired
private ArrayList mList;
private Context mContext;
private Activity mActivity;
private int selectedPos = -1; // init value for not-selected
private ArrayList<String> ratedCallsList;
private CallDataHelper cdh;
public void setSelectedPosition(int pos){
selectedPos = pos;
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
public MyListAdapter(Context context, Activity activity, int textViewResourceId, ArrayList list) {
super(context, textViewResourceId, list);
this.mList = list;
this.mContext = context;
this.mActivity = activity;
}
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
try{
if (view == null) {
LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.list_item, null); // --CloneChangeRequired(list_item)
}
// setting STRIP BG
if(position == selectedPos){
view.findViewById(R.id.rlt_main).setBackgroundColor( Color.rgb(062, 076, 120) );
}else if(position%2==0){
view.findViewById(R.id.rlt_main).setBackgroundColor( Color.rgb(226, 231, 239) );
}else{
view.findViewById(R.id.rlt_main).setBackgroundColor( Color.rgb(200, 210, 223) );
}
setViews(position, view);
}catch(Exception e){
//Log.i(MyListAdapter.class.toString(), e.getMessage());
}
return view;
}
public void setViews(int position, View view) {
cdh = new CallDataHelper(mContext);
if(mContext.getClass().equals((RatedCalls.class))){
ratedCallsList = this.cdh.selectTopCalls();
Log.i("MYLISTADAPTER", "size " + ratedCallsList.size());
if (ratedCallsList != null) {
((TextView) view.findViewById(R.id.contact_name)).setText(ratedCallsList.get(0));
((TextView) view.findViewById(R.id.phone_number)).setText(ratedCallsList.get(1));
((TextView) view.findViewById(R.id.duration)).setText(ratedCallsList.get(2));
((TextView) view.findViewById(R.id.date)).setText(ratedCallsList.get(3));
}
}else if(mContext.getClass().equals(RatedContacts.class)){
final PublishersBO listPublisher = (PublishersBO) mList.get(position);
if (listPublisher != null) {
//--setting list_item views
((TextView) view.findViewById(R.id.contact_name)).setText(listPublisher.getName());
((TextView) view.findViewById(R.id.phone_number)).setText(listPublisher.getEmail());
//--onClickListener
view.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(mContext,RatedContacts.class);
myIntent.putExtra("NAME", listPublisher.getName());
myIntent.putExtra("ACTIVITY_NAME", mContext.getClass().toString());
mContext.startActivity(myIntent);
mActivity.finish();
}
});
}
}
}
}
The method that retrieve the data from the database is in a separated class that deals with SQLite function. This is the method:
public ArrayList<String> selectTopCalls() {
ArrayList<String> list1 = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME, null, null, null, null, null,
"duration desc");
if (cursor.moveToFirst()) {
do {
//if (cursor.getString(2) != "") {
cdObj = new CallData();
list1.add(cursor.getString(2));
list1.add(cursor.getString(4));
list1.add(cursor.getString(5));
list1.add(cursor.getString(6));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list1;
}
And here is the xml file for the view named list_item.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="67px"
android:id="#+id/rlt_main"
android:layout_toRightOf="#+id/iv_forward">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:id="#+id/iv_forward"
android:src="#drawable/icon"
android:layout_alignParentLeft="true">
</ImageView>
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="#+id/phone_number"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/iv_forward"
android:layout_alignBottom="#+id/iv_forward">
</TextView>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/duration"
android:layout_alignBottom="#+id/phone_number"
android:layout_alignRight="#+id/phone_number"
>
</TextView>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/date"
android:layout_alignBottom="#+id/contact_name"
android:layout_alignRight="#+id/contact_name"
>
</TextView>
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="#+id/contact_name"
android:textSize="20px"
android:layout_toRightOf="#+id/iv_forward"
android:layout_alignParentTop="true">
</TextView>
So I'd like to print the data in the text views in the activity, but I dont know where to set the text, in what class, if in the MyListAdapter class or if in the activity.
Thanks.
I have made few changes to your code, check here,
https://gist.github.com/683b84af9d01bf18fe3d
Thanks.........

Android custom listview

Hi i've got a custom listview with a text view and a button in each row.
Im having trouble trying to use the buttons . Each button will fire a different intent. This is the xml file for the list view rows.
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout
android:id="#+id/widget28"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<Button
android:id="#+id/widget29"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remind me"
android:layout_alignParentRight="true"
/>
<TextView android:id="#+id/text12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ff99ccff"
android:text="Text view" />
</RelativeLayout>
Then i have another xml file which simply contains the list view in a linear layout.
This is my custom array class.
public class customArray extends ArrayAdapter<String> {
int resource;
public customArray(Context cont, int _resource, List<String> items) {
super (cont, _resource,items);
resource = _resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RelativeLayout rl;
String prod = getItem(position);
if (convertView == null) {
rl = new RelativeLayout(getContext());
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi.inflate(resource, rl, true);
} else {
rl = (RelativeLayout)convertView;
}
TextView t1 = (TextView)rl.findViewById(R.id.text12);
t1.setText(prod);
Button b1 = (Button)rl.findViewById(R.id.widget29);
return rl;
}
}
Then the final class which gets the data from a database and uses the custom adapter to display the information. Does anyone know how i would call each button?
`public class SatMain extends Activity {
/** Called when the activity is first created.
* #param cont */
#Override
public void onCreate(Bundle savedInstanceState)
{
List<String> results = new ArrayList<String>();
super.onCreate(savedInstanceState);
setContentView(R.layout.satmain);
dbAdapter db = new dbAdapter(this);
// button.setOnClickListener(m);
//---get all titles---
db.open();
db.InsertData();
Cursor c = db.getSat1();
if (c.moveToFirst())
{
do {
String pub = c.getString(c.getColumnIndex(db.KEY_Artist));
String pub1 = c.getString(c.getColumnIndex(db.KEY_Time));
results.add(pub + pub1 );
} while (c.moveToNext());
}
db.close();
ListView listProducts;
customArray ca = new customArray(this, R.layout.button, results);
listProducts = (ListView)findViewById(R.id.list1);
listProducts.setAdapter(ca);
ca.notifyDataSetChanged();
}
}`
In the "getView" method of your adapter, you should set an onClick listener for the button. You can do an anonymous class so that you can refer to the contents of the row in the button. I.e, add the following where you get b1 in your example.
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//create activity based on prod
}
});

Categories

Resources