listview position value not exceeding 5 - android

I have used a custom adapter to populate list view which is populating correctly using data. I have some textview which is getting data from database. when i click update it should get data from textview and present it to edittext for correction or updation. but it is not working correctly. Click on update some time enable more that two rows for updation and also data change from the original one.
Please help to correct this
UpdatePathi.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context="com.app.nirvachan.rssb.UpdatePathiActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorHead"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Pathi ID"
android:padding="5dip"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Pathi Name"
android:padding="5dip"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Center ID"
android:padding="5dip"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Point ID"
android:padding="5dip"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Contact No"
android:padding="5dip"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.1"
android:text="Options"
android:padding="5dip"/>
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listpathi"></ListView>
</LinearLayout>
Custom_Pathi_Item.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="wrap_content"
android:background="#color/colorList"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/layoutEdit"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/txtPathiID"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/txtPathiName"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/txtCenterID"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/txtPointID"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/txtContactNo"
android:layout_weight="1"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1.1">
<ImageButton
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/btnEdit"
android:layout_weight="1"
android:src="#mipmap/ic_edit"
android:textAllCaps="false"
android:background="#android:color/transparent"/>
<ImageButton
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/btnDelete"
android:layout_weight="1"
android:src="#mipmap/ic_delete"
android:text="Delete"
android:textAllCaps="false"
android:background="#android:color/transparent"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/layoutUpdate"
android:visibility="gone"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/etPathiID"
android:layout_weight="1"/>
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/etPathiName"
android:textSize="10sp"
android:inputType="textPersonName"
android:layout_weight="1"/>
<Spinner
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/etCenterID"
android:layout_weight="1"/>
<Spinner
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/etPointID"
android:layout_weight="1"/>
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="number"
android:id="#+id/etContactNo"
android:textSize="10sp"
android:layout_weight="1"/>
<ImageButton
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/btnUpdate"
android:src="#mipmap/ic_update"
android:layout_weight="1.1"
android:textAllCaps="false"
android:background="#android:color/transparent"/>
</LinearLayout>
</LinearLayout>
UpdatePathiActivity.java
package com.app.nirvachan.rssb;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class UpdatePathiActivity extends AppCompatActivity {
ListView listPathi;
JSONParser jsonParser = new JSONParser();
String pathiID, pathiName, contactNo;
int centerID, pointID;
private static String url_get_pathi = "http://onkararts.000webhostapp.com/php/rssb_get_pathi.php";
private static String url_get_point = "http://onkararts.000webhostapp.com/php/rssb_get_point.php";
private static String url_get_center = "http://onkararts.000webhostapp.com/php/rssb_get_center.php";
private static String url_update_pathi = "http://onkararts.000webhostapp.com/php/rssb_update_pathi.php";
private static String url_delete_pathi = "http://onkararts.000webhostapp.com/php/rssb_delete_pathi.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PATHIS = "pathis";
private static final String TAG_CENTERS = "centers";
private static final String TAG_POINTS = "points";
private static final String TAG_POINT_ID = "Point_ID";
private static final String TAG_POINT_NAME = "Point_Name";
private static final String TAG_CENTER_ID = "Center_ID";
private static final String TAG_CENTER_NAME = "Center_Name";
private static final String TAG_PATHI_ID = "Pathi_ID";
private static final String TAG_PATHI_NAME = "Pathi_Name";
private static final String TAG_CONTACT_NO = "Contact_No";
ArrayList<Pathi> pathi_Data;
UpdatePathiActivity.PathiAdapter a_pathi;
User[] centers_data, points_data;
SpinAdapter a_centers, a_points;
JSONArray centers, points, pathis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_pathi);
listPathi = (ListView) findViewById(R.id.listpathi);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
UpdatePathiActivity.getCenters gc = new UpdatePathiActivity.getCenters();
gc.execute();
UpdatePathiActivity.getPoints gp = new UpdatePathiActivity.getPoints();
gp.execute();
UpdatePathiActivity.getPathis gr = new UpdatePathiActivity.getPathis();
gr.execute();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
public class getPathis extends AsyncTask<String, String, ArrayList<Pathi>> {
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(ArrayList<Pathi> pathis) {
a_pathi = new UpdatePathiActivity.PathiAdapter(UpdatePathiActivity.this, pathis);
listPathi.setAdapter(a_pathi);
}
#Override
protected ArrayList<Pathi> doInBackground(String... args) {
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jsonParser.makeHttpRequest(
url_get_pathi, "GET", params);
Log.d("Getting Result", json.toString());
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// vehicles found
// Getting Array of vehicles
pathis = json.getJSONArray(TAG_PATHIS);
pathi_Data = new ArrayList<Pathi>();
for (int i = 0; i < pathis.length(); i++) {
JSONObject c = pathis.getJSONObject(i);
Pathi r = new Pathi(Integer.parseInt(c.getString(TAG_PATHI_ID)), c.getString(TAG_PATHI_NAME), Integer.parseInt(c.getString(TAG_CENTER_ID)), Integer.parseInt(c.getString(TAG_POINT_ID)), Long.parseLong(c.getString(TAG_CONTACT_NO)));
pathi_Data.add(i,r);
}
} else {
}
} catch (JSONException ex) {
ex.getMessage().toString();
}
return pathi_Data;
}
}
public class updatePathi extends AsyncTask<String, String, String>
{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String r) {
Toast.makeText(getBaseContext(),r,Toast.LENGTH_SHORT).show();
if(isSuccess) {
Intent i = new Intent(getBaseContext(), MainActivity.class);
startActivity(i);
finish();
}
}
#Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Pathi_ID", pathiID));
params.add(new BasicNameValuePair("Pathi_Name", pathiName));
params.add(new BasicNameValuePair("Center_ID", centerID+""));
params.add(new BasicNameValuePair("Point_ID", pointID+""));
params.add(new BasicNameValuePair("Contact_No", contactNo));
JSONObject json = jsonParser.makeHttpRequest(url_update_pathi,"POST", params);
Log.d("Create Response", json.toString());
try {
int r = json.getInt(TAG_SUCCESS);
if(r == 1){
z = "Record Updated Successfully";
isSuccess = true;
}
else{
isSuccess = false;
z = "Pathi Updation Failed";
}
}
catch (JSONException ex) {
z = ex.getMessage();
}
return z;
}
}
public class deletePathi extends AsyncTask<String, String, String>
{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String r) {
Toast.makeText(getBaseContext(),r,Toast.LENGTH_SHORT).show();
if(isSuccess) {
Intent i = new Intent(getBaseContext(), MainActivity.class);
startActivity(i);
finish();
}
}
#Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Pathi_ID", pathiID));
JSONObject json = jsonParser.makeHttpRequest(url_delete_pathi,"POST", params);
Log.d("Create Response", json.toString());
try {
int r = json.getInt(TAG_SUCCESS);
if(r == 1){
z = "Record Deleted Successfully";
isSuccess = true;
}
else{
isSuccess = false;
z = "Pathi deletion Failed";
}
}
catch (JSONException ex) {
z = ex.getMessage();
}
return z;
}
}
public class PathiAdapter extends BaseAdapter {
Context context;
List<Pathi> pathiList;
public PathiAdapter(Context context, List<Pathi> pathiList) {
this.context = context;
this.pathiList = pathiList;
}
#Override
public int getCount() {
return pathiList.size();
}
#Override
public Pathi getItem(int position) {
return pathiList.get(position);
}
#Override
public long getItemId(int position) {
return pathiList.indexOf(getItem(position));
}
private class ViewHolder{
LinearLayout l_edit;
TextView t_pathiID;
TextView t_pathiName;
TextView t_centerID;
TextView t_pointID;
TextView t_contactNo;
ImageButton b_edit;
ImageButton b_delete;
LinearLayout l_update;
TextView e_pathiID;
EditText e_pathiName;
Spinner e_centerID;
Spinner e_pointID;
EditText e_contactNo;
ImageButton b_update;
}
UpdatePathiActivity.PathiAdapter.ViewHolder d_holder = null;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_pathi_item, null);
d_holder = new UpdatePathiActivity.PathiAdapter.ViewHolder();
d_holder.t_pathiID = (TextView) convertView.findViewById(R.id.txtPathiID);
d_holder.t_pathiName = (TextView) convertView.findViewById(R.id.txtPathiName);
d_holder.t_contactNo = (TextView) convertView.findViewById(R.id.txtContactNo);
d_holder.t_centerID = (TextView) convertView.findViewById(R.id.txtCenterID);
d_holder.t_pointID = (TextView) convertView.findViewById(R.id.txtPointID);
d_holder.b_edit = (ImageButton) convertView.findViewById(R.id.btnEdit);
d_holder.b_delete = (ImageButton) convertView.findViewById(R.id.btnDelete);
d_holder.l_edit = (LinearLayout) convertView.findViewById(R.id.layoutEdit);
d_holder.l_update = (LinearLayout) convertView.findViewById(R.id.layoutUpdate);
d_holder.e_pathiID = (TextView) convertView.findViewById(R.id.etPathiID);
d_holder.e_pathiName = (EditText) convertView.findViewById(R.id.etPathiName);
d_holder.e_contactNo = (EditText) convertView.findViewById(R.id.etContactNo);
d_holder.e_centerID = (Spinner) convertView.findViewById(R.id.etCenterID);
d_holder.e_pointID = (Spinner) convertView.findViewById(R.id.etPointID);
d_holder.b_update = (ImageButton) convertView.findViewById(R.id.btnUpdate);
convertView.setTag(d_holder);
}
else{
d_holder = (UpdatePathiActivity.PathiAdapter.ViewHolder) convertView.getTag();
}
Pathi row_pos = pathiList.get(position);
d_holder.t_pathiID.setText(String.valueOf(row_pos.getPathiID()));
d_holder.t_pathiName.setText(row_pos.getPathiName());
d_holder.t_contactNo.setText(String.valueOf(row_pos.getContactNo()));
d_holder.t_centerID.setText(String.valueOf(row_pos.getCenterID()));
d_holder.t_pointID.setText(String.valueOf(row_pos.getPointID()));
d_holder.b_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View view = listPathi.getChildAt(position);
TextView u_pathiID = (TextView) view.findViewById(R.id.etPathiID);
EditText u_pathiName = (EditText) view.findViewById(R.id.etPathiName);
EditText u_contactNo = (EditText) view.findViewById(R.id.etContactNo);
Spinner u_centerID = (Spinner) view.findViewById(R.id.etCenterID);
Spinner u_pointID = (Spinner) view.findViewById(R.id.etPointID);
LinearLayout u_edit = (LinearLayout) view.findViewById(R.id.layoutEdit);
LinearLayout u_update = (LinearLayout) view.findViewById(R.id.layoutUpdate);
Pathi pathi = getItem(position);
u_pathiID.setText(String.valueOf(pathi.getPointID()));
u_pathiName.setText(pathi.getPathiName());
u_contactNo.setText(String.valueOf(pathi.getContactNo()));
u_centerID.setAdapter(a_centers);
u_centerID.setSelection(pathi.getCenterID());
u_pointID.setAdapter(a_points);
u_pointID.setSelection(pathi.getPointID());
u_edit.setVisibility(View.GONE);
u_update.setVisibility(View.VISIBLE);
}
});
d_holder.b_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View view = listPathi.getChildAt(position);
TextView u_pathiID = (TextView) view.findViewById(R.id.etPathiID);
EditText u_pathiName = (EditText) view.findViewById(R.id.etPathiName);
EditText u_contactNo = (EditText) view.findViewById(R.id.etContactNo);
Spinner u_centerID = (Spinner) view.findViewById(R.id.etCenterID);
Spinner u_pointID = (Spinner) view.findViewById(R.id.etPointID);
pathiID = u_pathiID.getText().toString();
pathiName = u_pathiName.getText().toString();
contactNo = u_contactNo.getText().toString();
centerID = a_centers.getItem(u_centerID.getSelectedItemPosition()).getId();
pointID = a_centers.getItem(u_pointID.getSelectedItemPosition()).getId();
UpdatePathiActivity.updatePathi ur = new UpdatePathiActivity.updatePathi();
ur.execute();
}
});
d_holder.b_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pathi row_pos = pathiList.get(position);
pathiID = String.valueOf(row_pos.getPathiID());
//Toast.makeText(UpdateCenterActivity.this, centerID+centerName+address+contactNo+eMailID+secretaryName+secretaryNo, Toast.LENGTH_LONG).show();
UpdatePathiActivity.deletePathi dr = new UpdatePathiActivity.deletePathi();
dr.execute();
}
});
return convertView;
}
}
public class getCenters extends AsyncTask<String, String, User[]> {
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(User[] centers) {
a_centers = new SpinAdapter(getBaseContext(), android.R.layout.simple_spinner_item, centers);
}
#Override
protected User[] doInBackground(String... args) {
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jsonParser.makeHttpRequest(
url_get_center, "GET", params);
Log.d("Getting Result", json.toString());
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// vehicles found
// Getting Array of vehicles
centers = json.getJSONArray(TAG_CENTERS);
centers_data = new User[centers.length()+1];
// looping through All Vehicles
centers_data[0] = new User();
centers_data[0].setId(0);
centers_data[0].setName("Please Select Center Name");
for (int i = 0; i < centers.length(); i++) {
JSONObject c = centers.getJSONObject(i);
centers_data[i+1] = new User();
centers_data[i+1].setId(c.getInt(TAG_CENTER_ID));
centers_data[i+1].setName(c.getString(TAG_CENTER_NAME));
}
} else {
}
} catch (JSONException ex) {
ex.getMessage().toString();
}
return centers_data;
}
}
public class getPoints extends AsyncTask<String, String, User[]> {
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(User[] points) {
a_points = new SpinAdapter(getBaseContext(), android.R.layout.simple_spinner_item, points);
}
#Override
protected User[] doInBackground(String... args) {
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jsonParser.makeHttpRequest(
url_get_point, "GET", params);
Log.d("Getting Result", json.toString());
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// vehicles found
// Getting Array of vehicles
points = json.getJSONArray(TAG_POINTS);
points_data = new User[points.length()+1];
points_data[0] = new User();
points_data[0].setId(0);
points_data[0].setName("Please Select Point Name");
for (int i = 0; i < points.length(); i++) {
JSONObject c = points.getJSONObject(i);
points_data[i+1] = new User();
points_data[i+1].setId(c.getInt(TAG_POINT_ID));
points_data[i+1].setName(c.getString(TAG_POINT_NAME));
}
} else {
}
} catch (JSONException ex) {
ex.getMessage().toString();
}
return points_data;
}
}
}
Please find screenshot of the problem
Here when I click on 6th item
Here when I click on 7th item

