How to separate ImageView from adapter of ListView - android

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>

Related

How to add a new EditText with separate row in a ListView

I have 24 EditTexts and I want to have one EditText in each row.
Note: this code is working properly, but I want to add one EditText in one row.
I want to add one EditText per row.
Means I want to set 24 EditTexts in 24 separate rows, not 24 EditText in one row.
This is lyt_listview_activity.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" >
<ListView
android:id="#+id/listViewMain"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
And this is-lyt_listview_list.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:background="#android:color/white"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:textColor="#android:color/black"
android:layout_height="wrap_content"
android:text="15dp" />
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:ems="10" >
<requestFocus />
</EditText>
</LinearLayout>
This is -ListviewActivity.java
package com.example.testlistview;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class ListviewActivity extends Activity {
private String[] arrText =
new String[]{"Text1","Text2","Text3","Text4"
,"Text5","Text6","Text7","Text8","Text9","Text10"
,"Text11","Text12","Text13","Text14","Text15"
,"Text16","Text17","Text18","Text19","Text20"
,"Text21","Text22","Text23","Text24"};
private String[] arrTemp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.lyt_listview_activity) ;
arrTemp = new String[arrText.length];
MyListAdapter myListAdapter = new MyListAdapter();
ListView listView = (ListView) findViewById(R.id.listViewMain);
listView.setAdapter(myListAdapter);
}
private class MyListAdapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
if(arrText != null && arrText.length != 0){
return arrText.length;
}
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrText[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//ViewHolder holder = null;
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = ListviewActivity.this.getLayoutInflater();
convertView = inflater.inflate(R.layout.lyt_listview_list, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.textView1);
holder.editText1 = (EditText) convertView.findViewById(R.id.editText1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.ref = position;
holder.textView1.setText(arrText[position]);
holder.editText1.setText(arrTemp[position]);
holder.editText1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#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
arrTemp[holder.ref] = arg0.toString();
}
});
return convertView;
}
private class ViewHolder {
TextView textView1;
EditText editText1;
int ref;
}
}
}
In lyt_listview_list.xml you only have one EditText.
Those are your rows, and therefore, there's only one EditText (and a TextView) in each row
How many rows you see is determined by getCount(), and that's returning arrText.length, or 24.
As far as "adding another row". You can't add anything to an array. You need to use an Arraylist in your adapter. In which case, you'd likely want ArrayAdapter and not BaseAdapter

AndroidRuntime: FATAL EXCEPTION: main id is not going

I was trying to practice to use GridView in Android Studio, I don't know why I keep getting this exception.
Here is the code of my main class.
package com.example.chetam.gokalsapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
public class Products extends Activity {
GridView grid;
String[] web = {
"Google",
"Github",
"Instagram",
"Facebook",
"Flickr",
"Pinterest",
"Quora",
"Twitter",
"Vimeo",
"WordPress",
"Youtube",
"Stumbleupon",
"SoundCloud",
"Reddit",
"Blogger"
} ;
int[] imageId = {
R.drawable.v,
R.drawable.img,
R.drawable.img1,
R.drawable.img2,
R.drawable.img3,
R.drawable.v,
R.drawable.img,
R.drawable.img1,
R.drawable.img2,
R.drawable.img3,
R.drawable.v,
R.drawable.img,
R.drawable.img1,
R.drawable.img2,
R.drawable.img3
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_products);
grid=(GridView)findViewById(R.id.grid);
CustomGrid adapter = new CustomGrid(Products.this, web, imageId);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(Products.this, "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();
}
});
}
}
Here is the code of my main XML file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.chetam.gokalsapp.Products">
<GridView
android:numColumns="auto_fit"
android:gravity="center"
android:columnWidth="100dp"
android:stretchMode="columnWidth"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/grid"
/>
</RelativeLayout>
Here is my 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="match_parent"
android:padding="5dp"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:id="#+id/grid_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="15dp">
</ImageView>
<TextView
android:id="#+id/grid_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textSize="12sp" >
</TextView>
</LinearLayout>
here is my adapter class
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 CustomGrid extends BaseAdapter{
private Context mContext;
private final String[] web;
private final int[] Imageid;
public CustomGrid(Context c,String[] web,int[] Imageid ) {
mContext = c;
this.Imageid = Imageid;
this.web = web;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return web.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8,8,8,8);
textView.setText(web[position]);
imageView.setImageResource(Imageid[position]);
}
else
{
grid = (View) convertView;
}
return grid;
}
}
Replace grid onClickListener with:
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(Products.this, "You Clicked at " +web[position], Toast.LENGTH_SHORT).show();
}
});
You are using an integer variable for the position of the String array. If you had '+ position' because you wanted one number higher than the position, then the correct syntax is:
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(Products.this, "You Clicked at " +web[position + 1], Toast.LENGTH_SHORT).show();
}
});

