Gridview Listener is not working - android

In my application, I have grid view and I wrote a listener to get position of clicked item in the grid view. I tried many ways to solve it but it is noting working.I'm looking solutions or help I have checked everything but i'm not able to clear it.I don't know where I have done mistake. anyone help me out with is.
rowitems 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" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:background="#drawable/customborder"
android:gravity="center_vertical"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
<ImageView
android:id="#+id/product_img"
android:layout_width="350dp"
android:layout_height="150dp"
android:layout_alignParentLeft="true"
android:src="#drawable/ic_launcher"
android:focusable="false"
android:focusableInTouchMode="false"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_weight="0.5"
android:background="#D7D7D7" >
<TextView
android:id="#+id/product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="37dp"
android:text="#string/pname"
android:textAppearance="?android:attr/textAppearanceMedium"
android:focusable="false"
android:focusableInTouchMode="false"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="75dp" >
<Button
android:id="#+id/product_decribe_cart"
style="?android:attr/buttonStyleSmall"
android:layout_width="75dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="46dp"
android:background="#D41A37"
android:text="#string/cart"
android:textColor="#android:color/white"
android:textSize="8dp"
android:focusable="false"
android:focusableInTouchMode="false"/>
<TextView
android:id="#+id/product_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="40dp"
android:text="#string/rate"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#D41A37"
android:focusable="false"
android:focusableInTouchMode="false"/>
</RelativeLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="262dp"
android:layout_height="113dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="10dp"
android:background="#drawable/customborder" >
<TextView
android:id="#+id/product_detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:text="Product details"
android:textAppearance="?android:attr/textAppearanceMedium"
android:focusable="false"
android:focusableInTouchMode="false"/>
</RelativeLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class ProductActivity extends Activity
{
JSONArray results;
JSONObject jobj;
CustomProdAdapter adapter1;
ArrayList<String> a1,a2,a3,a4;
ArrayList<String> pname=new ArrayList<String>();
ArrayList<String> productdescription=new ArrayList<String>();
ArrayList<String> pimage=new ArrayList<String>();
ArrayList<String> pprice=new ArrayList<String>();
Button add;
String pid;
GridView gView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.product_activity);
a1=new ArrayList<String>();
a2=new ArrayList<String>();
a3=new ArrayList<String>();
a4=new ArrayList<String>();
Intent in=getIntent();
pid=in.getStringExtra("Dialoog");
System.out.println("productid"+pid);
gView = (GridView)findViewById(R.id.pa_grid);
/* gView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
System.out.println("inside listener");
}
});*/
new Producttask().execute();
}
private class Producttask extends AsyncTask<String, String, JSONObject>
{
private ProgressDialog pDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(ProductActivity.this);
pDialog.setMessage("Loading Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args)
{
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl("my link");
return json;
}
#Override
protected void onPostExecute(JSONObject json)
{
System.out.println("---------------return product list json------------"+json);
pDialog.dismiss();
try
{
jobj=json.getJSONObject("response");
// Getting Array of Contacts
results = jobj.getJSONArray("obejects");
System.out.println("In product Activity after JSON");
// looping through All Contacts
for(int i = 0; i < results.length(); i++)
{
JSONObject c = results.getJSONObject(i);
pname.add(c.getString("product_name"));
pimage.add(c.getString("product_image"));
pprice.add(c.getString("product_price"));
productdescription.add(c.getString("Description"));
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter1 = new CustomProdAdapter(getApplicationContext(), R.layout.product_describe, pname, pimage,productdescription,pprice);
gView.setAdapter(adapter1);
gView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
System.out.println("outside on click"+position);
}
});
/*gv=(GridView)findViewById(R.id.product_decribe_cart);
gv.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent(ProductActivity.this,product_details.class);
startActivity(i);
}
});
*/ }
}
}

Grid view listner set in oncreate method
new Producttask().execute();
gView = (GridView)findViewById(R.id.pa_grid);
gView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
System.out.println("outside on click"+position);
}
});
Or set you click listener on row , like that
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
View row=convertView;
ViewHolder vh;
if(row==null)
{
row=inflater.inflate(R.layout.custom_product_activity, parent, false);
vh=new ViewHolder();
vh.pname=(TextView)row.findViewById(R.id.product_name);
vh.image1=(ImageView) row.findViewById(R.id.imageView1);
row.setTag(vh);
}
else
{
vh = (ViewHolder) row.getTag();
row=convertView;
}
vh.pname.setText(c_pname.get(position));
iloader.DisplayImage(c_pimage.get(position), vh.image1);
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
System.out.println("outside on click"+"position");
}
});
return row;
}

Related

getView() is not called in custom list adapter?