Modify your code, your onClickListener should be outside if else block
public class PathiAdapter extends BaseAdapter {
Context context;
List<Pathi> pathiList;
public PathiAdapter(Context context, List<Pathi> pathiList) {
this.context = context;
this.pathiList = pathiList;
}
#Override
public int getCount() {
return pathiList.size();
}
#Override
public Pathi getItem(int position) {
return pathiList.get(position);
}
#Override
public long getItemId(int position) {
return pathiList.indexOf(getItem(position));
}
private class ViewHolder{
LinearLayout l_edit;
TextView t_pathiID;
TextView t_pathiName;
TextView t_centerID;
TextView t_pointID;
TextView t_contactNo;
ImageButton b_edit;
ImageButton b_delete;
LinearLayout l_update;
TextView e_pathiID;
EditText e_pathiName;
Spinner e_centerID;
Spinner e_pointID;
EditText e_contactNo;
ImageButton b_update;
}
UpdatePathiActivity.PathiAdapter.ViewHolder d_holder = null;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_pathi_item, null);
d_holder = new UpdatePathiActivity.PathiAdapter.ViewHolder();
d_holder.t_pathiID = (TextView) convertView.findViewById(R.id.txtPathiID);
d_holder.t_pathiName = (TextView) convertView.findViewById(R.id.txtPathiName);
d_holder.t_contactNo = (TextView) convertView.findViewById(R.id.txtContactNo);
d_holder.t_centerID = (TextView) convertView.findViewById(R.id.txtCenterID);
d_holder.t_pointID = (TextView) convertView.findViewById(R.id.txtPointID);
d_holder.b_edit = (ImageButton) convertView.findViewById(R.id.btnEdit);
d_holder.b_delete = (ImageButton) convertView.findViewById(R.id.btnDelete);
d_holder.l_edit = (LinearLayout) convertView.findViewById(R.id.layoutEdit);
d_holder.l_update = (LinearLayout) convertView.findViewById(R.id.layoutUpdate);
d_holder.e_pathiID = (TextView) convertView.findViewById(R.id.etPathiID);
d_holder.e_pathiName = (EditText) convertView.findViewById(R.id.etPathiName);
d_holder.e_contactNo = (EditText) convertView.findViewById(R.id.etContactNo);
d_holder.e_centerID = (Spinner) convertView.findViewById(R.id.etCenterID);
d_holder.e_pointID = (Spinner) convertView.findViewById(R.id.etPointID);
d_holder.b_update = (ImageButton) convertView.findViewById(R.id.btnUpdate);
convertView.setTag(d_holder);
}
else{
d_holder = (UpdatePathiActivity.PathiAdapter.ViewHolder) convertView.getTag();
}
d_holder.b_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Clicked at :" +position, Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}