GridView and ImageButton Weird issue

Hi all I have custom grid view with imageButton and textView as follows
Here i have used imageButton.. The problem is the grid is not clickable.. But if i use here imageView it works fine but UI is not appropriate.
Here is my layout
<?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"
android:gravity="center"
android:padding="5dp"
>
<ImageButton
android:id="#+id/profilePic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/newlocation"
android:background="#drawable/btnbackground"
/>
<TextView
android:id="#+id/SpeakerName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="15sp"
android:text="Some Speaker"
/>
Here is my adapter
package com.tt.cc;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class SavedConferencesGridAdapter extends ArrayAdapter<String>{
Context mContext;
List<String> confernceList;
public SavedConferencesGridAdapter(Context context, int textViewResourceId, List<String> confernceList)
{
super(context,textViewResourceId,confernceList);
this.confernceList = confernceList;
this.mContext = context;
Log.e("TAG", confernceList.size()+"");
}
int[] picIds = new int[] { R.drawable.newschedule,R.drawable.newexhibitors,
R.drawable.newsponsers, R.drawable.newlocation,
R.drawable.newfavourites, R.drawable.newreminder,R.drawable.info,R.drawable.info,R.drawable.info,R.drawable.info,R.drawable.info,R.drawable.info };
#Override
public int getCount() {
// TODO Auto-generated method stub
return confernceList.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v;
if(convertView==null){
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.entity, null);
TextView tv = (TextView)v.findViewById(R.id.SpeakerName);
tv.setText("tt");
/*ImageView iv = (ImageView) v.findViewById(R.id.profilePic);
iv.setImageResource(picIds[position]);*/
}
else
{
v = convertView;
}
return v;
}
}
and here is my activity
public class SavedConferencesActivity extends Activity{
GridView confereneceGridView;
ArrayAdapter<String> conferneceAdapter;
Button btnUpdate;
List<String> conferenceList;
TextView txtHeading;
Boolean result = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected void onStart() {
super.onStart();
setContentView(R.layout.homegridlayout);
initialize();
confereneceGridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(SavedConferencesActivity.this, conferenceList.get(position)+"", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
conferneceAdapter = new SavedConferencesGridAdapter(this, android.R.layout.simple_list_item_1, conferenceList);
confereneceGridView.setAdapter(conferneceAdapter);
}
private void initialize() {
confereneceGridView = (GridView) findViewById(R.id.gridOfConference);
btnUpdate = (Button) findViewById(R.id.btnUpdate);
txtHeading = (TextView) findViewById(R.id.txtTag);
conferenceList = new ArrayList<String>();
conferenceList.add("AA");
conferenceList.add("BB");
conferenceList.add("CC");
if (conferenceList.size() == 0)
txtHeading.setText("No conferences saved");
else
txtHeading.setText("Selected Conferences");
}
}
Please help me in solving this problem. Or if any alternative available..
Simple. Provide this attribute for the ImageButton ,
android:focusable="false"
This problem usually occurs when there is a focussable element in the Grid.(Eg:Buttons, ImageButton etc).
Reason of this ImageButton is by Default is clickable and focusable, so Focus and click event never goes to ItemView.
Set Properties
android:focusable-"false"
and
android:clickable="false"
Your item's Layout should be:
<LinearLayout ...
android:descendantFocusability="blocksDescendants">
<ImageButton ...
android:focusable="false"
android:focusableInTouchMode="false"/>
</LinearLayout>
Don't forget setOnClickListener for ImageButton in Adapter.
in your adapter class,
before you return the view "v", add the "onClickListener" to "v"
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, position, Toast.LENGTH_SHORT).show();
}
});

Pass Data form listview to another activity in android?

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);
}
});

Change the Gallery View for the button clicked in android