This is my homepage.xml - where list view is placed:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:orientation="vertical"
tools:context="com.andapps.azaz.e_recommender.HomePage">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Category:"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
/>
<Spinner
android:id="#+id/spcategorieshomepage"
android:layout_width="match_parent"
android:layout_height="35sp"
android:layout_marginRight="14sp"
android:spinnerMode="dropdown"
android:textColor="#color/textColor"
>
</Spinner>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/llhome"
android:gravity="center"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp">
<ListView
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
</LinearLayout>
</LinearLayout>
And also my customlist.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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Product ID:"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
android:id="#+id/tvproductid"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Product Name:"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
android:id="#+id/tvproductname"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Product Rating:"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
/>
<RatingBar
android:id="#+id/ratingBar"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:max="5"
android:numStars="5" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold|italic"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
android:textColor="#color/textColor"
android:id="#+id/tvproductdesc"
/>
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:id="#+id/imageView"
android:layout_marginLeft="15sp"
android:layout_marginRight="14sp"
/>
</LinearLayout>
My homepage.java contains code which is using AsyncTask to consume REST API and fill arrays of data and send it to customAdapter.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
lv=(ListView) findViewById(R.id.listView);
Bundle emailbundle=getIntent().getExtras();
email=emailbundle.get("email").toString();
initializer();
addingItemstoSpinner();
}
protected void onPostExecute(String result) {
try {
jsonArray = new JSONArray(result);
} catch (JSONException e) {
e.printStackTrace();
}
len= jsonArray.length();
pdLoading.dismiss();
if (len != 0) {
try {
String [] productIDListArr= new String[len];
String [] productNameListArr= new String[len];
String [] productDescListArr= new String[len];
String [] productImagesArr= new String[len];
String [] productStarsArr= new String[len];
for (int i=0;i<len;i++)
{
objectInArray = jsonArray.getJSONObject(i);
productIDListArr[i]=(objectInArray.getString("productId"));
productNameListArr[i]=(objectInArray.getString("productName"));
productDescListArr[i]=(objectInArray.getString("stars"));
productImagesArr[i]=(objectInArray.getString("productId"));
productStarsArr[i]=(objectInArray.getString("stars")+" out of 5");
if(i==len-1)
{
createdAt=objectInArray.getString("createdAt");
}
}
lv.setAdapter(new CustomAdapter(HomePage.this, productIDListArr,productNameListArr,productDescListArr,productImagesArr,productStarsArr,email));
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Server is down please try again later", Toast.LENGTH_LONG).show();
}
My customAdapter.java is
package com.andapps.azaz.e_recommender;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
/**
* Created by M.Azaz on 30-Mar-17.
*/
public class CustomAdapter extends BaseAdapter {
String [] productIDListArr,productNameListArr,productDescListArr,productImagesArr,productStarsArr;
Context context;
String email;
private static LayoutInflater inflater=null;
public CustomAdapter(HomePage homePage, String[] productIDList, String[] productNameList, String[] productDescList, String[] productImages, String[] productStars,String emailMain) {
// TODO Auto-generated constructor stub
productIDListArr=productIDList;
productNameListArr=productNameList;
productDescListArr=productDescList;
productImagesArr=productImages;
productStarsArr=productStars;
context=homePage;
email=emailMain;
inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return productIDListArr.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return productIDListArr[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tvproductname, tvproductid, tvproductdesc;
ImageView imageView;
RatingBar ratingBar;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.activity_custom_list, null);
holder.tvproductname=(TextView) rowView.findViewById(R.id.tvproductname);
holder.tvproductid=(TextView) rowView.findViewById(R.id.tvproductid);
holder.tvproductdesc=(TextView) rowView.findViewById(R.id.tvproductdesc);
holder.imageView=(ImageView) rowView.findViewById(R.id.imageView);
holder.ratingBar=(RatingBar) rowView.findViewById(R.id.ratingBar);
holder.tvproductname.setText(productNameListArr[position]);
holder.tvproductid.setText(productIDListArr[position]);
holder.tvproductdesc.setText(productDescListArr[position]);
holder.ratingBar.setRating(Integer.parseInt(productStarsArr[position]));
Picasso.with(context).load(context.getString(R.string.imageip) + productImagesArr[position]+".jpg").into(holder.imageView);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+productIDListArr[position], Toast.LENGTH_LONG).show();
Intent intent = new Intent("com.andapps.azaz.e_recommender.RATINGS");
intent.putExtra("tag",productIDListArr[position]);
intent.putExtra("email", email);
context.startActivity(intent);
}
});
return rowView;
}
}
But when I run the code, it actually calls customAdapter.java but right after calling getCount() from customAdapter Its not calling getView and the application terminates.
One more thing... how can I update more items into existing list?
You app may crash in getCount method when productIDListArr is null. So add if condition in your getCount method before returning count.
For example :
public int getCount(){
if(productIDListArr==null){
return 0;
}else{
return productIDListArr.length;
}
}
Tips : Create a class for holding your response data and pass the list of that model class to the adapter and each time when there is any change in your data update that list and call notify method of adapter.
For example :
Class Item{
public String productIDListArr;
public String productNameListArr;
public String productDescListArr;
public String productImagesArr;
public String productStarsArr;
}
ArrayList<Item> items=new ArrayList<Item>();
for (int i=0;i<len;i++)
{
objectInArray = jsonArray.getJSONObject(i);
Item item=new Item();
item.productIDListArr=(objectInArray.getString("productId"));
.......
}
CustomAdapter extend BaseAdapter{
ArrayList<Item> items;
public CustomAdapter(ArrayList<Item> items){
this.items=items;
}
public int getCount(){
return items==null?0:items.size()
}

SetEmptyView not showing text and button when list view empty

This is my actual code
I'm already defined setEmptyview on AsyncTask
DepartureFragmentInter.java
package com.trust.flightboard.fragment;
import java.util.ArrayList;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.trust.flightboard.R;
import com.trust.flightboard.adapter.DepartureAdapter;
import com.trust.flightboard.http.DepartureConnection;
import com.trust.flightboard.model.Departure;
import com.trust.flightboard.ui.DepartureDetailActivity;
public class DepartureFragmentInter extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
private DepartureAdapter mAdapter;
private ListView mListview;
private TextView mDate,flight,destination,time,gate;
ArrayList<Departure> dList = new ArrayList<Departure>();
private static int REFRESH_TIME_IN_SECONDS = 5;
public SwipeRefreshLayout swipeRefreshLayout;
DepartureConnection rest;
String airport;
public static DepartureFragmentInter newInstance() {
return new DepartureFragmentInter();
}
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,Bundle savedInstanceState) {
View viewroot = inflater.inflate(R.layout.departure_activity,container, false);
mListview = (ListView) viewroot.findViewById(R.id.listview_maskapai);
mDate = (TextView) viewroot.findViewById(R.id.datetime);
swipeRefreshLayout = (SwipeRefreshLayout);
viewroot.findViewById(R.id.lySwipeRefresh);
flight = (TextView) viewroot.findViewById(R.id.codejudul);
destination = (TextView) viewroot.findViewById(R.id.Bandarajudul);
time = (TextView) viewroot.findViewById(R.id.Timejudul);
gate = (TextView) viewroot.findViewById(R.id.Gatejudul);
airport = getArguments().getString("airport");
Toast.makeText(getActivity(), airport, Toast.LENGTH_LONG).show();
Typeface typeFace =
Typeface.createFromAsset(getActivity().getAssets(),
"HELVETICANEUELTPRO-BD_0.OTF");
setTypeFace(typeFace);
mAdapter = new DepartureAdapter(getActivity());
rest = new DepartureConnection(getActivity());
mListview.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int
scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
boolean enable = false;
if (mListview != null && mListview.getChildCount() > 0) {
// check if the first item of the list is visible
boolean firstItemVisible =
mListview.getFirstVisiblePosition() == 0;
// check if the top of the first item is visible
boolean topOfFirstItemVisible =
mListview.getChildAt(0).getTop() == 0;
// enabling or disabling the refresh layout
enable = firstItemVisible && topOfFirstItemVisible;
}
swipeRefreshLayout.setEnabled(enable);
}
});
initUI();
new setList().execute();
mListview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
Intent in = new
Intent(getActivity(),DepartureDetailActivity.class);
in.putExtra("code", dList.get(position).code_departure);
in.putExtra("airport",dList.get(position).airport);
in.putExtra("time",dList.get(position).time);
in.putExtra("gate",dList.get(position).gate);
in.putExtra("city",dList.get(position).airportcity);
startActivityForResult(in, 100);
getActivity().overridePendingTransition(R.anim.left_in,
R.anim.left_out);
}
});
return viewroot;
}
class setList extends AsyncTask<String, String, String>{
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String result = "error";
try {
dList = rest.getAirport(airport,"Domestic");
result = "Ok";
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
mAdapter.setArray(dList);
mListview.setEmptyView(getActivity().
findViewById(R.id.emptyElement));
mListview.setAdapter(mAdapter);
}
}
private void initUI() {
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorScheme(android.R.color.black,
android.R.color.white,
android.R.color.black, android.R.color.white);
}
#Override
public void onRefresh() {
// TODO Auto-generated method stub
Log.d("cek", "onRefresh SwipeRefreshLayout");
new setList().execute();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
stopSwipeRefresh();
}
}, REFRESH_TIME_IN_SECONDS * 1000);
}
private void stopSwipeRefresh() {
swipeRefreshLayout.setRefreshing(false);
}
class mDateSetListener implements DatePickerDialog.OnDateSetListener {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
// getCalender();
int mYear = year;
int mMonth = monthOfYear;
int mDay = dayOfMonth;
}
}
private void setTypeFace(Typeface typeFace) {
flight.setTypeface(typeFace);
destination.setTypeface(typeFace);
time.setTypeface(typeFace);
gate.setTypeface(typeFace);
}
}
and this my departure_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_frame2"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg" >
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/lySwipeRefresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/datetime"
android:layout_below="#+id/rel1" >
<ListView
android:id="#+id/listview_maskapai"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/bg"
android:cacheColorHint="#android:color/transparent"
android:divider="#color/bg_separator"
android:dividerHeight="1dp"
android:paddingLeft="8dp"
android:paddingRight="8dp" />
</android.support.v4.widget.SwipeRefreshLayout>
<RelativeLayout
android:id="#+id/rel1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/text_color_white"
android:paddingBottom="#dimen/margin_medium" >
<LinearLayout
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/margin_medium"
android:layout_marginRight="#dimen/margin_medium"
android:layout_marginTop="#dimen/margin_small"
android:orientation="horizontal"
android:paddingLeft="8dp"
android:paddingRight="8dp" >
<TextView
android:id="#+id/codejudul"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="15"
android:text="FLIGHT"
android:textColor="#59000000"
android:textSize="#dimen/text_size_medium" />
<TextView
android:id="#+id/Bandarajudul"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="25"
android:text="DEST"
android:textColor="#59000000"
android:textSize="#dimen/text_size_medium" />
<TextView
android:id="#+id/Timejudul"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="13"
android:text="TIME"
android:textColor="#59000000"
android:textSize="#dimen/text_size_medium" />
<TextView
android:id="#+id/Gatejudul"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="9"
android:text="GATE"
android:textColor="#59000000"
android:textSize="#dimen/text_size_medium" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/rel2"
android:layout_width="match_parent"
android:layout_height="8dp"
android:layout_below="#+id/rel1"
android:background="#drawable/ic_shd_tab" >
</RelativeLayout>
<FrameLayout
android:id="#+id/emptyElement"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/emptytext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/emptytext"
android:textColor="#color/text_color_white" />
<Button
android:id="#+id/emptybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/emptytext"
android:layout_centerHorizontal="true"
android:text="RELOAD" />
</RelativeLayout>
</FrameLayout>
</RelativeLayout>
</FrameLayout>
when I load ListView contain zero record empty list view not showed
Any help will appreciate thanks
Well, i wrote simple it will help you
Override onContentChanged() method
Like below:
#Override
public void onContentChanged() {
super.onContentChanged();
// write you code here, when list view empty.
}
Change the following:
mListview.setEmptyView(getActivity().
findViewById(R.id.emptyElement));
mListview.setAdapter(mAdapter);
to
mListview.setAdapter(mAdapter);
mListview.setEmptyView(getActivity(). findViewById(R.id.emptyElement));
Bind the listview first and then set the empty view.
Place the
mListview.setEmptyView(getActivity(). findViewById(R.id.emptyElement));
below
mListview.setAdapter(mAdapter);