just chnge this code in your getView
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_pathi_item, null);
d_holder = new UpdatePathiActivity.PathiAdapter.ViewHolder();
d_holder.t_pathiID = (TextView) convertView.findViewById(R.id.txtPathiID);
d_holder.t_pathiName = (TextView) convertView.findViewById(R.id.txtPathiName);
d_holder.t_contactNo = (TextView) convertView.findViewById(R.id.txtContactNo);
d_holder.t_centerID = (TextView) convertView.findViewById(R.id.txtCenterID);
d_holder.t_pointID = (TextView) convertView.findViewById(R.id.txtPointID);
d_holder.b_edit = (ImageButton) convertView.findViewById(R.id.btnEdit);
d_holder.b_delete = (ImageButton) convertView.findViewById(R.id.btnDelete);
d_holder.l_edit = (LinearLayout) convertView.findViewById(R.id.layoutEdit);
d_holder.l_update = (LinearLayout) convertView.findViewById(R.id.layoutUpdate);
d_holder.e_pathiID = (TextView) convertView.findViewById(R.id.etPathiID);
d_holder.e_pathiName = (EditText) convertView.findViewById(R.id.etPathiName);
d_holder.e_contactNo = (EditText) convertView.findViewById(R.id.etContactNo);
d_holder.e_centerID = (Spinner) convertView.findViewById(R.id.etCenterID);
d_holder.e_pointID = (Spinner) convertView.findViewById(R.id.etPointID);
d_holder.b_update = (ImageButton) convertView.findViewById(R.id.btnUpdate);
convertView.setTag(d_holder);
}
else{
d_holder = (UpdatePathiActivity.PathiAdapter.ViewHolder) convertView.getTag();
}
d_holder.b_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Clicked at :" +position, Toast.LENGTH_SHORT).show();
}
});
return convertView;
}

Make Your Listview's onClickListener outside of the if and else
if()
{
}
else
{
}
d_holder.b_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Clicked at :" +position, Toast.LENGTH_SHORT).show();
}
});

Related

how to get radibutton Postion from listview On Button click in android

This is my screenshot:
This is my adapter class:
public class ListofAddressesAdapter extends ArrayAdapter<ListofAddressesDataModel> {
private Context context;
private int layoutResourceId;
HashMap<Integer, Integer> hashMap;
private List<ListofAddressesDataModel> data;
int selectedPosition = 0;
String name, phone, address;
String customeraddressid;
public ListofAddressesAdapter(Context context, int layoutResourceId,
List<ListofAddressesDataModel> data) {
super(context, R.layout.listofaddresses, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
hashMap = new HashMap<Integer, Integer>();
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.name = (TextView) row.findViewById(R.id.tvsubservices);
holder.description = (TextView) row.findViewById(R.id.tvdesc);
holder.fulladd = (TextView) row.findViewById(R.id.tvfulladdr);
holder.r = (RadioButton) row.findViewById(R.id.radioButton);
holder.delet = (ImageView) row.findViewById(R.id.ivdelete);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final ListofAddressesDataModel item = data.get(position);
holder.name.setText(item.getName());
holder.description.setText(item.getPhone());
holder.fulladd.setText(item.getFulladdress());
holder.r.setChecked(position == selectedPosition);
holder.r.setTag(position);
holder.r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPosition = (Integer) view.getTag();
name = data.get(selectedPosition).getName();
phone = data.get(selectedPosition).getPhone();
address = data.get(selectedPosition).getFulladdress();
customeraddressid = data.get(selectedPosition).getCustaddid();
notifyDataSetChanged();
}
});
return row;
}
static class ViewHolder {
TextView name;
TextView description;
TextView fulladd;
RadioButton r;
ImageView delet;
}
public Object getItemAtPosition(int position) {
// TODO Auto-generated method stub
return null;
}
}
This is my activity class:
public class testclass extends Activity implements View.OnClickListener{
List<ListofAddressesDataModel> lstDataModel;
ListView add;
JSONArray _jsonarray;
JSONObject jsonObject;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
add = (ListView) findViewById(R.id.add);
setContentView(R.layout.test);
add=(ListView)findViewById(R.id.add);
lstDataModel=new ArrayList<>();
button=(Button)findViewById(R.id.button);
button.setOnClickListener(this);
new manageaddresses().execute();
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.button)
{
}
}
class manageaddresses extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
String response = JSONfunctions.getJSONfromURL("http://cpanel.smartindiaservice.com/api/CustomerAddresses?CustomerID=4");
try {
_jsonarray = new JSONArray(response);
for (int i = 0; i < _jsonarray.length(); i++) {
ListofAddressesDataModel datamodel = new ListofAddressesDataModel();
jsonObject = _jsonarray.getJSONObject(i);
String customeraddressid = jsonObject.getString("CustomerAddressID");
datamodel.setCustaddid(customeraddressid);
String fullname = jsonObject.getString("FullName");
datamodel.setName(fullname);
String housenumber = jsonObject.getString("HouseNumber");
String phonenumber = jsonObject.getString("PhoneNumber");
datamodel.setPhone(phonenumber);
String area = jsonObject.getString("Area");
String landmark = jsonObject.getString("Landmark");
String city = jsonObject.getString("City");
String fulladdress = housenumber + "," + " " + area + "," + " " + landmark + "," + " " + city;
datamodel.setFulladdress(fulladdress);
lstDataModel.add(datamodel);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ListofAddressesAdapter adapter = new ListofAddressesAdapter(testclass.this, R.layout.listofaddresses, lstDataModel);
add.setAdapter(adapter);
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
}
This is my item.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:paddingBottom="20dp">
<RadioButton
android:id="#+id/radioButton"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:buttonTint="#999999"
android:text="New RadioButton" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout4"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:orientation="vertical"
android:paddingBottom="10dp">
<TextView
android:id="#+id/tvsubservices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/radioButton"
android:layout_marginLeft="50dp"
android:layout_toRightOf="#+id/radioButton"
android:text="TextView"
android:textColor="#000000"
android:textSize="18dp" />
<TextView
android:id="#+id/tvdesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvsubservices"
android:layout_marginLeft="50dp"
android:layout_toRightOf="#+id/radioButton"
android:text="Description"
android:textColor="#000000"
android:textSize="14dp" />
<TextView
android:id="#+id/tvfulladdr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvdesc"
android:layout_marginLeft="50dp"
android:layout_toRightOf="#+id/radioButton"
android:text="New Text"
android:textColor="#000000"
android:textSize="14dp" />
<TextView
android:id="#+id/custaddidposition"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="position"
android:visibility="gone" />
</LinearLayout>
</RelativeLayout>
I want to get selected radio button position or value and id so that on button click I tried with but it always take first position. Can any one suggest me where am I doing wrong? I have to get selected radio button position so that I can get value from list of Objects. I have to send into next activity.
In adapter create a method which returns the object of selected position. Like :
public ListofAddressesDataModel getSelectedItem() {
return data.get(selectedPosition);
}
In activity, on click of the button call this method. Like :
#Override
public void onClick(View v) {
if(v.getId() == R.id.button) {
//Here you will get the selected item of which the radio button is checked
ListofAddressesDataModel selectedItem = ((ListofAddressesAdapter) add.getAdapter()).getSelectedItem();
}
}
EDIT :
Instead of below lines in getView() in adapter
holder.r.setTag(position);
holder.r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPosition = (Integer) view.getTag();
name = data.get(selectedPosition).getName();
phone = data.get(selectedPosition).getPhone();
address = data.get(selectedPosition).getFulladdress();
customeraddressid = data.get(selectedPosition).getCustaddid();
notifyDataSetChanged();
}
});
just replace it with below line
holder.r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPosition = position;
}
});

