I used the below code for displaying all cities time. When i execute my code the time will displayed in a list view, now my problem is once i click any one of the country (position in list), i must pass the Country name, day, month, year and time from the list to another class (*ShowAnalogClock)*. In ShowAnalogClock class i will display the time which is fetched from the list view.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<AutoCompleteTextView
android:id="#+id/autoCompleteZone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:completionThreshold="1" >
<requestFocus />
</AutoCompleteTextView>
<ListView
android:id="#+id/zoneList"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="#+id/autoCompleteTextview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
timezone.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="?android:attr/listPreferredItemHeight"
android:orientation="vertical" >
<TextView
android:id="#+id/timezone_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dip" />
<TextView
android:id="#+id/timezone_time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="15dip" />
</LinearLayout>
My Java code is,
TimeZoneProjectActivity.java
package com.test.timezone;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class TimeZoneProjectActivity extends Activity {
/** Called when the activity is first created. */
ListView ZONE_LIST;
AutoCompleteTextView zoneComplete_TXT;
TimeZoneAdaptor timezoneAdaptor;
List<TimeZoneDataList> timezonelist;
String[] listItems;
TextView auto_completeTXT;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
auto_completeTXT = (TextView) findViewById(R.id.autoCompleteTextview);
ZONE_LIST = (ListView) findViewById(R.id.zoneList);
zoneComplete_TXT = (AutoCompleteTextView) findViewById(R.id.autoCompleteZone);
timezonelist = new ArrayList<TimeZoneDataList>();
timezoneAdaptor = new TimeZoneAdaptor(this, R.layout.timezoneview,
timezonelist);
ZONE_LIST.setAdapter(timezoneAdaptor);
ZONE_LIST.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long arg3) {
// TODO Auto-generated method stub
//
System.out.println("Clicked Position" + position);
}
});
}
#Override
protected void onStart() {
super.onStart();
listItems = TimeZone.getAvailableIDs();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, listItems);
zoneComplete_TXT.setAdapter(adapter);
TimeZone timezone = null;
SimpleDateFormat format = new SimpleDateFormat(
"EEE, MMM d, yyyy h:mm a");
Date now = new Date();
for (int index = 0; index < listItems.length; ++index) {
timezone = TimeZone.getTimeZone(listItems[index]);
format.setTimeZone(timezone);
timezonelist.add(new TimeZoneDataList(
getDiaplayName(listItems[index]), format.format(now)));
timezone = null;
}
}
private String getDiaplayName(String timezonename) {
String displayname = timezonename;
int sep = timezonename.indexOf('/');
if (-1 != sep) {
displayname = timezonename.substring(0, sep) + ", "
+ timezonename.substring(sep + 1);
displayname = displayname.replace("_", " ");
}
return displayname;
}
public class TimeZoneAdaptor extends ArrayAdapter<TimeZoneDataList> {
List<TimeZoneDataList> objects = null;
public TimeZoneAdaptor(Context context, int textViewResourceId,
List<TimeZoneDataList> objects) {
super(context, textViewResourceId, objects);
this.objects = objects;
}
#Override
public int getCount() {
return ((null != objects) ? objects.size() : 0);
}
#Override
public TimeZoneDataList getItem(int position) {
return ((null != objects) ? objects.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (null == view) {
LayoutInflater vi = (LayoutInflater) TimeZoneProjectActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.timezoneview, null);
}
TimeZoneDataList data = objects.get(position);
if (null != data) {
TextView textName = (TextView) view
.findViewById(R.id.timezone_name);
TextView textTime = (TextView) view
.findViewById(R.id.timezone_time);
textName.setText(data.name);
textTime.setText(data.time);
}
return view;
}
}
}
TimeZoneDataList.java
package com.test.timezone;
public class TimeZoneDataList {
public String name;
public String time;
public TimeZoneDataList(String name, String time) {
this.name = name;
this.time = time;
}
}
In which code i will add in the following block, to pass the listview content
ZONE_LIST.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long arg3) {
// TODO Auto-generated method stub
System.out.println("Clicked Position" + position);
}
});
You can only pass primitives and Parcelable objects between Activities. It should be pretty easy to make a class which encapsulates your primitives and implements the Parcelable interface. You can then pass this class in the Extras bundle of the Intent.
Or you can just pass your primitives directly, also in the Intent Extras.
You can get the current item with ListView.getItemAtPosition(position) and then pass this information to your next activity.
See e.g. this example
I used like this, it works good.
ZONE_LIST.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long arg3) {
// TODO Auto-generated method stub
Intent i = new Intent(TimeZonesList.this, TimerClass.class);
i.putExtra("the_image_id", timezonelist.get(position).name);
i.putExtra("the_image_id2", timezonelist.get(position).time);
startActivity(i);
}
});
Related
This is may XML class random values in which we make a row that I want to delete
randomvalues.xml
<LinearLayout
android:id="#+id/linear"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#+id/addbtn">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/img"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/img1"
/>
<LinearLayout
android:layout_width="255dp"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#339966"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/adress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:textColor="#606060" />
</LinearLayout>
</LinearLayout>
<ImageButton
android:id="#+id/removebtn"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/remove"/>
</LinearLayout>
</LinearLayout>
this is my activity_main XML in which i used a list view to show a row that I make in random values XML file
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.chaqeel.taskviews.MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linear">
<ImageButton
android:id="#+id/addbtn"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/add"
android:layout_marginLeft="280dp"/>
</LinearLayout>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/linear"
>
</ListView>
</RelativeLayout>
This is MainActivity.java in which we used a array to show the values
MainActivity.java
package com.example.chaqeel.taskviews;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
public class MainActivity extends Activity {
ListView lv;
String[] Names = {"Aqeel", "Ali", "Ansar", "Usama", "Farhad"};
String[] Address = {"Chakwal", "Rawalpindi", "Islamabad", "Lahore",
"Multan"};
int[] Images = {R.drawable.img1, R.drawable.img2, R.drawable.img3,
R.drawable.img4, R.drawable.img5};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listview);
lv.setAdapter(new dataListAdapter(Names, Address, Images));
}
class dataListAdapter extends BaseAdapter {
String[] Name, Addres;
int[] imge;
/*dataListAdapter() {
Name = null;
Addres = null;
imge=null;
}*/
public dataListAdapter(String[] text, String[] text1, int[] text3) {
Name = text;
Addres = text1;
imge = text3;
}
public int getCount() {
return Name.length;
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup
parent) {
LayoutInflater inflater = getLayoutInflater();
final View row;
row = inflater.inflate(R.layout.randomvalues, parent, false);
final TextView Name, Addres;
ImageView imge;
Name = (TextView) row.findViewById(R.id.name);
Addres = (TextView) row.findViewById(R.id.adress);
imge = (ImageView) row.findViewById(R.id.img);
Name.setText(Names[position]);
Addres.setText(Address[position]);
imge.setImageResource(Images[position]);
final ArrayList<String> lvv= new ArrayList<>();
Collections.addAll(lvv,Names);
// Collection.addAll(lvv,Address);
ImageButton dltbutton = (ImageButton) findViewById(R.id.removebtn);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
lvv.remove(Names);
lvv.remove(Address);
notifyDataSetChanged();
}
});
return (row);
}
}
}
In the onClickListener try the following code
youradapter.notifyDataSetChanged();
In the deletebutton onClickListener try this
Names = ArrayUtils.removeElement(Names,Names[position]);
Address = ArrayUtils.removeElement(Address,Address[position]);
notifyDataSetChanged();
Though it is advised to use OOP concept like a class to hold the Arrays of Names,Address and Images.
Try below code:
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Name = ArrayUtils.removeElement(Names, Names[position]);
Address = ArrayUtils.removeElement(Address, Address[position]);
imge = ArrayUtils.removeElement(imge, imge[position]);
notifyDataSetChanged();
}
});
change this:
ImageButton dltbutton = (ImageButton) findViewById(R.id.removebtn);
dltbutton.setTag(position);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer index = (Integer) view.getTag();
lvv.remove(index.intValue());
notifyDataSetChanged();
}
});
Are you from Chakwal? I am Chakwalian. Again StackOverflow is telling me that my answer does not meet thier quality requirements.
You need to better idea to use Model class as below:-
create a model class MyModel.class
import java.util.ArrayList;
import java.util.List;
public class MyModel {
String Name, Address;
int image;
public MyModel(String name, String address, int image) {
Name = name;
Address = address;
this.image = image;
}
public String getName() {
return Name;
}
public String getAddress() {
return Address;
}
public int getImage() {
return image;
}
}
and then add with adapter class see below:
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
ListView lv;
String[] Names = {"Aqeel", "Ali", "Ansar", "Usama", "Farhad"};
String[] Address = {"Chakwal", "Rawalpindi", "Islamabad", "Lahore",
"Multan"};
int[] Images = {R.drawable.ic_menu_camera, R.drawable.ic_menu_gallery, R.drawable.ic_menu_manage,
R.drawable.ic_menu_send, R.drawable.ic_menu_share};
private List<MyModel> myModel=new ArrayList<>();
private DataListAdapter dataListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
lv = (ListView) findViewById(R.id.listview);
for(int i=0;i<Names.length;i++){
myModel.add( new MyModel(Names[i],Address[i],Images[i]));
}
dataListAdapter=new DataListAdapter(myModel);
lv.setAdapter(dataListAdapter);
}
class DataListAdapter extends BaseAdapter {
private List<MyModel> myModel=new ArrayList<>();
public DataListAdapter(List<MyModel> myModel) {
this.myModel=myModel;
}
public int getCount() {
return myModel.size();
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, final ViewGroup
parent) {
LayoutInflater inflater = getLayoutInflater();
final View row;
row = inflater.inflate(R.layout.randomevalue, parent, false);
final TextView Name, Addres;
ImageView imge;
Name = (TextView) row.findViewById(R.id.name);
Addres = (TextView) row.findViewById(R.id.adress);
imge = (ImageView) row.findViewById(R.id.img);
Name.setText(myModel.get(position).getName());
Addres.setText(myModel.get(position).getAddress());
imge.setImageResource(myModel.get(position).getImage());
ImageButton dltbutton = (ImageButton) row.findViewById(R.id.removebtn);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myModel.remove(position);
notifyDataSetChanged();
}
});
return (row);
}
}
public void addMore(View v)
{
myModel.add( new MyModel("Mahesh","India",R.drawable.ic_menu_share));
dataListAdapter.notifyDataSetChanged();
}
}
public void addMore(View v)
{
myModel.add( new MyModel("Mahesh","India",R.drawable.ic_menu_share));
dataListAdapter.notifyDataSetChanged();
}
add android:onClick="addMore" to your add button
it will fine Happy Coding :)
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterContextMenuInfo info =(AdapterContextMenuInfo) item.getMenuInfo();
pos=info.position;
deleteditem=myList.get(pos);
if(item.getTitle()=="Delete")
{
String delete = myList.get(pos);
File f = new File(path + "/"+ delete);
if (f != null && f.exists())
{
f.delete();
}
myList.remove(pos);
adapter. notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "item has deleted",Toast.LENGTH_LONG).show();
}
I have an ArrayList<String> List which contains some items from the listview all_list. How can I select these items in the list view all_list programmatically by checking the ArrayList<String> List contents?
for e.g., listview all_list contains [0] apple
[1] orange
[2] banana
In ArrayList<String> List, I have orange so I want item on position 1 on the listview all_list to be selected (highlighted) automatically.
I have tried using all_list.setItemChecked(), but it does nothing and shuts down the application. I am performing the operation after listing the adapter.
set an onItemClickListener to the listview such that on click, you set a boolean flag that sets the checkbox in each row to selected. then call notifyDataSetChanged()
Try this
MainActivity.java
package com.example.multiseekbar;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class MainActivity extends Activity {
ListView listView1;
ArrayList<ModelClass> modelClass = new ArrayList<ModelClass>();
FruitSelectAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelClass.add(new ModelClass("Orange", true));
modelClass.add(new ModelClass("Apple", false));
modelClass.add(new ModelClass("Banana", false));
modelClass.add(new ModelClass("Grapes", false));
listView1 = (ListView) findViewById(R.id.listView1);
adapter = new FruitSelectAdapter(MainActivity.this, modelClass);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if(modelClass.get(arg2).isSelected()){
modelClass.get(arg2).setSelected(false);
}else{
modelClass.get(arg2).setSelected(true);
}
adapter.notifyDataSetChanged();
}
});
}
}
activity_main.xml
<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"
tools:context="com.example.multiseekbar.MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
>
</ListView>
</RelativeLayout>
FruitSelectAdapter.java
package com.example.multiseekbar;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FruitSelectAdapter extends BaseAdapter
{
private Activity activity;
private LayoutInflater inflater;
private ArrayList<ModelClass> modelClass=null;
public FruitSelectAdapter(Activity activity, ArrayList<ModelClass> modelClass) {
this.activity = activity;
this.modelClass = modelClass;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return modelClass.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return modelClass.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder =new ViewHolder();
convertView = inflater.inflate(R.layout.row1, null);
holder.txtFruitName = (TextView)convertView.findViewById(R.id.txtFruitName);
holder.cbFruitSelectStatus = (CheckBox)convertView.findViewById(R.id.cbFruitSelectStatus);
holder.linLayBackground = (LinearLayout) convertView.findViewById(R.id.linLayBackground);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.txtFruitName.setText(modelClass.get(position).getFruitName());
holder.cbFruitSelectStatus.setChecked(modelClass.get(position).isSelected());
if(modelClass.get(position).isSelected()){
holder.linLayBackground.setBackgroundColor(Color.parseColor("#80ccff"));
}else{
holder.linLayBackground.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
return convertView;
}
class ViewHolder{
TextView txtFruitName;
CheckBox cbFruitSelectStatus;
LinearLayout linLayBackground;
}
}
row1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/linLayBackground"
android:layout_height="70dp"
android:orientation="horizontal"
>
<TextView
android:id="#+id/txtFruitName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Fruit name"
android:layout_weight="1"
android:textSize="16sp"
android:textColor="#000000" />
<CheckBox
android:id="#+id/cbFruitSelectStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false" />
</LinearLayout>
ModelClass.java
package com.example.multiseekbar;
public class ModelClass {
String fruitName;
boolean isSelected=false;
public ModelClass(String fruitName, boolean isSelected) {
this.fruitName = fruitName;
this.isSelected = isSelected;
}
public String getFruitName() {
return fruitName;
}
public void setFruitName(String fruitName) {
this.fruitName = fruitName;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}
I have a listview with and adapter that changes the title (TextView) and an image (ImageView) of all single item. But I have a problem, I also have and inputsearch (edittext) with the function TextChangedListener to search any single item of the list view. But actualy this is mi code of the TextChangedListener:
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
Alimentacion.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
This generales a null pointer in this line: Alimentacion.this.adapter.getFilter().filter(cs); I think that the null pointer is because when I'm going to search something I only want to search by the title but in the adapter I have the title and the image so tries to search the title and the image and returs the null pointer, I think.
How can separate these thing to search only for the title?
My full code:
** OncreateView of myfragment.xml** (the list view is in a fragment)
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
ArrayAdapter<String> adapter2;
// Search EditText
EditText inputSearch;
// Set the Text to try this out
lv = (ListView)myInflatedView.findViewById(R.id.list_view);
inputSearch = (EditText) myInflatedView.findViewById(R.id.inputSearch);
// Listview Data
final String categorias[] = {"1. Huevos y Lacteos", "2. Carnes y Derivados", "3. Pescados y Mariscos", "4. Aceites y grasos", "5. Verduras y hortalizas",
"6. Frutas", "7. Bebidas",
"8. Comida Rapida", "9. Pasta y Cereales", "10. Bolleria y Snacks"};
Integer ImgCategorias[] = {R.drawable.cat1,R.drawable.cat2,R.drawable.cat3,R.drawable.cat4,R.drawable.cat5,R.drawable.cat6
,R.drawable.cat7,R.drawable.cat8,R.drawable.cat9,R.drawable.cat10};
// Pass results to ListViewAdapter Class
CustomList adapter = new
CustomList(this.getActivity(), categorias, ImgCategorias);
// Binds the Adapter to the ListView
lv.setAdapter(adapter);
// OLD ADAPTER (where only change the text, it works to the TextChangeListener)
/* adapter2 = new ArrayAdapter<String>(this.getActivity(), R.layout.adapter_categorias, R.id.TVTitulo, categorias);
lv.setAdapter(adapter2); */
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text (LINE OF THE NULLPOINTER)
Alimentacion.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
And the CustomList.java
public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final String[] categorias;
private final Integer[] ImgCategorias;
public CustomList(Activity context,
String[] categorias, Integer[] ImgCategorias) {
super(context, R.layout.adapter_categorias, categorias);
this.context = context;
this.categorias = categorias;
this.ImgCategorias = ImgCategorias;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.adapter_categorias, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.TVTitulo);
ImageView imageView = (ImageView) rowView.findViewById(R.id.IVCategoria);
txtTitle.setText(categorias[position]);
imageView.setImageResource(ImgCategorias[position]);
return rowView;
}
}
In conclusion, I want if is posible have the images and the titles in diferents adapters and in the search function put only the adapter of the title. Or something that allows me search for the title with no error..
I have seen this question: android attaching multiple adapters to one adapter
But I don't understand very well how to implement it to my app..
Thanks.
I have modified the code as below and it's working fine now. Please check and let me know:
public class Image {
String categorias;
Integer ImgCategorias;
public String getCategorias() {
return categorias;
}
public void setCategorias(String categorias) {
this.categorias = categorias;
}
public Integer getImgCategorias() {
return ImgCategorias;
}
public void setImgCategorias(Integer imgCategorias) {
ImgCategorias = imgCategorias;
}
}
Your Adapter class:
import java.util.ArrayList;
import java.util.Locale;
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.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomList extends BaseAdapter {
private Context context;
private ArrayList<Image> data;
private ArrayList<Image> listImage;
public CustomList(Context context, ArrayList<Image> listImage) {
this.context = context;
data = listImage;
this.listImage = new ArrayList<Image>();
this.listImage.addAll(listImage);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View rowView = inflater
.inflate(R.layout.adapter_categorias, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.TVTitulo);
ImageView imageView = (ImageView) rowView
.findViewById(R.id.IVCategoria);
txtTitle.setText(data.get(position).getCategorias());
imageView.setImageResource(data.get(position).getImgCategorias());
return rowView;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("DefaultLocale")
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
data.clear();
if (charText.trim().length() == 0) {
data.addAll(listImage);
} else {
for (Image wp : listImage) {
if (wp.getCategorias().toLowerCase().contains(charText)) {
data.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Activity Class:
import java.util.ArrayList;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class Alimentacion extends Activity {
Context context;
TextView txtTVtexto;
EditText txtInputSearch;
ListView list;
CustomList adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_alimentacion);
context = Alimentacion.this;
txtTVtexto = (TextView) findViewById(R.id.TVtexto);
txtInputSearch = (EditText) findViewById(R.id.inputSearch);
list = (ListView) findViewById(R.id.list_view);
ArrayList<Image> listImage = prepareImageList();
adapter = new CustomList(context, listImage);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos,
long id) {
Image image = (Image) list.getItemAtPosition(pos);
Toast.makeText(context, "Name: "+image.getCategorias(), Toast.LENGTH_LONG).show();
}
});
txtInputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
String text = "";
try {
text = txtInputSearch.getText().toString().toLowerCase(Locale.getDefault());
} catch ( Exception e ) {
e.printStackTrace();
}
adapter.filter(text);
}
});
}
private ArrayList<Image> prepareImageList() {
ArrayList<Image> listImage = new ArrayList<Image>();
Image image = new Image();
image.setCategorias("1. Huevos y Lacteos");
image.setImgCategorias(R.drawable.ic_launcher);
listImage.add(image);
image = new Image();
image.setCategorias("2. Carnes y Derivados");
image.setImgCategorias(R.drawable.ic_launcher);
listImage.add(image);
image = new Image();
image.setCategorias("3. Pescados y Mariscos");
image.setImgCategorias(R.drawable.ic_launcher);
listImage.add(image);
image = new Image();
image.setCategorias("4. Aceites y grasos");
image.setImgCategorias(R.drawable.ic_stub);
listImage.add(image);
image = new Image();
image.setCategorias("5. Verduras y hortalizas");
image.setImgCategorias(R.drawable.share);
listImage.add(image);
image = new Image();
image.setCategorias("6. Frutas");
image.setImgCategorias(R.drawable.ic_launcher);
listImage.add(image);
image = new Image();
image.setCategorias("7. Bebidas");
image.setImgCategorias(R.drawable.ic_launcher);
listImage.add(image);
image = new Image();
image.setCategorias("8. Comida Rapida");
image.setImgCategorias(R.drawable.ic_launcher);
listImage.add(image);
image = new Image();
image.setCategorias("9. Pasta y Cereales");
image.setImgCategorias(R.drawable.ic_launcher);
listImage.add(image);
image = new Image();
image.setCategorias("10. Bolleria y Snacks");
image.setImgCategorias(R.drawable.ic_launcher);
listImage.add(image);
return listImage;
}
}
Layout:
fragment_alimentacion.xml:
<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"
tools:context="es.bawi.testdeporte.Alimentacion" >
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/TVtexto"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_horizontal|center_vertical"
android:text="Blank Fragment" />
<!-- Editext for Search -->
<EditText
android:id="#+id/inputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/TVtexto"
android:hint="Productos"
android:inputType="textVisiblePassword" />
<!-- List View -->
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/inputSearch" />
</RelativeLayout>
adapter_categorias.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/holo_blue_light"
android:paddingBottom="2dp" >
<RelativeLayout
android:layout_width="fill_parent"
android:background="#android:color/holo_green_light"
android:layout_height="70dp">
<ImageView
android:id="#+id/IVCategoria"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerVertical="true"
android:src="#drawable/ic_launcher"
android:focusable="false" />
<TextView
android:id="#+id/TVTitulo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_centerVertical="true"
android:layout_toRightOf="#id/IVCategoria"
android:text="Categoria"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/TVCalorias"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/TVTitulo"
android:paddingTop="0dp"
android:text="NÂș Productos"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
</LinearLayout>
I am trying to display a custom listview but nothing appears.
My activity:
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import com.example.elnoorgeh.ServerAPI;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class BlogFragment extends Fragment {
JSONArray jArray;
TextView title;
RelativeLayout layout;
int previousID = 0;
int currentID = 0;
ArrayList<String> titles;
ArrayList<String> contents;
ListView list;
public BlogFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_blog, container,
false);
new AsyncFetch().execute();
return rootView;
}
private class AsyncFetch extends AsyncTask<Object, Object, Object> {
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
jArray = new JSONArray();
jArray = ServerAPI.getData();
titles = new ArrayList<String>();
contents = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
String blogTitle = null;
String content = null;
try {
blogTitle = jArray.getJSONObject(i).getString("title");
content = jArray.getJSONObject(i).getString("content");
titles.add(blogTitle);
contents.add(content);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(blogTitle);
System.out.println(content);
}
// display(titles, contents);
return null;
}
protected void onPostExecute(Object result) {
layout = (RelativeLayout) getView().findViewById(R.id.blogPage);
layout.removeAllViews();
CustomList adapter = new CustomList(getActivity(), titles);
list = new ListView(getActivity());
System.out.println("list done");
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(),
"You Clicked at " + titles.get(position),
Toast.LENGTH_SHORT).show();
}
});
}
}
public void display(ArrayList<String> t, ArrayList<String> c) {
}
}
Custom ListView class:
import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomList extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> web;
// private final Integer[] imageId;
public CustomList(Activity context, ArrayList<String>web) {
super(context, R.layout.fragment_listview);
this.context = context;
this.web = web;
// this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.fragment_listview, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText((CharSequence) web.get(position));
// imageView.setImageResource(imageId[position]);
return rowView;
}
}
fragment_blog:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/blogPage"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
<TextView
android:id="#+id/txtLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:maxLines="20"
android:singleLine="false"
android:textSize="16dp" />
</RelativeLayout>
fragment_listview:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow>
<ImageView
android:id="#+id/img"
android:layout_width="50dp"
android:layout_height="50dp" />
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="50dp" />
</TableRow>
</TableLayout>
I can't find any errors or notice something irregular, so why is that happening?
you should extend BaseAdapter and implement abstract methods
#Override
public int getCount() {
return web.size();
}
#Override
public Object getItem(int position) {
return web.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
also you might change
txtTitle.setText((CharSequence) web.get(position));
to
txtTitle.setText((CharSequence) getItem(position));
now your adapter don't know size of web array
edit:
you can get one inflater in constructor and keep in class, no need to getting inflater each time (little bit better for perfomance)
LayoutInflater inflater = context.getLayoutInflater();
edit 2:
localhost put proper comment - you are removing all Views from RelativeLayout, also ListView, and creating new ListView without adding to Relative. keeping reference will not auto-add View
protected void onPostExecute(Object result) {
layout = (RelativeLayout) getView().findViewById(R.id.blogPage);
layout.removeView(getView().findViewById(R.id.txtLabel);
//assuming you need to remove only txtLabel
CustomList adapter = new CustomList(getActivity(), titles);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(),
"You Clicked at " + titles.get(position),
Toast.LENGTH_SHORT).show();
}
});
}
my app has custom ListView, each row contains checkbox ,edit text and 2 buttons. In the main xml layout file i have 1 submit button and listView. i want that, when i click on submit button, i should get all checked row position.I am new to android programming ,so plz help me my code is not working here is my code:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button android:layout_height="wrap_content"
android:text="#string/button_submit"
android:layout_width="wrap_content"
android:id="#+id/main_submit_button" android:onClick="#string/button_submit"></Button>
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout android:layout_height="wrap_content"
android:layout_width="fill_parent">
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent" android:layout_weight="1"
android:id="#+id/items_name"
android:gravity="left"
android:textStyle="bold" />
<CheckBox android:id="#+id/items_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
/>
</LinearLayout>
<LinearLayout android:layout_height="wrap_content"
android:layout_width="fill_parent">
<Button android:id="#+id/items_add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:text="#string/text_switcher_plus" />
<EditText android:digits="10"
android:textStyle="bold" android:gravity="left"
android:id="#+id/items_plates" android:layout_height="wrap_content"
android:layout_width="90dp"></EditText>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/items_minus_button"
android:text="#string/text_switcher_minus"
android:gravity="right"
/>
</LinearLayout>
</LinearLayout>
VegmenuActivity
package com.sagar.resmenu;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
// reference:http://pareshnmayani.wordpress.com/tag/android-custom-listview-example
public class VegmenuActivity extends Activity implements OnItemClickListener{
//dynamic array that contains names of items
private ArrayList<String> items = new ArrayList<String>
(Arrays.asList("Veg pulav", "Pav bhaji", "Panir tikka", "veg kolhapuri",
"Coconut Rice", "Curd rice", "Mint Pulao",
"Banana Custard","Basundi", "Cheese potato Tikkis",
"Dum aloo"));
private ArrayList<Integer> counter = new ArrayList<Integer>
(Arrays.asList(0, 0,0, 0, 0,0, 0,0, 0,0,0));
private SparseBooleanArray a;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ListView lv =(ListView)findViewById(R.id.list_view);
// lv.setOnClickListener(null);
MyAdapter adapter = new MyAdapter(getApplicationContext(),items,counter);
lv.setAdapter(adapter);
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button submit1;
submit1 = (Button)findViewById(R.id.main_submit_button);
submit1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
a = new SparseBooleanArray();
a.clear();
a = lv.getCheckedItemPositions();
int len = items.size();
for (int i = 0; i < len; i++)
{
if(a.valueAt(i) == true)
Log.d("Returned ", String.valueOf(a.valueAt(i)));
}
}
});
}
//private OnItemClickListener selectCat = new OnItemClickListener();
public void onItemClick(AdapterView<?> a, View v, int positon, long id) {
// TODO Auto-generated method stub
}
}
MyAdapter.java
package com.sagar.resmenu;
import java.util.ArrayList;
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.CheckBox;
import android.widget.EditText;
import android.widget.TextSwitcher;
import android.widget.TextView;
public class MyAdapter extends BaseAdapter implements OnClickListener{
private LayoutInflater inflater;
private ArrayList<String> data;
VegmenuActivity m;
private ArrayList<Integer> counter;
public MyAdapter(Context context, ArrayList<String> data,ArrayList<Integer> counter) {
// TODO Auto-generated constructor stub
super();
// Caches the LayoutInflater for quicker use
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Sets the events data
this.data= data;
this.counter=counter;
}
public int getCount() {
return this.data.size();
//return this.counter.size();
}
public String getItem(int position) throws IndexOutOfBoundsException{
return null;
}
public long getItemId(int position) throws IndexOutOfBoundsException{
return 0;
}
public int getViewTypeCount(){
return 1;
}
public static class ViewHolder
{
TextView items_name;
CheckBox items_check ;
Button items_plus_button;
Button items_minus_button;
EditText plates;
}
public View getView(int position, View convertView, ViewGroup parent){
//String myText = getItem(position);
ViewHolder holder;
if(convertView == null){ // If the View is not cached
// Inflates the Common View from XML file
holder = new ViewHolder();
convertView = this.inflater.inflate(R.layout.items,parent,false);
holder.items_name = (TextView) convertView.findViewById(R.id.items_name);
holder.plates = (EditText) convertView.findViewById(R.id.items_plates);
holder.items_check = (CheckBox) convertView.findViewById(R.id.items_check);
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
holder.items_name.setText(data.get(position));
holder.plates.setText(String.valueOf(counter.get(position)));
return convertView;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
when I need check boxes inside listview, I often code as following:
MyAdapter.java:
- Declare an boolean array to mark which item is checked/unchecked:
....
boolean[] checked;
...
inside constructor:
checked = new boolean[data.size()];
- Inside getView()
{
.....
holder.items_check.setChecked(checked[position]);
holder.items_check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checked[position] = isChecked;
}
});
.....
- And method to get all checked items:
boolean[] getCheckedItems() {
return checked;
}
That's !
Could it be that your getItem and getItemId only return null and 1? These methods need to return the correct data for this to work I believe. getItem would need to be:
String getItem(int position)
{
return data.get(position);
}
and getItemId would simply return position instead of 0:
String getItemId(int position)
{
return position;
}