onListItemClick is not working for listview?

Hi onListItemClick for listview is not working. Here i am fetching datas from SQLite using AsyncTask and displaying it in a list view. And i wants to do some actions when a list in a listview has clicked. But the click is not happening. I had tried a lot for this. Please help me.
Here is my code
package com.applexus.app.mobilesalesorder;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
import com.applexus.app.library.sql.SqlConnector;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class SoldToPartiesList extends ListActivity {
private ArrayList<String> data = new ArrayList<String>();
private ArrayList<String> idk = new ArrayList<String>();
private ArrayList<String> name1 = new ArrayList<String>();
private ArrayList<String> inco1 = new ArrayList<String>();
private ArrayList<String> email = new ArrayList<String>();
private ArrayList<String> tel = new ArrayList<String>();
private ArrayList<String> vwerk = new ArrayList<String>();
private SharedPreferences prefs;
private String prefNamesalesorgid = "salesorgid";
private String prefNamedistchnlid = "distchnlid";
private String prefNamedivid = "divid";
private String prefName = "mso";
private TextView titlename;
private static class ViewHolder {
TextView tvlist;
TextView tvlistsmall;
}
private class EfficientAdapter extends BaseAdapter {
private Context context;
LayoutInflater inflater;
public EfficientAdapter(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
final int place = position;
if (convertView == null) {
convertView = inflater.inflate(R.layout.listso, null);
holder = new ViewHolder();
holder.tvlist = (TextView) convertView
.findViewById(R.id.textViewlist);
holder.tvlistsmall = (TextView) convertView
.findViewById(R.id.textView1);
convertView.setTag(holder);
//
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvlist.setText(idk.get(position));
holder.tvlistsmall.setText(data.get(position));
return convertView;
}
}
Map<String, String> map = new TreeMap<String, String>();
SqlConnector con;
String salorg;
String distch;
String division;
Context co = this;
Boolean searchable=false;
TextView tvmc;
TextView tvmn;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.materiallist);
titlename = (TextView) findViewById(R.id.textViewtitle);
titlename.setText(R.string.soldtoparties);
tvmc=(TextView)findViewById(R.id.textViewmc);
tvmn=(TextView)findViewById(R.id.textViewmn);
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
salorg = (prefs.getString(prefNamesalesorgid, ""));
distch = (prefs.getString(prefNamedistchnlid, ""));
division=(prefs.getString(prefNamedivid, ""));
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { null });
// ListView lv=(ListView)findViewById(android.R.id.list);
// lv.setOnItemSelectedListener(new )
}
EditText es;
LinearLayout ls;
LinearLayout mc;
LinearLayout mn;
Boolean searchFlag = false;
String search;
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
es = (EditText) findViewById(R.id.editTextSearch);
ls = (LinearLayout) findViewById(R.id.linearLayoutsearch);
}
private class DownloadWebPageTasksearch extends
AsyncTask<String, Void, String> {
Cursor c;
ProgressBar pb;
#Override
protected String doInBackground(String... urls) {
con = new SqlConnector(co);
try {
if (searchFlag) {
c = con.select("select Kunnr,Name,Name1,Inco1,Vwerk,SmtpAddr,Telf1 from tb_soldtoparties where salesorg='"
+ salorg + "' and channel='" + distch + "' and Name like '%"+search+"%' and division='"+division+"';");
} else {
c = con.select("select Kunnr,Name,Name1,Inco1,Vwerk,SmtpAddr,Telf1 from tb_soldtoparties where salesorg='"
+ salorg + "' and channel='" + distch + "' and Kunnr like '%"+search+"%' and division='"+division+"';");
}
} catch (Exception e) {
e.printStackTrace();
}
int in = c.getCount();
c.moveToFirst();
for (int i = 0; i < in; i++) {
idk.add(c.getString(0));
data.add(c.getString(1));
name1.add(c.getString(2));
inco1.add(c.getString(3));
vwerk.add(c.getString(4));
email.add(c.getString(5));
tel.add(c.getString(6));
c.moveToNext();
}
return null;
}
#Override
protected void onPostExecute(String result) {
setListAdapter(new EfficientAdapter(SoldToPartiesList.this));
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
searchable=true;
con.close();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
idk.clear();
data.clear();
name1.clear();
inco1.clear();
vwerk.clear();
email.clear();
tel.clear();
setListAdapter(new EfficientAdapter(SoldToPartiesList.this));
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.VISIBLE);
searchable=false;
}
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
Cursor c;
ProgressBar pb;
#Override
protected String doInBackground(String... urls) {
con = new SqlConnector(co);
try {
c = con.select("select Kunnr,Name,Name1,Inco1,Vwerk,SmtpAddr,Telf1 from tb_soldtoparties where salesorg='"
+ salorg + "' and channel='" + distch + "' and division='"+division+"';");
} catch (Exception e) {
e.printStackTrace();
}
int in = c.getCount();
c.moveToFirst();
Log.d("size", "" + in + "");
for (int i = 0; i < in; i++) {
idk.add(c.getString(0));
data.add(c.getString(1));
name1.add(c.getString(2));
inco1.add(c.getString(3));
vwerk.add(c.getString(4));
email.add(c.getString(5));
tel.add(c.getString(6));
c.moveToNext();
}
return null;
}
#Override
protected void onPostExecute(String result) {
setListAdapter(new EfficientAdapter(SoldToPartiesList.this));
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
searchable=true;
con.close();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
idk.clear();
data.clear();
name1.clear();
inco1.clear();
vwerk.clear();
email.clear();
tel.clear();
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.VISIBLE);
searchable=false;
}
}
// class ClickOnList implements OnItemClickListener
// {
// #Override
// public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
// long arg3) {
// Log.d("ListView", "Position"+arg2);
//
// }
//
// }
// public OnItemClickListener theListListener = new OnItemClickListener() {
//
// public void onItemClick(android.widget.AdapterView<?> parent, View v, int position, long id) {
// Log.d("position",position+"");
// } };
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
int place=position;
Log.d("position",position+"");
}
}
And Layout code is materiallist.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:background="#color/bluebg"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/bar1"
android:gravity="center_vertical"
android:minHeight="50dp"
android:orientation="horizontal" >
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_margin="5dp"
android:layout_weight="1"
android:gravity="center_vertical|left" >
<TextView
android:id="#+id/textViewtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:shadowColor="#000000"
android:shadowDx="1"
android:shadowDy="1"
android:shadowRadius="1.5"
android:text="#string/materials"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_margin="5dp"
android:gravity="center" >
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="#+id/linearLayout4"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center" >
<EditText
android:id="#+id/editTextSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:hint="#string/search"
android:imeOptions="actionDone"
android:inputType="textUri" >
</EditText>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayoutsearch"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center" android:clickable="true">
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:src="#drawable/search" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout6"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout7"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/listbg2" >
<LinearLayout
android:id="#+id/linearLayoutmc"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/lbg1"
android:gravity="center" >
<TextView
android:id="#+id/textViewmc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Code"
android:textColor="#color/black" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayoutmn"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/lbg2"
android:gravity="center" >
<TextView
android:id="#+id/textViewmn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Name"
android:textColor="#color/black" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout10"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#color/offwhite" >
</ListView>
</LinearLayout>
</LinearLayout>
And listso3.xml is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/lbg"
android:orientation="vertical"
>
<TextView
android:id="#+id/textViewNamelist3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/black"
android:focusable="false"/>
<TextView
android:id="#+id/textViewKunn2list3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/black"
android:focusable="false"/>
</LinearLayout>
Add below code to your TextView in the XML
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
and try again.
Another simple solution: add android:descendantFocusability="blocksDescendants" to the root viewgroup.
You should add android:focusable="false" for ListView row items to make ListView Clikable. Because the views in the row of ListView gain the focus so ListView is not focusable. So, in your case you can add android:focusable="false" to the TextViews of your ListView row.
I had the same symptoms, and it drove me crazy for a while. Adding android:focusable="false" for the list items as suggested above fixed the problem for me.
But the real issue was that I had set android:textIsSelectable="true" for my list items (in response to a Warning generated by Eclipse); setting android:textIsSelectable="false" fixed the problem for me, and I did not need the android:focusable="false" option at all.
The workaround I found avoid the
AdapterView.OnItemClickListener mMessageClickedHandler=new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
};
on the ListView, but exploit the Adapter constructor that takes a Context as parameter:
myCustomAdapter=new MyCustomAdapter(ActivityName.this,...)
Passing ActivityName.this is possible to cast the Context in the adapter's class as ActivityName in a safe way and use its methods working like callbacks:
((ActivityName)context).activityMethod()
Given that the getView() method of the Adapter class has a position parameter, is possible to pass this value to the activityMethod(int position) in order to know which list item has been pressed into the Activity where the ListView is.
Another solution.
if you have many child-control,and its to trouble to add android:focusable="false" to every child-control,you can add android:descendantFocusability="blocksDescendants" to its parent-control.try it.
I struggled with this for a while - none of the provided solutions worked for me. In the end I found that having a call to getListView() in my onViewCreated() method did the trick, although I have no idea why. This is for a Fragment rather than an Activity; not sure if this makes any difference.
public class NewsListFragment extends ListFragment {
private ListView listView;
...
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
newsListView = getListView();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// this now works as expected
}
}
I was also struggling with this issue and none of the suggested solutions worked. My problem was that I did an override for onViewCreated but didn't call super.onViewCreated(view, savedInstanceState);. Hopefully this will help someone else so they don't spend hours trying to figure out what's going on.
I struggled as I by mistake put android:inputType="textCapWords" with the textbox after removing it it is fixed
Only the line below worked for me:
android:descendantFocusability="blocksDescendants"
The whole list_view_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<!--android:focusableInTouchMode="false"-->
<!--android:focusable="false"-->
<!--android:clickable="false"-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:descendantFocusability="blocksDescendants"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/checkBox_list_view_checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/checkBox_list_view_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
The above is to be used in getView like:
convertView=LayoutInflater.from(getContext())
.inflate(R.layout.list_view_item, parent, false);
`

Listview doesnt fire onItemClickListener Event

i want to place onItemClick listener on my listview...but when i click on listview nothing is happen..
here is my code...can anyone suggest me how can i do this..??
Here is my XML FILE (list.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:background="#drawable/listbg">
<!-- For the Header Part -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="35dip"
android:background="#EE7621">
<Button
android:id="#+id/menuButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/backhome"
>
</Button>
<TextView
android:text="Pantries"
android:layout_height="wrap_content"
android:layout_width="210dip"
android:gravity="center"
android:shadowColor="#3B3B3B"
android:textColor="#FFFFFF"
android:textSize="20dip"
android:textStyle="bold">
</TextView>
<Button
android:id="#+id/allonmap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/allonmap"
>
</Button>
</LinearLayout>
<!-- For the List View -->
<TextView android:text="Total Pantries"
android:id="#+id/totalPantries"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#F2F2F2"
android:background="#B3B3B3">
</TextView>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<ListView
android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<!-- For the Footer Part -->
<RelativeLayout
android:orientation="vertical"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_centerHorizontal="true"
android:gravity="bottom">
<ImageView
android:id="#+id/footerview"
android:src="#drawable/footer"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_gravity="center">
</ImageView>
</RelativeLayout>
</RelativeLayout>
</LinearLayout>
here is my Row.xml file
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<RelativeLayout
android:id="#+id/mainContent"
android:orientation="vertical"
android:layout_width="300dip"
android:layout_height="fill_parent">
<TextView
android:id="#+id/pantryName"
android:layout_marginTop="8dip"
android:layout_marginLeft="10dip"
android:text="name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="16dip"
android:textColor="#00AF33"
android:gravity="center_vertical"
/>
<TextView
android:layout_below="#id/pantryName"
android:textColor="#242424"
android:text="address1"
android:layout_marginTop="8dip"
android:layout_marginLeft="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/pantryAddress1"
/>
<TextView
android:layout_below="#id/pantryAddress1"
android:textColor="#242424"
android:text="address2"
android:layout_marginLeft="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/pantryAddress2"
/>
<Button android:layout_below="#+id/pantryAddress2"
android:layout_width="wrap_content"
android:id="#+id/phbtn"
android:layout_marginLeft="10dip"
android:layout_height="wrap_content"
android:background="#drawable/phonecall"
></Button>
<TextView
android:layout_toRightOf="#id/phbtn"
android:layout_width="fill_parent"
android:layout_below="#id/pantryAddress2"
android:textColor="#242424"
android:layout_marginLeft="10dip"
android:layout_height="wrap_content"
android:id="#+id/pantryPhno"
/>
<TextView
android:layout_below="#id/pantryPhno"
android:textColor="#242424"
android:textSize="10dip"
android:layout_marginLeft="12dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/distTime"
/>
</RelativeLayout>
<Button android:layout_width="wrap_content"
android:background="#drawable/next"
android:layout_marginTop="45dip"
android:layout_marginRight="7dip"
android:layout_alignParentRight="true"
android:id="#+id/nextBtn"
android:layout_height="wrap_content"
></Button>
</RelativeLayout>
here is my java file....
package com.pantylocator;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.ListActivity;
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.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class PantriesListActivity extends ListActivity
{
PantreisInfo parsedPantry;
ImageAdapter m_adapter;
TextView totalPantries;
public Button allOnMap,pantrySelection;
public static ArrayList<PantreisInfo> m_pantries=new ArrayList<PantreisInfo>();
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.m_adapter=new ImageAdapter(this, R.layout.row, m_pantries);
setListAdapter(this.m_adapter);
setContentView(R.layout.list);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
Bundle bundle = this.getIntent().getExtras();
String parseURL = bundle.getString("url");
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int Position,long id)
{
Toast.makeText(getApplicationContext(),"Clicked",Toast.LENGTH_LONG).show();
}
});
parseURL(parseURL);
parsedPantry=PanatriesHandler.getPantries();
PantreisInfo pantry[]=null;
pantry =new PantreisInfo[parsedPantry.getID().size()];
for(int i=0;i<parsedPantry.getID().size();i++)
{
String temp_id=parsedPantry.getID().get(i);
String temp_name=parsedPantry.getName().get(i);
String temp_add1=parsedPantry.getAddress1().get(i);
String temp_add2=parsedPantry.getAddress2().get(i);
String temp_phno=parsedPantry.getPhone().get(i);
String temp_distTime=parsedPantry.getDistTime().get(i);
String temp_lat=parsedPantry.getGeo_lat().get(i);
String temp_long=parsedPantry.getGeo_long().get(i);
pantry[i]=new PantreisInfo();
pantry[i].setId(temp_id);
pantry[i].setName(temp_name);
pantry[i].setAddress1(temp_add1);
pantry[i].setAddress2(temp_add2);
pantry[i].setPhone(temp_phno);
pantry[i].setDistTime(temp_distTime);
pantry[i].setGeoLat(temp_lat);
pantry[i].setGeoLong(temp_long);
m_pantries.add(pantry[i]);
}
totalPantries=(TextView)findViewById(R.id.totalPantries);
totalPantries.setText("Total "+parsedPantry.getID().size()+" Pantries");
allOnMap=(Button)findViewById(R.id.allonmap);
allOnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Toast.makeText(PantriesListActivity.this,
"Wait..map is being loaded",Toast.LENGTH_SHORT).show();
Intent myIntent;
myIntent=new Intent(PantriesListActivity.this, PantriesOnMap.class);
startActivityForResult(myIntent, 0);
// TODO Auto-generated method stub
}
});
}
void parseURL(String url)
{
try
{
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
URL sourceUrl = new URL(url);
PanatriesHandler pantriesHandler=new PanatriesHandler();
xr.setContentHandler(pantriesHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
}
catch(Exception e)
{
System.out.println("==================>Exception Raised==>"+e);
}
}
class ImageAdapter extends ArrayAdapter<PantreisInfo>
{
private ArrayList<PantreisInfo> items;
public ImageAdapter(Context context,
int textViewResourceId,ArrayList<PantreisInfo> items)
{
super(context, textViewResourceId, items);
this.items = items;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null)
{
try
{
LayoutInflater vi = (LayoutInflater)
getSystemServiceContext.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
}
catch(Exception e)
{
System.out.println("Excption Caught"+e);
}
}
PantreisInfo p = items.get(position);
if (p != null)
{
TextView name = (TextView) v.findViewById(R.id.pantryName);
TextView add1= (TextView) v.findViewById(R.id.pantryAddress1);
TextView add2=(TextView)v.findViewById(R.id.pantryAddress2);
TextView phno = (TextView) v.findViewById(R.id.pantryPhno);
TextView distTime = (TextView) v.findViewById(R.id.distTime);
if (name != null)
{
name.setText(p.getName().get(0).toString());
}
if (add1 != null)
{
add1.setText(p.getAddress1().get(0).toString());
}
if (add2 != null)
{
add2.setText(p.getAddress2().get(0).toString());
}
if (phno != null)
{
phno.setText(p.getPhone().get(0).toString());
}
if (distTime!= null)
{
distTime.setText("Distribution Time: "+p.getDistTime().get(0).toString());
}
}
return v;
}
}
}
thanks in advance.....
hi nirav to get a onItem click of list u have to write onclickListener that i not found in your code try with that.
Instead of setting the clikclistener lv.setOnItemClickListener(new OnItemClickListener()
, can you use the override the method,
protected void onListItemClick(ListView l, View v, int position, long id) which is provided by the ListActivity
try this, its working for me..
public void onItemClick(AdapterView<?> parent,
View view1, int position, long id) {
// The action to be taken when item is clicked
}
SimpleAdapter adapter = new SimpleAdapter(this,
groupData,
R.layout.listitem,
new String[] {"name" , "id"},
new int[]{ R.id.txtItemName, R.id.txtid} );
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3){
//u get positon of list item from arg2
}
});

How to let a user add and remove items to a ListView?

I am trying to make it so that when a user clicks a button, it pops up a dialog with an EditText and an OK Button. When the user completes, the dialog, it should add the item they just typed in to the ListView. How do I do this?
I will need a large code example; this is my first application.
You'll want to follow the official notepad tutorial example. It's very comprehensive. It does 95% of what you want to do.
http://developer.android.com/resources/tutorials/notepad/index.html
Well here is a sample code. There is a button to add text in list and long press on list item will remove it.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Add Item" />
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
dialog_layout.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" >
<EditText
android:id="#+id/edit_box"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:inputType="text" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal"
android:weightSum="2" >
<Button
android:id="#+id/button_ok"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="OK" />
<Button
android:id="#+id/button_cancel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="CANCEL" />
</LinearLayout>
MainActivity.java
package com.example.listexample;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener,
OnItemLongClickListener {
private ArrayList<String> datasource;
private MyAdapter adapter;
private Dialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new ArrayList<String>();
adapter = new MyAdapter();
ListView listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(adapter);
listView.setOnItemLongClickListener(this);
findViewById(R.id.button).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog_layout);
dialog.findViewById(R.id.button_cancel).setOnClickListener(
MainActivity.this);
dialog.findViewById(R.id.button_ok).setOnClickListener(
MainActivity.this);
dialog.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class MyAdapter extends BaseAdapter {
#Override
public int getCount() {
// TODO Auto-generated method stub
return datasource.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return datasource.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView) convertView;
if (null == view) {
view = new TextView(MainActivity.this);
view.setPadding(10, 10, 10, 10);
}
view.setText(datasource.get(position));
return view;
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_cancel:
dialog.dismiss();
break;
case R.id.button_ok:
String text = ((EditText) dialog.findViewById(R.id.edit_box))
.getText().toString();
if (null != text && 0 != text.compareTo("")) {
datasource.add(text);
dialog.dismiss();
adapter.notifyDataSetChanged();
}
break;
}
}
#Override
public boolean onItemLongClick(AdapterView<?> listView, View view,
int position, long column) {
datasource.remove(position);
adapter.notifyDataSetChanged();
return true;
}
}

Categories

Resources