Search In List View Android

How to implement search method on this code? It successfully load data from Service but I am not able to implement searching on this list.
Main Class from where it Application Runs
import java.util.HashMap;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class ClaimList extends Activity implements OnItemClickListener{
private static final String SOAP_ACTION = "http://tempuri.org/Adminclaim_List";
private static final String METHOD_NAME = "Adminclaim_List";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://www.ps-computers.com/service.asmx";
EditText searchText;
ProgressDialog Dialog;
SoapObject resultRequestSOAP;
ListView lview;
ListViewAdapter_claimlist lviewAdapter;
String Constants = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.claimlist);
Dialog = new ProgressDialog(this);
Dialog.setMessage("Loading...");
lview = (ListView) findViewById(R.id.lstvw_cliamlist);
searchText = (EditText) findViewById(R.id.searchTextFeild);
new doCallKsoapApiTask().execute();
lview.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
}
private class doCallKsoapApiTask extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
Dialog.show();
}
#Override
protected String doInBackground(Void... arg0) {
HashMap<String, String> a = new HashMap<String, String>();
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
resultRequestSOAP = (SoapObject) envelope.bodyIn;
return "";
} catch (Exception e) {
e.printStackTrace();
Log.v("test", "Error : " + e.getMessage()); // / REMOVE
return null;
}
}
#Override
protected void onPostExecute(String response) {
if (Dialog.isShowing())
Dialog.dismiss();
try {
SoapObject root = (SoapObject) resultRequestSOAP.getProperty(0);
SoapObject s_deals = (SoapObject) root
.getProperty("NewDataSet");
String claimid[] = new String[s_deals.getPropertyCount()];
String ref[] = new String[s_deals.getPropertyCount()];
String policy[] = new String[s_deals.getPropertyCount()];
String natureofloss[] = new String[s_deals.getPropertyCount()];
String registration[] = new String[s_deals.getPropertyCount()];
String status[] = new String[s_deals.getPropertyCount()];
for (int i = 0; i < s_deals.getPropertyCount(); i++) {
Object property = s_deals.getProperty(i);
if (property instanceof SoapObject) {
SoapObject category_list = (SoapObject) property;
String chk = "";
chk = category_list.getProperty("claim_id").toString()
.trim();
if (chk.equals("anyType{}")) {
claimid[i] = Constants;
} else {
claimid[i] = chk;
}
chk = category_list.getProperty("key_id").toString()
.trim();
if (chk.equals("anyType{}")) {
ref[i] = Constants;
} else {
ref[i] = chk;
}
chk = category_list.getProperty("policy_no").toString()
.trim();
if (chk.equals("anyType{}")) {
policy[i] = Constants;
} else {
policy[i] = chk;
}
chk = category_list.getProperty("Nature_of_Loss")
.toString().trim();
if (chk.equals("anyType{}")) {
natureofloss[i] = Constants;
} else {
natureofloss[i] = chk;
}
chk = category_list.getProperty("regis")
.toString().trim();
if (chk.equals("anyType{}")) {
registration[i] = Constants;
} else {
registration[i] = chk;
}
chk = category_list.getProperty("claim_status")
.toString().trim();
if (chk.equals("anyType{}")) {
status[i] = Constants;
} else {
status[i] = chk;
}
}
}
lviewAdapter = new ListViewAdapter_claimlist(ClaimList.this,
claimid, ref, policy, natureofloss,registration, status);
lview.setAdapter(lviewAdapter);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Claims not found",
Toast.LENGTH_SHORT).show();
}
}
}
}
Custom Adapter Class
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class ListViewAdapter_claimlist extends BaseAdapter{
Activity context;
String claimid[];
String ref[];
String policy[];
String natureofloss[];
String registration[];
String status[];
public ListViewAdapter_claimlist(Activity context, String[] claimid, String[] ref,String[] policy, String[] natureofloss,String[] registration, String[] status) {
super();
this.context = context;
this.claimid = claimid;
this.ref = ref;
this.policy = policy;
this.natureofloss = natureofloss;
this.registration = registration;
this.status = status;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return ref.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView cliamid;
TextView ref;
TextView policy;
TextView natureofloss;
TextView registration;
TextView status;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.rowitem_cliamlist, null);
holder = new ViewHolder();
holder.cliamid = (TextView) convertView.findViewById(R.id.tv_claims);
holder.ref = (TextView) convertView.findViewById(R.id.tv_referencepolicy);
holder.policy = (TextView) convertView.findViewById(R.id.tv_policyNo);
holder.natureofloss = (TextView) convertView.findViewById(R.id.tv_natureoflos);
holder.registration = (TextView) convertView.findViewById(R.id.tv_registration);
holder.status = (TextView) convertView.findViewById(R.id.tv_claimstatus);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.cliamid.setText(claimid[position]);
holder.ref.setText(ref[position]);
holder.policy.setText(policy[position]);
holder.natureofloss.setText(natureofloss[position]);
holder.status.setText(status[position]);
return convertView;
}
}
Main Layout
<?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" >
<TableRow
android:id="#+id/tableRow2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="100" >
<EditText
android:id="#+id/searchTextFeild"
style="#style/FormTextBoxes"
android:layout_margin="5dp"
android:layout_weight="30"
android:paddingLeft="5px"
android:ems="10"
android:hint="Police No..."
android:singleLine="true" >
<requestFocus />
</EditText>
</TableRow>
<ListView
android:id="#+id/lstvw_cliamlist"
android:layout_width="fill_parent"
android:layout_height="347dp"
android:layout_centerHorizontal="true"
android:scrollbars="none"
android:focusable="false"
android:layout_weight="0.88" >
</ListView>
</LinearLayout>
Custom Row
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="10"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="7"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="10" >
<TextView
android:id="#+id/TextView02"
style="#style/rowitem_left"
android:layout_weight="5"
android:text="Claim #"
android:textColor="#color/default_blue" />
<TextView
android:id="#+id/tv_claims"
style="#style/rowitem_right"
android:layout_width="0dp"
android:layout_weight="5"
android:text="220330"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="10" >
<TextView
android:id="#+id/textView2"
style="#style/rowitem_left"
android:layout_weight="5"
android:text="Ref #" />
<TextView
android:id="#+id/tv_referencepolicy"
style="#style/rowitem_right"
android:layout_weight="5"
android:text="220330" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/TextView04"
style="#style/rowitem_left"
android:layout_weight="5"
android:text="Registration" />
<TextView
android:id="#+id/tv_registration"
style="#style/rowitem_right"
android:layout_width="0dp"
android:layout_weight="5"
android:text="0" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/TextView01"
style="#style/rowitem_left"
android:layout_weight="5"
android:text="Police No" />
<TextView
android:id="#+id/tv_policyNo"
style="#style/rowitem_right"
android:layout_width="0dp"
android:layout_weight="5"
android:text="220330" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView3"
style="#style/rowitem_left"
android:layout_weight="5"
android:text="Nature of Loss"
/>
<TextView
android:id="#+id/tv_natureoflos"
style="#style/rowitem_right"
android:layout_weight="5"
android:text="TD"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
style="#style/rowitem_left"
android:layout_weight="5"
android:text="Status"
/>
<TextView
android:id="#+id/tv_claimstatus"
style="#style/rowitem_right"
android:layout_weight="5"
android:text="Open"
android:textStyle="bold"
android:textColor="#color/textgreen" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Screen Shot
Thanks in Advance if some one implement Searching Via Police No (In code policy no)
I have used this as my code for search filter . i hope this helps .
yourEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String Police No=yourEditText.getText().toString();
ArrayList<YouDataModel> Filter=new ArrayList<YouDataModel>();
for (DataModel data: leaveDatas) {
if (data.getUserName().toLowerCase().contains(nameToSearch.toLowerCase()) || data.getUserName().toLowerCase().equalsIgnoreCase(nameToSearch.toLowerCase()) )
{
filteredLeaves.add(data);
}
}
leaves_adapter = new Leaves_Adapter(filteredLeaves, Activity.this);
listView.setAdapter(leaves_adapter);
}
#Override
public void afterTextChanged(Editable s) {
}
});

