SetEmptyView not showing text and button when list view empty - android

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

Related

ViewPager not loading properly when user swipes in Android

I have an Android View Pager with five screens with images, autoload pager screen with timer.
When user swipes, it is jumping screens based on timer, and is not loading properly.
I have attached code below.
MainActivity.java
package com.sks.androidviewpager;
import java.util.Timer;
import java.util.TimerTask;
import com.androidsurya.androidviewpager.R;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends Activity {
int noofsize = 5;
ViewPager myPager = null;
int count = 0;
Timer timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set the layout which is containg viewPager Tag for image
setContentView(R.layout.activity_main);
//ViewPager Adapter to set image
ViewPagerAdapter adapter = new ViewPagerAdapter(MainActivity.this,noofsize);
myPager = (ViewPager) findViewById(R.id.reviewpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
// Timer for auto sliding
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(count<=5){
myPager.setCurrentItem(count);
count++;
}else{
count = 0;
myPager.setCurrentItem(count);
}
}
});
}
}, 500, 3000);
}
}
ViewPagerAdapter.java
package com.sks.androidviewpager;
import com.androidsurya.androidviewpager.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class ViewPagerAdapter extends PagerAdapter {
int size;
Activity act;
View layout;
TextView pagenumber1,pagenumber2,pagenumber3,pagenumber4,pagenumber5;
ImageView pageImage;
Button click;
public ViewPagerAdapter(MainActivity mainActivity, int noofsize) {
// TODO Auto-generated constructor stub
size = noofsize;
act = mainActivity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return size;
}
#Override
public Object instantiateItem(View container, int position) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) act
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = inflater.inflate(R.layout.pages, null);
pagenumber1 = (TextView)layout.findViewById(R.id.pagenumber1);
pagenumber2 = (TextView)layout.findViewById(R.id.pagenumber2);
pagenumber3 = (TextView)layout.findViewById(R.id.pagenumber3);
pagenumber4 = (TextView)layout.findViewById(R.id.pagenumber4);
pagenumber5 = (TextView)layout.findViewById(R.id.pagenumber5);
pageImage = (ImageView)layout.findViewById(R.id.imageView1);
int pagenumberTxt=position + 1;
//pagenumber1.setText("Now your in Page No " +pagenumberTxt );
try {
if(pagenumberTxt == 1){
pageImage.setBackgroundResource(R.drawable.android_1);
pagenumber1.setTextColor(Color.RED);
pagenumber2.setTextColor(Color.WHITE);
pagenumber3.setTextColor(Color.WHITE);
pagenumber4.setTextColor(Color.WHITE);
pagenumber5.setTextColor(Color.WHITE);
}
else if(pagenumberTxt == 2){
pageImage.setBackgroundResource(R.drawable.android_2);
pagenumber1.setTextColor(Color.WHITE);
pagenumber2.setTextColor(Color.RED);
pagenumber3.setTextColor(Color.WHITE);
pagenumber4.setTextColor(Color.WHITE);
pagenumber5.setTextColor(Color.WHITE);
}else if(pagenumberTxt == 3){
pageImage.setBackgroundResource(R.drawable.android_3);
pagenumber1.setTextColor(Color.WHITE);
pagenumber2.setTextColor(Color.WHITE);
pagenumber3.setTextColor(Color.RED);
pagenumber4.setTextColor(Color.WHITE);
pagenumber5.setTextColor(Color.WHITE);
}
else if(pagenumberTxt == 4){
pageImage.setBackgroundResource(R.drawable.android_4);
pagenumber1.setTextColor(Color.WHITE);
pagenumber2.setTextColor(Color.WHITE);
pagenumber3.setTextColor(Color.WHITE);
pagenumber4.setTextColor(Color.RED);
pagenumber5.setTextColor(Color.WHITE);
}
else if(pagenumberTxt == 5){
pageImage.setBackgroundResource(R.drawable.android_5);
pagenumber1.setTextColor(Color.WHITE);
pagenumber2.setTextColor(Color.WHITE);
pagenumber3.setTextColor(Color.WHITE);
pagenumber4.setTextColor(Color.WHITE);
pagenumber5.setTextColor(Color.RED);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
((ViewPager) container).addView(layout, 0);
return layout;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
// }
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<RelativeLayout
android:id="#+id/relativeTextview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/header"
android:padding="5dp" >
<android.support.v4.view.ViewPager
android:id="#+id/reviewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
</RelativeLayout>
pages.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/android_3"
android:contentDescription="#string/app_name" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom|center" >
<TextView
android:id="#+id/pagenumber1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#000"
android:onClick="pageOneClick"
android:text=" 1 "
android:textColor="#fff"
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:id="#+id/pagenumber2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#000"
android:textColor="#fff"
android:text=" 2 "
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:id="#+id/pagenumber3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#000"
android:textColor="#fff"
android:text=" 3 "
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:id="#+id/pagenumber4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#000"
android:textColor="#fff"
android:text=" 4 "
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:id="#+id/pagenumber5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#000"
android:textColor="#fff"
android:text=" 5 "
android:textSize="14sp"
android:textStyle="bold" />
</LinearLayout>
</FrameLayout>
Use
myPager.setCurrentItem(myPager.getCurrentItem()+1);
instead of myPager.setCurrentItem(count);
And you should judge if current item is the last item of this view pager.

Gridview Listener is not working

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

onListItemClick not working

The function onListItemClick is not being called:
ListActivity
package it.devapp.listview;
import java.util.ArrayList;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class ListNewsActivity extends ListActivity {
ArrayList<News> news;
Util util = new Util();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LoadData task = new LoadData();
task.execute();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
News news = (News) getListAdapter().getItem(position);
Intent i = new Intent(getApplicationContext(), NewsActivity.class);
i.putExtra("news",news);
startActivity(i);
}
private final class MyAdapter extends BaseAdapter
{
#Override
public boolean isEnabled(int position) {
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
RowWrapper wrapper;
if (convertView == null)
{
convertView = getLayoutInflater().inflate(R.layout.activity_list_news, null);
wrapper = new RowWrapper(convertView);
convertView.setTag(wrapper);
}
else
{
wrapper = (RowWrapper) convertView.getTag();
}
News news = (News) getItem(position);
wrapper.poulate(news);
return convertView;
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public Object getItem(int position)
{
//return News.notizie[position];
return news.get(position);
}
#Override
public int getCount()
{
return news.size();
}
}
private static class RowWrapper
{
private TextView data,titolo;
private ImageView immagine;
public RowWrapper(View convertView)
{
data = (TextView) convertView.findViewById(R.id.datanews);
immagine = (ImageView) convertView.findViewById(R.id.immagine);
titolo = (TextView) convertView.findViewById(R.id.titolo);
}
public void poulate(News news)
{
titolo.setText(news.getTitolo());
data.setText(news.getDate());
if ("".equals(news.getImg())){
immagine.setImageResource(R.drawable.news);
}else{
UrlImageViewHelper.setUrlDrawable(immagine, news.getImg(),null, 60000);
}
}
}
public class LoadData extends AsyncTask<Void, Void, ArrayList<News>> {
ProgressDialog progressDialog;
//declare other objects as per your need
#Override
protected void onPreExecute()
{
progressDialog= ProgressDialog.show(ListNewsActivity.this, "Caricamento dati","Attendere prego", true);
//do initialization of required objects objects here
};
#Override
protected ArrayList<News> doInBackground(Void... params)
{
news = util.getNews();
return news;
}
#Override
protected void onPostExecute(ArrayList<News> news)
{
super.onPostExecute(news);
setListAdapter(new MyAdapter());
progressDialog.dismiss();
};
}
}
activity_list_news.xml
<?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"
android:layout_marginLeft="3dip"
android:layout_marginRight="3dip"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="3dip"
android:layout_marginRight="3dip"
android:background="#aaFFFFFF"
>
<ImageView
android:id="#+id/immagine"
android:layout_width="80dip"
android:layout_height="80dip"
android:layout_marginLeft="2dip"
/>
<TextView
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:layout_marginTop="5dip"
android:id="#+id/datanews"
android:layout_toRightOf="#id/immagine"
android:layout_width="wrap_content"
style="#style/Date"
android:layout_height="25dip"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
/>
<TextView
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:id="#+id/titolo"
android:layout_toRightOf="#id/immagine"
android:layout_width="wrap_content"
style="#style/Titolo"
android:layout_below="#+id/datanews"
android:layout_height="50dip"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
/>
</RelativeLayout>
</RelativeLayout>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/sfondo">
<ImageView
android:id="#+id/imageView1"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_gravity="center"
android:src="#drawable/logo"
android:layout_marginTop="10dip"
/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
android:cacheColorHint="#00000000"
android:divider="#00000000"
/>
</LinearLayout>
you should return true instead of false in isEnabled
#Override
public boolean isEnabled(int position) {
return false;
}
From the documentation:
Returns true if the item at the specified position is not a separator.
(A separator is a non-selectable, non-clickable item).

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

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