I have three buttons Image , Videos , Audios. I want to change the views in gallery with the audios , videos , images resources when corresponding button clicked so that only related image of the buttons appear in gallery.
My code is here:
XML layout:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Audios" >
</Button>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Videos" >
</Button>
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Images" >
</Button>
</LinearLayout>
<Gallery
android:id="#+id/Gallery01"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</Gallery>
</LinearLayout>
<ImageView
android:id="#+id/ImageView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ImageView>
Java file:
public class GalleryView extends Activity {
Integer[] pics = {
R.drawable.cloudy,
R.drawable.hazy,
R.drawable.mostlycloudyday,
R.drawable.partlycloud,
R.drawable.sunny,
R.drawable.sunrain,
R.drawable.thunderstorm,
R.drawable.weathercloudy,
};
ImageView imageView;
Button mAudio;
Button mVideo;
Button mImages;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAudio=(Button) findViewById(R.id.button1);
Gallery ga = (Gallery)findViewById(R.id.Gallery01);
ga.setAdapter(new ImageAdapter(this));
imageView = (ImageView)findViewById(R.id.ImageView01);
ga.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
Toast.makeText(getBaseContext(),
"You have selected picture " + (pos+1) + "of Gallery",
Toast.LENGTH_SHORT).show();
imageView.setImageResource(pics[pos]);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context ctx;
int imageBackground;
public ImageAdapter(Context c) {
ctx = c;
TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
imageBackground = ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
ta.recycle();
}
#Override
public int getCount() {
return pics.length;
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
ImageView iv = new ImageView(ctx);
iv.setImageResource(pics[arg0]);
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setLayoutParams(new Gallery.LayoutParams(150,120));
iv.setBackgroundResource(imageBackground);
return iv;
}
}
}
Anybody please help me with this,
Thanks.
For the changing the image in gallery, you must change the Resources image id in array. e.g change image for videos in int[] video_pics and so on.
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
public class GalleryView extends Activity implements OnClickListener {
int[] image_pics = { R.drawable.cloudy, R.drawable.hazy, R.drawable.mostlycloudyday, R.drawable.partlycloud,
R.drawable.sunny, R.drawable.sunrain, R.drawable.thunderstorm, R.drawable.weathercloudy, };
int[] video_pics = { R.drawable.cloudy, R.drawable.hazy, R.drawable.mostlycloudyday, R.drawable.partlycloud,
R.drawable.sunny, R.drawable.sunrain, R.drawable.thunderstorm, R.drawable.weathercloudy, };
int[] audio_pics = { R.drawable.cloudy, R.drawable.hazy, R.drawable.mostlycloudyday, R.drawable.partlycloud,
R.drawable.sunny, R.drawable.sunrain, R.drawable.thunderstorm, R.drawable.weathercloudy, };
ImageView imageView;
Button mAudio;
Button mVideo;
Button mImages;
ImageAdapter galleryAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAudio = (Button) findViewById(R.id.button1);
mVideo = (Button) findViewById(R.id.button2);
mImages = (Button) findViewById(R.id.button3);
mAudio.setOnClickListener(this);
mVideo.setOnClickListener(this);
mImages.setOnClickListener(this);
Gallery ga = (Gallery) findViewById(R.id.Gallery01);
galleryAdapter = new ImageAdapter(this);
galleryAdapter.setResourseArray(image_pics);
ga.setAdapter(galleryAdapter);
imageView = (ImageView) findViewById(R.id.ImageView01);
ga.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
Toast.makeText(getBaseContext(), "You have selected picture " + (pos + 1) + "of Gallery", Toast.LENGTH_SHORT)
.show();
imageView.setImageResource(pics[pos]);
}
});
}
#Override
public void onClick(View view) {
if (view == mAudio) {
if (galleryAdapter != null) {
galleryAdapter.setResourseArray(audio_pics);
galleryAdapter.notifyDataSetChanged();
}
} else if (view == mVideo) {
if (galleryAdapter != null) {
galleryAdapter.setResourseArray(video_pics);
galleryAdapter.notifyDataSetChanged();
}
} else if (view == mImages) {
if (galleryAdapter != null) {
galleryAdapter.setResourseArray(image_pics);
galleryAdapter.notifyDataSetChanged();
}
}
}
public class ImageAdapter extends BaseAdapter {
private Context ctx;
int imageBackground;
private int[] resourseArray = null;
public ImageAdapter(Context c) {
ctx = c;
TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
imageBackground = ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
ta.recycle();
}
#Override
public int getCount() {
return resourseArray.length;
}
public int[] getResourseArray() {
return resourseArray;
}
public void setResourseArray(int[] resourseArray) {
this.resourseArray = resourseArray;
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View arg1, ViewGroup arg2) {
ImageView iv = new ImageView(ctx);
iv.setImageResource(resourseArray[position]);
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setLayoutParams(new Gallery.LayoutParams(150, 120));
iv.setBackgroundResource(imageBackground);
return iv;
}
}
}
Button.onClickEvent -> ga.setSelection(int postion);

Categories

Resources