How to handle different events inside ViewPager Tab?

I am working on an android project that contains a view pager. The UI of MenuActivity is as following...
Below are the code of view pager activities...
MenuActivity.java
public class MenuActivity extends FragmentActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs;
private String[] category_id;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
CommonFunctions.changeActionBar(getResources(),getActionBar());
// Initialization
initializeFoodCatagories();
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), tabs, category_id, MenuActivity.this);
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
//Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
}
private void initializeFoodCatagories() {
GeneralHelper helper = new GeneralHelper();
JSONObject json = helper.callWebService(getString(R.string.API_END_POINT) + "get_food_category");
String total_items = helper.getValueFromJson(json, "TotalRecords");
tabs = new String[Integer.parseInt(total_items)];
category_id = new String[Integer.parseInt(total_items)];
if(!(total_items.equals("0"))) {
try {
final JSONArray jsonarray = json.getJSONArray("Response");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
tabs[i] = jsonobject.getString("category_name").toString();
category_id[i] = jsonobject.getString("category_id").toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
}
#Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
}}
TabsPagerAdapter.java
public class TabsPagerAdapter extends FragmentPagerAdapter {
String [] category_name;
String [] category_id;
Activity context;
public TabsPagerAdapter(FragmentManager fm, String[] category_name, String[] category_id, Activity context) {
super(fm);
this.category_name = category_name;
this.category_id = category_id;
this.context = context;
}
#Override
public Fragment getItem(int index) {
for(int i = 0; i < category_name.length; i++) {
if(index==i) {
return new SwipeTabFragment(context, category_id[i]);
}
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return category_name.length;
}}
SwipeTabFragment.java
public class SwipeTabFragment extends Fragment {
Activity context;
ListView list;
private String[] item_name;
private String[] price_per_unit;
private String[] item_image;
private String category_id;
public SwipeTabFragment(Activity context, String category_id) {
this.context = context;
this.category_id = category_id;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_items, container, false);
list = (ListView) rootView.findViewById(R.id.lstItems);
initializeFoodItems(category_id);
list.setAdapter(new ItemListAdapter(context, item_name, price_per_unit));
//ListView event handling
//This event not working
/*list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","ListView activated");
}
});*/
//This event is also not working
/*rootView.findViewById(R.id.imgPlus).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","Plus Image Button activated");
}
});*/
return rootView;
}
private void initializeFoodItems(String position) {
String url = getString(R.string.API_END_POINT) + "get_menu_items?food_cat_id="+position;
GeneralHelper helper = new GeneralHelper();
JSONObject json = helper.callWebService(url);
String total_items = helper.getValueFromJson(json, "TotalRecords");
price_per_unit = new String[Integer.parseInt(total_items)];
item_name = new String[Integer.parseInt(total_items)];
item_image = new String[Integer.parseInt(total_items)];
if(!(total_items.equals("0"))) {
try {
final JSONArray jsonarray = json.getJSONArray("Response");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
price_per_unit[i] = jsonobject.getString("price_per_unit").toString();
item_name[i] = jsonobject.getString("item_name").toString();
item_image[i] = jsonobject.getString("item_image").toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}}
ItemListAdapter.java
public class ItemListAdapter extends ArrayAdapter<String> {
static int grand_total;
private final Activity context;
private final String title[];
private final String price[];
private final String discount[];
public ItemListAdapter(Activity context, String[] title, String[] price, String[] discount) {
super(context, R.layout.item_list, title);
this.context = context;
this.title = title;
this.price = price;
this.discount = discount;
}
#SuppressLint({ "ViewHolder", "InflateParams" })
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View row = inflater.inflate(R.layout.item_list, null,true);
((TextView) row.findViewById(R.id.txtTitl)).setText(title[position]);
final int item_price = Integer.parseInt(price[position]);
((TextView) row.findViewById(R.id.txtPrice)).setText(price[position] + " Rs. Each");
((TextView) row.findViewById(R.id.txtDiscount)).setText(discount[position] + "%");
RatingBar ratingBar = (RatingBar) row.findViewById(R.id.ratingBar);
LayerDrawable stars = (LayerDrawable) ratingBar.getProgressDrawable();
stars.getDrawable(2).setColorFilter(row.getResources().getColor(R.color.orange), PorterDuff.Mode.SRC_ATOP);
//Increasing Quantity
row.findViewById(R.id.imgPlus).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView qty = (TextView) row.findViewById(R.id.txtQty);
qty.setText(String.valueOf((Integer.parseInt(qty.getText().toString()))+1));
if (Integer.parseInt(qty.getText().toString()) > 0) {
//Calculating Total Amount
int t = item_price * Integer.parseInt(qty.getText().toString());
((TextView) row.findViewById(R.id.txtTotal)).setText("Rs. " + String.valueOf(t));
}
}
});
//Decreasing Quantity
row.findViewById(R.id.imgMinus).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView qty = (TextView) row.findViewById(R.id.txtQty);
if (Integer.parseInt(qty.getText().toString()) > 0) {
qty.setText(String.valueOf((Integer.parseInt(qty.getText().toString()))-1));
//Calculating Total Amount
int t = item_price * Integer.parseInt(qty.getText().toString());
((TextView) row.findViewById(R.id.txtTotal)).setText("Rs. " + String.valueOf(t));
}
}
});
return row;
}
}
activity.menu.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
activity_items.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#drawable/activity_background">
<ListView
android:id="#+id/lstItems"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#drawable/listview_design"/>
</RelativeLayout>
item_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#drawable/listview_design"
android:padding="5dp"
android:layout_margin="5dp" >
<TextView
android:id="#+id/txtTitl"
style="#style/ListViewHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="8dp"
android:layout_toRightOf="#+id/imgIcon"
android:gravity="left"
android:text="#string/itemname"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="#+id/imgIcon"
android:layout_width="80dp"
android:layout_height="80dp"
android:contentDescription="#string/img_desp"
android:src="#drawable/food_item_thumb" />
<RatingBar
android:id="#+id/ratingBar"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imgIcon"
android:layout_alignLeft="#+id/imgIcon"
android:background="#80FF0000"
android:numStars="5"
android:paddingBottom="5dp"
android:rating="3.5" />
<TextView
android:id="#+id/txtPrice"
style="#style/ListViewBottomText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtTitl"
android:layout_below="#+id/txtTitl"
android:paddingTop="0dp"
android:text="#string/price_tag"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="25dp"
android:layout_alignBottom="#+id/imgIcon"
android:layout_alignLeft="#+id/txtPrice"
android:layout_alignTop="#+id/ratingBar" >
<ImageButton
android:id="#+id/imgPlus"
android:layout_width="25dp"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/sqr_plus"
android:contentDescription="#string/img_desp" />
<ImageButton
android:id="#+id/imgMinus"
android:layout_width="25dp"
android:layout_height="match_parent"
android:layout_alignBottom="#+id/imgPlus"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#drawable/sqr_minus"
android:contentDescription="#string/img_desp" />
<TextView
android:id="#+id/txtQty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/imgPlus"
android:layout_toRightOf="#+id/imgMinus"
android:gravity="center_horizontal|center_vertical"
android:text="#string/qty"
android:textColor="#808080"
android:textSize="20sp" />
<TextView
android:id="#+id/TextView01"
style="#style/ListViewBottomText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:gravity="center_horizontal|center_vertical"
android:paddingBottom="0dp"
android:paddingTop="0dp"
android:text="#string/total"
android:textColor="#AC2A2E"
android:textSize="20sp" />
</RelativeLayout>
<ImageView
android:id="#+id/imgDiscount"
android:layout_width="30dp"
android:layout_height="40dp"
android:layout_alignRight="#+id/txtTitl"
android:layout_alignTop="#+id/txtTitl"
android:background="#drawable/label"
android:contentDescription="#string/img_desp" />
</RelativeLayout>
I think I've provided sufficient information to understand the problem. GeneralHelper is a web service class to get JSON data from server.
Here I want to get order details by the user. But I am facing some problems as following...
List Items are not clickable, and when I put event handling code, it is not working
How to handle onClick event of ImageButton(imgPlus and (imgMinus) which is placed in ListView item. I tried with the code written in comment in SwipeTabFragment.java, But it is also not working.
Last problem is, Tabs are switching very well when we swipe left or right, but if we click on tabs, then not able to switch.
Please help me to solve above problems or any one of them. Thank You!
How to use LinearLayout:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="400dp" >
<LinearLayout
android:id="#+id/layout1"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</RelativeLayout>
prompts.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Type Your Name : "
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/editTextDialogUserInput"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
</LinearLayout>
row.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/layoutbg"
android:layout_width="fill_parent"
android:layout_height="70dp"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<ImageView
android:id="#+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<Button
android:id="#+id/del"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="REMOVE" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
MainActivity.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.bean.FriendBean;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private LinearLayout mList;
private ArrayList<FriendBean> arr = new ArrayList<FriendBean>();
int loader = R.drawable.loader;
int i;
String val;
// public LayoutInflater inflater;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = (LinearLayout) findViewById(R.id.layout1);
final ImageLoader img = new ImageLoader(getApplicationContext());
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"jsonarray.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
String myjsonstring = sb.toString();
try {
JSONObject obj = new JSONObject(myjsonstring);
JSONArray jsonarray = obj.getJSONArray("json");
Log.e("Length", "" + jsonarray.length());
for (i = 0; i < jsonarray.length(); i++) {
JSONObject jsonObj = jsonarray.getJSONObject(i);
String friend_name = jsonObj.getString("friend_name");
String friend_phone = jsonObj.getString("friend_phone");
String url = jsonObj.getString("image_url");
FriendBean bean = new FriendBean(url, friend_name, friend_phone);
arr.add(bean);
Log.e("u", url);
Log.e("friend_name", friend_name);
Log.e("friend_phone", friend_phone);
LayoutInflater vi = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View v = vi.inflate(R.layout.row, null);
final ImageView im = (ImageView) v.findViewById(R.id.img);
final TextView t1 = (TextView) v.findViewById(R.id.name);
final TextView t2 = (TextView) v.findViewById(R.id.num);
final Button del = (Button) v.findViewById(R.id.del);
img.DisplayImage(url, loader, im);
t1.setText(friend_name);
t2.setText(String.valueOf(i));
mList.addView(v);
t1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LayoutInflater li = LayoutInflater.from(MainActivity.this);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
userInput.setText(t1.getText().toString());
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// get user input and set it to
// result
// edit text
int f = Integer.parseInt(t2.getText()
.toString());
Toast.makeText(getApplicationContext(),
"Position " + f, Toast.LENGTH_SHORT)
.show();
val = userInput.getText().toString();
Toast.makeText(getApplicationContext(),
val, Toast.LENGTH_SHORT).show();
t1.setText(val);
// mList.addView(v1);
del.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated
// method
// stub
Toast.makeText(
getApplicationContext(),
"Previously "
+ mList.getChildCount(),
Toast.LENGTH_SHORT).show();
int f = Integer.parseInt(t2.getText()
.toString());
mList.removeViewAt(f);
Toast.makeText(
getApplicationContext(),
"Position "
+ t1.getText().toString(),
Toast.LENGTH_SHORT).show();
myFunction(mList);
}
});
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
Log.e("MSG", "HI");
}
});
del.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"Previously " + mList.getChildCount(),
Toast.LENGTH_SHORT).show();
int f = Integer.parseInt(t2.getText().toString());
mList.removeViewAt(f);
Toast.makeText(getApplicationContext(), "Position " + f,
Toast.LENGTH_SHORT).show();
myFunction(mList);
}
});
im.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
t1.getText().toString(), Toast.LENGTH_SHORT).show();
return false;
}
});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void myFunction(LinearLayout l) {
LayoutInflater vi = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.row, null);
int c = l.getChildCount();
for (int j = 0; j < c; j++) {
v = l.getChildAt(j);
TextView t2 = (TextView) v.findViewById(R.id.num);
t2.setText(String.valueOf(j));
}
Toast.makeText(getApplicationContext(), "Finally " + c,
Toast.LENGTH_SHORT).show();
}
}
jsonarray.json (put this on assets folder)
{ "json" : [ { "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Madhumoy",
"friend_phone" : "123"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Sattik",
"friend_phone" : "123"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Koushik",
"friend_phone" : "123"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Himanshu",
"friend_phone" : "123"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Sandy",
"friend_phone" : "123"
}
] }
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.customlist"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.customlist.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
FriendBean.java
public class FriendBean {
private String Image;
private String name;
private String ph;
public FriendBean(String Image,String name,String ph){
this.Image = Image;
this.name = name;
this.ph = ph;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPh() {
return ph;
}
public void setPh(String ph) {
this.ph = ph;
}
}
Just avoid the ImageLoader class. I expect that you can show a image from an URL. If you can do that then just use your method to show a image from an URL to the im ImageView...
Just create a new project with this files and you will understand this..
You have intentionally commented ListView's onItemclicklistener inside your onCreateView
Uncomment the code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_items, container, false);
list = (ListView) rootView.findViewById(R.id.lstItems);
initializeFoodItems(category_id);
list.setAdapter(new ItemListAdapter(context, item_name, price_per_unit));
//ListView event handling
list.setOnItemClickListener(itemClickListener );
return rootView;
}
ImageVIew Click
Write this method anywhere
// Item Click Listener for the listview
OnItemClickListener itemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
// Getting the Container Layout of the ListView
RelativeLayout linearLayoutParent = (RelativeLayout ) container;
// Getting the inner Linear Layout
RelativeLayout linearLayoutChild = (RelativeLayout ) linearLayoutParent.getChildAt(1);
// Getting the Country TextView
ImageView iv = (ImageView) linearLayoutChild.getChildAt(0);
Toast.makeText(getBaseContext(), "Image CLicked", Toast.LENGTH_SHORT).show();
}
};
I got solution of two problems. That are...
How to handle onClick event of ImageButton(imgPlus and imgMinus) which is placed in ListView item. I tried with the code written in comment in SwipeTabFragment.java, But it is also not working.
Solution :
I am handling onclick event in ItemListAdapter.java that is working fine. Below is the code of this file. That may be helpful for others.
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.PorterDuff;
import android.graphics.drawable.LayerDrawable;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.ArrayAdapter;
import android.widget.RatingBar;
import android.widget.TextView;
public class ItemListAdapter extends ArrayAdapter<String> {
static int grand_total;
private final Activity context;
private final String title[];
private final String price[];
private final String discount[];
public ItemListAdapter(Activity context, String[] title, String[] price, String[] discount) {
super(context, R.layout.item_list, title);
this.context = context;
this.title = title;
this.price = price;
this.discount = discount;
}
#SuppressLint({ "ViewHolder", "InflateParams" })
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View row = inflater.inflate(R.layout.item_list, null,true);
((TextView) row.findViewById(R.id.txtTitl)).setText(title[position]);
final int item_price = Integer.parseInt(price[position]);
((TextView) row.findViewById(R.id.txtPrice)).setText(price[position] + " Rs. Each");
((TextView) row.findViewById(R.id.txtDiscount)).setText(discount[position] + "%");
RatingBar ratingBar = (RatingBar) row.findViewById(R.id.ratingBar);
LayerDrawable stars = (LayerDrawable) ratingBar.getProgressDrawable();
stars.getDrawable(2).setColorFilter(row.getResources().getColor(R.color.orange), PorterDuff.Mode.SRC_ATOP);
//Increasing Quantity
row.findViewById(R.id.imgPlus).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView qty = (TextView) row.findViewById(R.id.txtQty);
qty.setText(String.valueOf((Integer.parseInt(qty.getText().toString()))+1));
if (Integer.parseInt(qty.getText().toString()) > 0) {
//Calculating Total Amount
int t = item_price * Integer.parseInt(qty.getText().toString());
((TextView) row.findViewById(R.id.txtTotal)).setText("Rs. " + String.valueOf(t));
}
}
});
//Decreasing Quantity
row.findViewById(R.id.imgMinus).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView qty = (TextView) row.findViewById(R.id.txtQty);
if (Integer.parseInt(qty.getText().toString()) > 0) {
qty.setText(String.valueOf((Integer.parseInt(qty.getText().toString()))-1));
//Calculating Total Amount
int t = item_price * Integer.parseInt(qty.getText().toString());
((TextView) row.findViewById(R.id.txtTotal)).setText("Rs. " + String.valueOf(t));
}
}
});
return row;
}
}
Tabs are switching very well when we swipe left or right, but if we click on tabs, then not able to switch.
Solution : I simply put the following line in the onTabSelected() and make the tabs working. This was suggested by #AvishekDas. Again Thanks for this.
#Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
But I'm still finding problem 1. My listView is not clickable. If any of you have solution then please post. Thank you!

ArrayList not showing last item in listview

I am storing values in arraylist as{india,pakisthan,srilanka,nepal,malasiya,australia,ireland} when I set this list to BaseAdapter the last element is not showing last item in listview when listview extends device screen. It showing only India, Pakisthan, Srilanka, Nepal, Malasiaya and Australia was breaking and Ireland was not showing. My ListFragment class is
package com.example.mynavigationtab;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class AndroidFragment extends ListFragment
{
ArrayList<CountryObject> mCountry = new ArrayList<CountryObject>();
ArrayList<String> mCoun = new ArrayList<String>();
CountryObject country = new CountryObject();
AndroidAdapter mAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
LoadUrl();
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
public void LoadUrl()
{
ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("naren", "naren"));
new GetJsonData().execute(getString(R.string.tag_url),pairs,ThreadCode.THREAD_URL, handler);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
getActivity().removeDialog(0);
switch (msg.what) {
case ThreadCode.THREAD_URL:
final String result = (String) msg.obj;
LoadJson(result);
break;
default:
break;
}
}
};
public void LoadJson(String result)
{
try
{
JSONObject mJson1 = new JSONObject(result);
JSONArray mResult = mJson1.getJSONArray("result");
mCountry = new ArrayList<CountryObject>();
for(int i=0; i<mResult.length(); i++)
{
JSONObject mRes = mResult.getJSONObject(i);
JSONArray mCount = mRes.getJSONArray("Country");
JSONObject mCoun = mCount.getJSONObject(i);
CountryObject mSetData = new CountryObject();
mSetData.setmCountry(mCoun.getString("name"));
mCountry.add(mSetData);
CountryObject mSetData1 = new CountryObject();
mSetData1.setmCountry(mCoun.getString("name1"));
mCountry.add(mSetData1);
CountryObject mSetData2 = new CountryObject();
mSetData2.setmCountry(mCoun.getString("name2"));
mCountry.add(mSetData2);
CountryObject mSetData3 = new CountryObject();
mSetData3.setmCountry(mCoun.getString("name3"));
mCountry.add(mSetData3);
CountryObject mSetData4 = new CountryObject();
mSetData4.setmCountry(mCoun.getString("name4"));
mCountry.add(mSetData4);
CountryObject mSetData5 = new CountryObject();
mSetData5.setmCountry(mCoun.getString("name5"));
mCountry.add(mSetData5);
CountryObject mSetData6 = new CountryObject();
mSetData6.setmCountry(mCoun.getString("name6"));
mCountry.add(mSetData6);
CountryObject mSetData7 = new CountryObject();
mSetData7.setmCountry(mCoun.getString("name7"));
mCountry.add(mSetData7);
CountryObject mSetData8 = new CountryObject();
mSetData8.setmCountry(mCoun.getString("name8"));
mCountry.add(mSetData8);
}
}
catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
String mMessage = "Error parsing JSON data from server. Please try again.";
showToast(mMessage);
}
}
public void showToast(String message) {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getActivity(), message, duration);
toast.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
LoadUrl();
}
}`
//Adapter class
package com.example.mynavigationtab;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class AndroidAdapter extends BaseAdapter
{
ArrayList<String> mCountry = new ArrayList<String>();
Context mContext;
TextView mCountryName;
public AndroidAdapter(Context androidFragment,ArrayList<String> mCoun)
{
mCountry = mCoun;
mContext = androidFragment;
}
#Override
public int getCount()
{
return mCountry.size();
}
#Override
public Object getItem(int position)
{
return mCountry.get(position);
}
#Override
public long getItemId(int position)
{
return mCountry.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
converview = null;
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.adapter_list, parent,false);
mCountryName = (TextView) convertView.findViewById(R.id.textOne);
mCountryName.setText(mCountry.get(position));
}
return convertView;
}
}
// Xml Layout for adapter_list.xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textOne"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:padding="2dp"
android:textStyle="bold"/>
</RelativeLayout>
//Json File
{
result: [
{
Country: [
{
name: "India",
name1: "Pakisthan",
name2: "Bangaldesh",
name3: "Australia",
name4: "Ireland",
name5: "SriLanka",
name6: "Nepal",
name7: "USA",
name8: "Russia"
}
],
States: [
{
states: "Tamil Nadu",
states1: "Andhra",
states2: "Karnataka",
states3: "Kerala"
}
],
District: [
{
district: "Krishnagiri",
district1: "Dharmapuri",
district2: "Salem",
district3: "Hosur"
}
]
}
]
}
May this solve your problem :
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.adapter_list, parent,false);
mCountryName = (TextView) convertView.findViewById(R.id.textOne);
}
mCountryName.setText(mCountry.get(position));//Write this after condition
One problem is that you're setting the text only when convertView is null. You should make sure that the line mCountryName.setText(mCountry.get(position)); is executed every single time, otherwise some items will not show up.
Atlast I solved it.............
The Problem is in my xml layout. That i have mentioned a weight for framelayout in TabHost
//Modified xml layout
<?xml version="1.0" encoding="UTF-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DBE9F4">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/frame_shape"
android:layout_weight="0" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#android:color/white">
</FrameLayout>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</android.support.v4.view.ViewPager>
</LinearLayout>
</TabHost>

How to add a checkbox in my gridview?

how do i add checkbox in my code? so user select multiple pictures using checkbox in gridview what do i do? I just want to add a checkbox in my gridview what do i do?
GridView gridView;
TextView textView;
File currentParent;
File[] currentFiles;
SimpleAdapter simpleAdapter;
File root1;
File root;
root1 = new File("/data/data/com.myexample.lock/files/");
currentParent = root1;
currentFiles = root1.listFiles();
currentFilePath = new String[currentFiles.length];
int count = 0;
for (File f : currentFiles) {
currentFilePath[count] = f.getAbsolutePath();
count++;
}
gridView = (GridView) findViewById(R.id.grid);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
if (currentFiles[position].isDirectory()) {
root = new File("/data/data/com.myexample.lock/files/" +
FileName(currentFilePath[position]) + "/");
currentFiles = root.listFiles();
inflateListView(currentFiles);
} else if (currentFiles[position].isFile()) {
openFile(currentFiles[position]);
}
}
});
private void inflateListView(File[] files) {
List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
for (int i = 0; i < files.length; i++) {
Map<String, Object> listItem = new HashMap<String, Object>();
if (files[i].isDirectory()) {
listItem.put("icon", R.drawable.folder);
listItem.put("fileName", files[i].getName()+
"("+files[i].list().length+")");
} else {
listItem.put("icon", files[i]);
}
listItems.add(listItem);
}
simpleAdapter = new SimpleAdapter(this,
listItems, R.layout.line,new String[] {
"icon", "fileName" }, new int[] { R.id.icon, R.id.file_name });
}
line.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="fill_parent"
android:background="#ffffff"
android:orientation="horizontal"
android:padding="5dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/file_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/icon"
android:paddingLeft="5dp"
android:textColor="#000000"
android:textSize="12dp" />
</RelativeLayout>
Use custom adapter for your gridView. In the getView method you can inflate any layout you want for the cell
This the example of how i made a custom listview with Imageview and TextView. I did this because i also wanted to delete multiple items selected in the listview.
This is my java code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class DeleteData extends Activity {
Cursor cursor;
ListView lv_delete_data;
static ArrayList<Integer> listOfItemsToDelete;
SQLiteDatabase database;
private Category[] categories;
ArrayList<Category> categoryList;
private ArrayAdapter<Category> listAdapter;
ImageView iv_delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_data);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
manage_reload_list();
listOfItemsToDelete = new ArrayList<Integer>();
iv_delete = (ImageView) findViewById(R.id.imageViewDeleteDataDelete);
iv_delete.setClickable(true);
iv_delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (listOfItemsToDelete.isEmpty()) {
Toast.makeText(getBaseContext(), "No items selected.",
Toast.LENGTH_SHORT).show();
}
else {
showDialog(
"Warning",
"Are you sure you want to delete these categories ? This will erase all records attached with it.");
}
}
});
lv_delete_data = (ListView) findViewById(R.id.listViewDeleteData);
lv_delete_data.setAdapter(listAdapter);
lv_delete_data.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
ImageView imageView = (ImageView) arg1
.findViewById(R.id.imageViewSingleRowDeleteData);
Category category = (Category) imageView.getTag();
if (category.getChecked() == false) {
imageView.setImageResource(R.drawable.set_check);
listOfItemsToDelete.add(category.getId());
category.setChecked(true);
} else {
imageView.setImageResource(R.drawable.set_basecircle);
listOfItemsToDelete.remove((Integer) category.getId());
category.setChecked(false);
}
}
});
}
private void showDialog(final String title, String message) {
AlertDialog.Builder adb = new Builder(DeleteData.this);
adb.setTitle(title);
adb.setMessage(message);
adb.setIcon(R.drawable.ic_launcher);
String btn = "Ok";
if (title.equals("Warning")) {
btn = "Yes";
adb.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
adb.setPositiveButton(btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
if (title.equals("Warning")) {
for (int i : listOfItemsToDelete) {
// -------first delete from category table-----
// database.delete("category", "cat_id=?",
// new String[] { i + "" });
// ---------delete from category_fields
database.delete("category_fields", "cat_id=?",
new String[] { i + "" });
// --------now fetch rec_id where cat_id =
// i-----------------
cursor = database.query("records_data",
new String[] { "rec_id" }, "cat_id=?",
new String[] { i + "" }, null, null, null);
if (cursor.getCount() == 0)
cursor.close();
else {
ArrayList<Integer> al_tmp_rec_id = new ArrayList<Integer>();
while (cursor.moveToNext())
al_tmp_rec_id.add(cursor.getInt(0));
cursor.close();
for (int i1 : al_tmp_rec_id) {
database.delete("records_fields_data",
"rec_id=?", new String[] { i1 + "" });
database.delete("record_tag_relation",
"rec_id=?", new String[] { i1 + "" });
}
// ---------delete from records_data-------
database.delete("records_data", "cat_id=?",
new String[] { i + "" });
cursor.close();
}
}
showDialog("Success",
"Categories, with their records, deleted successfully.");
} else {
database.close();
listOfItemsToDelete.clear();
manage_reload_list();
lv_delete_data.setAdapter(listAdapter);
}
}
});
AlertDialog ad = adb.create();
ad.show();
}
protected void manage_reload_list() {
loadDatabase();
categoryList = new ArrayList<Category>();
// ------first fetch all categories name list-------
cursor = database.query("category", new String[] { "cat_id",
"cat_description" }, null, null, null, null, null);
if (cursor.getCount() == 0) {
Toast.makeText(getBaseContext(), "No categories found.",
Toast.LENGTH_SHORT).show();
cursor.close();
} else {
while (cursor.moveToNext()) {
categories = new Category[] { new Category(cursor.getInt(0),
cursor.getString(1)) };
categoryList.addAll(Arrays.asList(categories));
}
cursor.close();
}
listAdapter = new CategoryArrayAdapter(this, categoryList);
}
static class Category {
String cat_name = "";
int cat_id = 0;
Boolean checked = false;
Category(int cat_id, String name) {
this.cat_name = name;
this.cat_id = cat_id;
}
public int getId() {
return cat_id;
}
public String getCatName() {
return cat_name;
}
public Boolean getChecked() {
return checked;
}
public void setChecked(Boolean checked) {
this.checked = checked;
}
public boolean isChecked() {
return checked;
}
public void toggleChecked() {
checked = !checked;
}
}
static class CategoryViewHolder {
ImageView imageViewCheck;
TextView textViewCategoryName;
public CategoryViewHolder(ImageView iv_check, TextView tv_category_name) {
imageViewCheck = iv_check;
textViewCategoryName = tv_category_name;
}
public ImageView getImageViewCheck() {
return imageViewCheck;
}
public TextView getTextViewCategoryName() {
return textViewCategoryName;
}
}
static class CategoryArrayAdapter extends ArrayAdapter<Category> {
LayoutInflater inflater;
public CategoryArrayAdapter(Context context, List<Category> categoryList) {
super(context, R.layout.single_row_delete_data,
R.id.textViewSingleRowDeleteData, categoryList);
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Category category = (Category) this.getItem(position);
final ImageView imageViewCheck;
final TextView textViewCN;
if (convertView == null) {
convertView = inflater.inflate(R.layout.single_row_delete_data,
null);
imageViewCheck = (ImageView) convertView
.findViewById(R.id.imageViewSingleRowDeleteData);
textViewCN = (TextView) convertView
.findViewById(R.id.textViewSingleRowDeleteData);
convertView.setTag(new CategoryViewHolder(imageViewCheck,
textViewCN));
}
else {
CategoryViewHolder viewHolder = (CategoryViewHolder) convertView
.getTag();
imageViewCheck = viewHolder.getImageViewCheck();
textViewCN = viewHolder.getTextViewCategoryName();
}
imageViewCheck.setFocusable(false);
imageViewCheck.setFocusableInTouchMode(false);
imageViewCheck.setClickable(true);
imageViewCheck.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ImageView iv = (ImageView) v;
Category category = (Category) iv.getTag();
if (category.getChecked() == false) {
imageViewCheck.setImageResource(R.drawable.set_check);
listOfItemsToDelete.add(category.getId());
category.setChecked(true);
} else {
imageViewCheck
.setImageResource(R.drawable.set_basecircle);
listOfItemsToDelete.remove((Integer) category.getId());
category.setChecked(false);
}
}
});
imageViewCheck.setTag(category);
if (category.getChecked() == true)
imageViewCheck.setImageResource(R.drawable.set_check);
else
imageViewCheck.setImageResource(R.drawable.set_basecircle);
textViewCN.setText(category.getCatName());
return convertView;
}
}
private void loadDatabase() {
database = openOrCreateDatabase("WalletAppDatabase.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
This is my main layout code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
tools:context=".DeleteData" >
<RelativeLayout
android:id="#+id/relativeLayoutDeleteDataTopBar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
<TextView
android:id="#+id/textViewDeleteDataScreenTitle"
style="#style/screen_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Data" />
<ImageView
android:id="#+id/imageViewDeleteDataDelete"
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:src="#drawable/set_delete" />
</RelativeLayout>
<View
android:id="#+id/viewDeleteData"
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_below="#+id/relativeLayoutDeleteDataTopBar"
android:background="#drawable/shadow" />
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="#+id/linearLayoutDeleteDataAdMobBanner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical" >
<com.google.ads.AdView
android:id="#+id/adViewDeleteData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="a1512f50d8c3692"
ads:loadAdOnCreate="true"
ads:testDevices="TEST_EMULATOR, TEST_DEVICE_ID" />
</LinearLayout>
<ListView
android:id="#+id/listViewDeleteData"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#BDBDBD"
android:dividerHeight="1dp"
android:layout_below="#+id/viewDeleteData"
android:layout_above="#+id/linearLayoutDeleteDataAdMobBanner" >
</ListView>
</RelativeLayout>
And this is my custom layout code which i use to inflate in listview:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:padding="15dp" >
<TextView
android:id="#+id/textViewSingleRowDeleteData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
style="#style/listview_only_textview"
android:text="Category" />
<ImageView
android:id="#+id/imageViewSingleRowDeleteData"
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="#drawable/set_basecircle" />
</RelativeLayout>

Categories

Resources