Search In List View Android - 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) {
}
});

Related

How to set OnItemClickListener on ListView using CustomAdapter

I have displayed the list of student from the database, field that are displayed Student_Roll_no, Student_Name and Student_ID.
Student_Roll_no and Student_Name are display using TextView and Student_ID id is display with checkbox.
Now I want to set the code by which, when I click at the list the checkbox of that particular row should be checked but the listview is not responding to OnItemClickListener function, as there i have make a toast that doesn't appear when i click on the list.
Sry for the bad english
activity_attendence.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_attendence"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.tejas.paras.bpibs.Attendence"
android:orientation="vertical">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/roll"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:text="Roll"
android:layout_weight=".1"
android:textColor="#000000" />
<TextView
android:id="#+id/name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:text="Name"
android:layout_weight=".6"
android:textColor="#000000" />
<TextView
android:text="Present"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/textView26"
android:layout_weight=".2"
android:textColor="#000000" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:background="#000000"
android:layout_height="1dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"></LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="375dp"
android:id="#+id/listview"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_weight="1.10" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:text="Save Attendence"
android:layout_width="match_parent"
android:background="#drawable/buttonlayout2"
android:textColor="#FFFFFF"
android:layout_height="wrap_content"
android:id="#+id/button5" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
Attendence.java
package com.tejas.paras.bpibs;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
public class Attendence extends AppCompatActivity{
String date, course, year,ID;
String myJSON;
private static final String TAG_RESULTS = "result";
String link;
JSONArray peoples = null;
BufferedReader bufferedReader;
String result,data;
ArrayList<HashMap<String, String>> personList;
Button b5;
ListView list,listView;
private DataModel dataModel;
private ArrayList<DataModel> dataModels;
private static CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendence);
list=(ListView)findViewById(R.id.listview);
b5=(Button)findViewById(R.id.button5);
getData();
b5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(Attendence.this,"1."+view, Toast.LENGTH_SHORT).show();
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
dataModel = dataModels.get(position);
Toast.makeText(Attendence.this,"2.1",Toast.LENGTH_LONG).show();
ID=dataModel.getID();
Toast.makeText(Attendence.this,dataModel.getRoll(),Toast.LENGTH_LONG).show();
}
});
}
protected void showList() {
dataModels= new ArrayList<>();
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for (int i = 0; i < peoples.length(); i++) {
JSONObject c = peoples.getJSONObject(i);
dataModels.add(new DataModel(c.getString("name"),c.getString("id"), c.getString("roll")));
}
adapter = new CustomAdapter(dataModels, getApplicationContext());
list.setAdapter(adapter);
}
catch (JSONException e) {
e.printStackTrace();
}
}
public void getData() {
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
link = "http://painnation.esy.es/attendence.php?date=18022017&course=MCA&year=3";
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
return result;
}
#Override
protected void onPostExecute(String result) {
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
}
item_layout.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="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight=".1">
<TextView
android:id="#+id/roll"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textStyle="bold"
android:text="Roll"
android:layout_weight=".1"
android:textColor="#000000" />
<TextView
android:id="#+id/name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textStyle="bold"
android:text="Name"
android:layout_weight=".6"
android:textColor="#000000" />
<CheckBox
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/id"
android:layout_weight=".15"
android:textColor="#000000" />
</LinearLayout>
</LinearLayout>
CustomAdapter.java
package com.tejas.paras.bpibs;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends ArrayAdapter<DataModel> implements View.OnClickListener{
private ArrayList<DataModel> dataSet;
Context mContext;
private static class ViewHolder {
TextView name;
TextView roll;
CheckBox id;
}
public CustomAdapter(ArrayList<DataModel> data, Context context) {
super(context, R.layout.item_layout, data);
this.dataSet = data;
this.mContext=context;
}
#Override
public void onClick(View v) {
int position=(Integer) v.getTag();
Object object= getItem(position);
DataModel dataModel=(DataModel)object;
}
private int lastPosition = -1;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
DataModel dataModel = getItem(position);
ViewHolder viewHolder;
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_layout, parent, false);
viewHolder.name = (TextView) convertView.findViewById(R.id.name);
viewHolder.roll = (TextView) convertView.findViewById(R.id.roll);
viewHolder.id=(CheckBox) convertView.findViewById(R.id.id);
result=convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
lastPosition = position;
viewHolder.name.setText(dataModel.getName());
viewHolder.roll.setText(dataModel.getRoll());
viewHolder.id.setText(dataModel.getID());
return convertView;
}
}
DataModel.java
package com.tejas.paras.bpibs;
public class DataModel {
String roll;
String name;
String id;
public DataModel(String name1, String id1, String roll1) {
this.name=name1;
this.id=id1;
this.roll=roll1;
}
public String getName() {
return name;
}
public String getID() {
return id;
}
public String getRoll() {
return roll;
}
}
Attendence.php file and the database is hosted on a free hosting web server(Hostinger). you can check the DB output using the
http://painnation.esy.es/attendence.php?date=18022017&course=MCA&year=3
Output Screen
Data from server is fetch in json format.plz comment the code to do check the checkbox by clicking listview.
Thank You
i think you should put android:focusable="false" in item_layout.xml for checkbox, then onItemClickListener respond. for checkbox you need to put variable in DataModel, android make it true or false and change in listview put adapter.notifyDataSetChanged
<CheckBox
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/id"
android:layout_weight=".15"
android:focusable="false"
android:textColor="#000000" />

cant get profile image and button image in custom listview

i am a beginner in android programming and i made a custom list view which should present the user details by searching function. while i search the the user i get only the name and the mobile of the user but the default images is not presenting.
this is what i get:
and this is what i would like to get:
this is the layout for the each row in the list:
<?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" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffffff"
>
<ImageView
android:id="#+id/profileImage"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="#drawable/camera"
android:background="#drawable/border"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:textColor="#000000"
android:textSize="16dp"
android:text="Full name"
android:layout_marginTop="5dp"
android:layout_marginLeft="10dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/profileImage"
android:layout_toEndOf="#+id/profileImage" />
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:textColor="#000000"
android:textSize="14dp"
android:text="User details"
android:layout_toRightOf="#+id/profileImage"
android:layout_alignBottom="#+id/profileImage"
android:layout_toLeftOf="#+id/imageButtonInviteUser"
android:layout_toStartOf="#+id/imageButtonInviteUser"
android:layout_below="#+id/title" />
<ImageButton
android:layout_width="80dp"
android:layout_height="80dp"
android:src="#drawable/add_user_50"
android:id="#+id/imageButtonInviteUser"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#drawable/border"/>
<View
android:id="#+id/divider2"
android:layout_below="#+id/profileImage"
android:layout_width="fill_parent"
android:layout_marginTop="1dp"
android:layout_height="6dp"
android:background="#android:color/darker_gray"/>
</RelativeLayout>
</RelativeLayout>
main layout:
<?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">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/editTextSearch"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Search..." />
<View
android:id="#+id/divider1"
android:layout_below="#+id/editTextSearch"
android:layout_width="fill_parent"
android:layout_height="6dp"
android:background="#android:color/darker_gray"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/divider1"
android:id="#+id/scrollViewListView"
android:fillViewport="true"
android:layout_above="#+id/linearLayoutBtn">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/listViewusers"
android:layout_below="#+id/divider1"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</ScrollView>
<View
android:id="#+id/divider2"
android:layout_below="#+id/scrollViewListView"
android:layout_width="fill_parent"
android:layout_height="6dp"
android:background="#android:color/darker_gray"/>
<LinearLayout
android:id="#+id/linearLayoutBtn"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<Button android:text="Save"
android:id="#+id/ButtonSave"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</Button>
<Button android:text="Discard"
android:id="#+id/ButtonDiscard"
android:layout_toRightOf="#+id/ButtonSave"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</Button>
</LinearLayout>
</RelativeLayout>
custom adapter:
/**
* Created by matant on 9/24/2015.
*/
import java.util.List;
import com.example.matant.gpsportclient.R;
import com.example.matant.gpsportclient.Utilities.InviteUsersListRow;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class InviteUsersArrayAdapter extends ArrayAdapter<InviteUsersListRow> {
Context context;
List<InviteUsersListRow> rowUsers;
public InviteUsersArrayAdapter(Context context,int resourceId, List<InviteUsersListRow> items) {
super(context, resourceId, items);
this.context = context;
this.rowUsers = items;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
ImageButton imgStatus;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
InviteUsersListRow rowItem = (InviteUsersListRow) getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.invite_users_listview_row, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.profileImage);
holder.imgStatus = (ImageButton) convertView.findViewById(R.id.imageButtonInviteUser);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
holder.imgStatus.setImageResource(rowItem.getImageStatus());
return convertView;
}
#Override
public int getCount() {
return rowUsers.size();
}
#Override
public InviteUsersListRow getItem(int position) {
return rowUsers.get(position);
}
#Override
public long getItemId(int position) {
return rowUsers.indexOf(getItem(position));
}
}
row in list:
package com.example.matant.gpsportclient.Utilities;
/**
* Created by matant on 9/22/2015.
*/
public class InviteUsersListRow {
private int imageId,imagestatus;
private String title;
private String desc;
public InviteUsersListRow(int imageId,int status, String title,String desc){
this.imageId = imageId;
this.title = title;
this.desc = desc;
this.imagestatus = status;
}
public int getImageId() {
return this.imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getImageStatus(){
return this.imagestatus;
}
public void setImagestatus(int imgStatus)
{
this.imagestatus = imgStatus;
}
}
main activity:
package com.example.matant.gpsportclient.Controllers;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import com.example.matant.gpsportclient.AsyncResponse;
import com.example.matant.gpsportclient.R;
import com.example.matant.gpsportclient.Utilities.InviteUsersArrayAdapter;
import com.example.matant.gpsportclient.Utilities.InviteUsersListRow;
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 InviteUsersActivity extends AppCompatActivity implements AsyncResponse, View.OnClickListener,AdapterView.OnItemClickListener {
private EditText editTextSearch;
private Button btnSave,btnDiscard;
private ListView usersListView;
private List<InviteUsersListRow> rowUser;
private DBcontroller dbController;
public static final String EXTRA_USERS = "";
ListView listViewUsers;
List<InviteUsersListRow> rowUsers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_invite_users);
editTextSearch = (EditText) findViewById(R.id.editTextSearch);
btnSave = (Button) findViewById(R.id.ButtonSave);
btnDiscard = (Button)findViewById(R.id.ButtonDiscard);
editTextSearch.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) {
sendDataToDBController();
}
#Override
public void afterTextChanged(Editable s) {
}
});
btnDiscard.setOnClickListener(this);
}
#Override
public void handleResponse(String resStr) {
Log.d("invite_Response", resStr);
if (resStr != null) {
try {
JSONObject json = new JSONObject(resStr);
String flg = json.getString("flag");
Log.d("flag",flg);
switch (flg){
case "user found":{
JSONArray jsonarr = json.getJSONArray("users");
Log.d("array",jsonarr.toString());
rowUsers = new ArrayList<InviteUsersListRow>();
for(int i = 0; i < jsonarr.length();i++){
{
Log.d("user is", jsonarr.getJSONObject(i).toString());
String name = jsonarr.getJSONObject(i).getString("name");
String mobile = jsonarr.getJSONObject(i).getString("mobile");
InviteUsersListRow rowUser = new InviteUsersListRow(R.id.profileImage, R.id.imageButtonInviteUser, name, mobile);
rowUsers.add(rowUser);
}
listViewUsers = (ListView) findViewById(R.id.listViewusers);
InviteUsersArrayAdapter Useradapter = new InviteUsersArrayAdapter(this,R.layout.invite_users_listview_row,rowUsers);
listViewUsers.setAdapter(Useradapter);
listViewUsers.setOnItemClickListener(this);
}
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}else
Log.d("ServiceHandler", "Couldn't get any data from the url");
}
#Override
public void sendDataToDBController() {
String username = editTextSearch.getText().toString();
BasicNameValuePair tagreq = new BasicNameValuePair("tag", "search_user");
BasicNameValuePair name = new BasicNameValuePair("name", username);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(tagreq);
nameValuePairList.add(name);
dbController = new DBcontroller(this,this);
dbController.execute(nameValuePairList);
}
#Override
public void preProcess() {
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.ButtonDiscard:
{
Intent i = new Intent();
setResult(RESULT_CANCELED,i);;
finish();
}
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
Replace the below
InviteUsersListRow rowUser = new InviteUsersListRow(R.id.profileImage, R.id.imageButtonInviteUser, name, mobile);
with
InviteUsersListRow rowUser = new InviteUsersListRow(R.drawable.camera, R.drawable.add_user_50, name, mobile);
The pic should be from "R.drawable" not from "R.id"
You should actually set an image resource below and not an id
holder.imageView.setImageResource(rowItem.getImageId());
holder.imgStatus.setImageResource(rowItem.getImageStatus());
In the above code you are not setting a drawable item.

How to filter listview data from PHP JSON Parser

How i can filter data using textview in Listview , data are from PHP using JSON Parser. I searched already from the net but i don't get their point because they are using array of string while Im using parsed data from php. Thanks for those who will help.
This is the code
productlist.java
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class productlist extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
private EditText et;
int textlength = 0;
private static final String URl = "http://192.168.254.101/productlist.php";
private static final String TAG_POSTS = "message";
private static final String TAG_BRAND = "Brand";
private static final String TAG_CATEGORY = "Category";
private static final String TAG_DESCRIPTION = "Description";
private static final String TAG_CODE = "Code";
private static final String TAG_QUANTITY = "Quantity";
private static final String TAG_UNIT = "Unit";
private static final String TAG_UNITPRICE = "Unitprice";
private JSONArray mComments = null;
//manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productlist);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//loading the comments via AsyncTask
new LoadComments().execute();
}
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(URl);
try {
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
//gets the content of each tag
String brand = c.getString(TAG_BRAND);
String category = c.getString(TAG_CATEGORY);
String description = c.getString(TAG_DESCRIPTION);
String code = c.getString(TAG_CODE);
String quantity = c.getString(TAG_QUANTITY);
String unit = c.getString(TAG_UNIT);
String unitprice = c.getString(TAG_UNITPRICE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_BRAND, brand);
map.put(TAG_CATEGORY, category);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_CODE, code);
map.put(TAG_QUANTITY, quantity);
map.put(TAG_UNIT, unit);
map.put(TAG_UNITPRICE, unitprice);
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[] { TAG_BRAND, TAG_CATEGORY,
TAG_DESCRIPTION, TAG_CODE, TAG_QUANTITY, TAG_UNIT, TAG_UNITPRICE}, new int[]{ R.id.Brand, R.id.Category,
R.id.Description, R.id.Code, R.id.Quantity, R.id.Unit, R.id.Price });
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(productlist.this);
pDialog.setMessage("Loading Products...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
productlist.xml
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff" >
<LinearLayout
android:id="#+id/top_layover"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/EditText01"
android:layout_gravity="center_horizontal"
android:hint="Search.." />
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/bottom_layover"
android:layout_below="#+id/top_layover"
android:background="#fff"
android:divider="#android:color/transparent"
android:scrollbars="none" />
<LinearLayout
android:id="#+id/bottom_layover"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:orientation="horizontal"
android:weightSum="2" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
singlepost.xml
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#f0f0f0"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/box"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="5dp"
android:background="#ffffff">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="5dp"
android:text="Brand: ">
</TextView>
<TextView
android:id="#+id/Brand"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="5dp"
android:text="Category: " >
</TextView>
<TextView
android:id="#+id/Category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="5dp"
android:text="Description: " >
</TextView>
<TextView
android:id="#+id/Description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="5dp"
android:text="Code: " >
</TextView>
<TextView
android:id="#+id/Code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="5dp"
android:text="Quantity: ">
</TextView>
<TextView
android:id="#+id/Quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="5dp"
android:text="Unit: " >
</TextView>
<TextView
android:id="#+id/Unit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="5dp"
android:text="Price: " >
</TextView>
<TextView
android:id="#+id/Price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:textColor="#5d5d5d"
android:textStyle="bold" >
</TextView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
produclist.php
<?php
try{
$handler= new PDO('mysql:host=localhost;dbname=account','root','');
$handler->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(Exception $e){
echo $e->getMessage();
die();
}
$query =$handler->query( "Select * from tblproducts");
$records= array();
$records =$query->fetchAll(PDO::FETCH_ASSOC);
$json["message"]=$records;
echo json_encode($json);
?>
Please use below code which you will get idea and customize as your need
class CustomAdpter extends BaseAdapter implements Filterable{
LayoutInflater inflater = null;
Activity activity;
ItemFilter itemfilter = new ItemFilter();
public CustomAdpter(Activity a) {
this.activity = a;
inflater = LayoutInflater.from(a);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listBillingSearch.size();
//return 3;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listBillingSearch.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View view1, ViewGroup parent) {
ViewHolder holder;
if (view1 == null) {
view1 = inflater.inflate(R.layout.adpter_billing, null);
holder = new ViewHolder();
holder.txtBillingListCompanyName = (TextView) view1.findViewById(R.id.txtBillingListCompanyName);
holder.txtBillingListInvoice = (TextView) view1.findViewById(R.id.txtBillingListInvoice);
holder.txtBillingListStartDate = (TextView) view1.findViewById(R.id.txtBillingListStartDate);
holder.txtBillingListEndDate = (TextView) view1.findViewById(R.id.txtBillingListEndDate);
holder.txtBillingListVoiceCalls = (TextView) view1.findViewById(R.id.txtBillingListVoiceCalls);
holder.txtBillingListSMS = (TextView) view1.findViewById(R.id.txtBillingListSMS);
holder.txtBillingListDataPlan = (TextView) view1.findViewById(R.id.txtBillingListDataPlan);
view1.setTag(holder);
}else{
holder = (ViewHolder) view1.getTag();
}
holder.txtBillingListCompanyName.setText(listBillingSearch.get(position).getStrCompanyName());
holder.txtBillingListInvoice.setText(listBillingSearch.get(position).getStrInvoice());
holder.txtBillingListStartDate.setText(listBillingSearch.get(position).getStrStartDate());
holder.txtBillingListEndDate.setText(listBillingSearch.get(position).getStrEndDate());
holder.txtBillingListVoiceCalls.setText(listBillingSearch.get(position).getStrVoiceCall());
holder.txtBillingListSMS.setText(listBillingSearch.get(position).getStrSMS());
holder.txtBillingListDataPlan.setText(" "+listBillingSearch.get(position).getStrDataPlan());
return view1;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
return itemfilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<Billing> list = listBilling;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
ArrayList<Billing> filterdata = new ArrayList<Billing>();
if(constraint.equals(null) || constraint.equals("")){
//filterdata = listBilling;
results.values = listBilling;
results.count = listBilling.size();
}else{
// listBillingSearch.clear();
for (int i = 0; i < count; i++) {
filterableString = list.get(i).getStrCompanyName();
if (filterableString.toLowerCase().startsWith(filterString)) {
filterdata.add(listBilling.get(i));
}
}
results.values = filterdata;
results.count = filterdata.size();
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
//if(results.count > 0)
listBillingSearch = (ArrayList<Billing>) results.values;
notifyDataSetChanged();
}
}
}
public static class ViewHolder {
TextView txtBillingListCompanyName;
TextView txtBillingListInvoice ;
TextView txtBillingListStartDate;
TextView txtBillingListEndDate;
TextView txtBillingListVoiceCalls;
TextView txtBillingListSMS;
TextView txtBillingListDataPlan;
}
I hope it will help you.
Let me know if you find any issue.

ListFragment and Custom Adapter Issue

Two issue with List Fragment: 1. I have a class that extends ListFragments.In the onCreated, I am setting my custom Adapter. The issue is that when the user logs in, the adadpter is null and would not have a value until the user searches for an owner. As a result, it throws an exception when it tries to set up the listadapter and it finds the ArrayAdapter object to be null. I have a custome layout that has a listview and a textview, but I still gets the error. See sample code below. I bold the line of code where the issue happens. Also, I bold few other section where I think it may be important to notice.
I implemented Parcelable in the class "Owner" so that I can pass the object as a ParcelableArray. Even though the object is not null, retrieving it in the OwnerDetail class shows null as if I did not pass it it. I've seen several example, but I am not able to get it right. What am I doing wrong here?
Note: If I were to call the AsyncTask in the OwnerDetail class and set the ListAdapter, it will work fine. The issue with that is that it will display a list of owners as soon as the user is logged in which is not the expected behavior. The behavior that I want is to login first, search for an owner, display the owner, double click on an owner, and finally display a list of cars that the owner owns. I am doing this project, so I can learn how to use ListFraments.
// Here is the entire code
package com.mb.carlovers;
import android.os.Parcel;
import android.os.Parcelable;
public class Car implements Parcelable {
private String _make;
private String _model;
private String _year;
public Car()
{
this._make = "";
this._model = "";
this._year = "";
}
public Car(String make)
{
this._make = make;
}
public Car(String make, String year)
{
this._make = make;
this._year = year;
}
public Car(String make, String model, String year)
{
this._make = make;
this._model = model;
this._year = year;
}
//Getters
public String getMake()
{
return _make;
}
public String getModel()
{
return _model;
}
public String getYear()
{
return _year;
}
//Setters
public void setMake(String make)
{
_make = make;
}
public void setModel(String model)
{
_model = model;
}
public void setYear(String year)
{
_year = year;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
}
}
package com.mb.carlovers;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class CarDetail extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.customize_layout,container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
String[] myCars = {};
super.onActivityCreated(savedInstanceState);
ArrayAdapter<String> carAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_activated_1, myCars);
setListAdapter(carAdapter);
}
}
package com.mb.carlovers;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Login extends Activity implements OnClickListener{
private Button btnLogin;
private EditText etUsername, etPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
initializeVariables();
}
public void initializeVariables()
{
btnLogin = (Button) this.findViewById(R.id.bLogin);
etUsername = (EditText)this.findViewById(R.id.etUserName);
etPassword = (EditText)this.findViewById(R.id.etPassword);
btnLogin.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public void onClick(View v) {
Log.i("Tag", "In Onclick Litener");
String uName = etUsername.getText().toString();
String pWord = etPassword.getText().toString();
if(uName.equals("owner") && pWord.equals("1234"))
{
Log.i("Tag", "username =" + uName + "Password =" + pWord);
Intent intent = new Intent(this, People.class);
startActivity(intent);
}
}
}
package com.mb.carlovers;
import android.os.Parcel;
import android.os.Parcelable;
public class Owner implements Parcelable {
private String _firstName;
private String _lastName;
private String _carId;
private Car _car;
public Owner()
{
this._firstName = "";
this._lastName = "";
this._carId = "";
}
public Owner(String lName)
{
this._lastName = lName;
}
public Owner(String lName, String cId)
{
this._lastName = lName;
this._carId = cId;
}
public Owner(String lName, String fName, String cId)
{
this._lastName = lName;
this._firstName = fName;
this._carId = cId;
}
public Owner(String lName, String fName, String cId, Car car)
{
this._lastName = lName;
this._firstName = fName;
this._carId = cId;
this._car = car;
}
//Getters
public String getFirstName()
{
return _firstName;
}
public String getLastName()
{
return _lastName;
}
public String getCarId()
{
return _carId;
}
public Car getCar()
{
return _car;
}
//Setters
public void setFirstName(String fName)
{
_firstName = fName;
}
public void setLastName(String lName)
{
_lastName = lName;
}
public void setCarId(String cId)
{
_carId = cId;
}
public void setCar(Car car)
{
_car = car;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(_firstName);
dest.writeString(_lastName);
dest.writeString(_carId);
dest.writeParcelable(_car, flags);
}
public Owner(Parcel source){
_firstName = source.readString();
_lastName = source.readString();
_carId = source.readString();
_car = source.readParcelable(Car.class.getClassLoader());
}
public class MyCreator implements Parcelable.Creator<Owner> {
public Owner createFromParcel(Parcel source) {
return new Owner(source);
}
public Owner[] newArray(int size) {
return new Owner[size];
}
}
}
package com.mb.carlovers;
import com.mb.carlovers.adapter.OwnerAdapter;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class OwnerDetail extends ListFragment {
OwnerAdapter ownerAdapter = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.customize_layout,container, false);
}
#Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
Owner[] myOwners = null;
super.onCreate(savedInstanceState);
Bundle values = getActivity().getIntent().getExtras();
if(values != null)
{
myOwners = (Owner[]) values.getParcelableArray("test");
}
super.onActivityCreated(savedInstanceState);
ownerAdapter = new OwnerAdapter(getActivity(), R.layout.owner_detail , myOwners);
ownerAdapter.notifyDataSetChanged();
}
package com.mb.carlovers;
import java.util.List;
import com.mb.carlovers.asynctask.OnwerAsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class People extends FragmentActivity implements OnClickListener, OnItemSelectedListener {
private Button search;
private EditText etSearchBy, etSearchByID;
private Spinner spOption;
private String selectedOption = null;
private TextView tvErrorMessage;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.people);
InitializeVariables();
}
private void InitializeVariables()
{
etSearchBy = (EditText) this.findViewById(R.id.etByLastName);
etSearchByID = (EditText) this.findViewById(R.id.etCarID);
spOption = (Spinner) this.findViewById(R.id.spOption);
search = (Button) this.findViewById(R.id.bSearch);
search.setOnClickListener(this);
tvErrorMessage = (TextView) this.findViewById(R.id.tvErrorMessage);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.spOptions, android.R.layout.simple_spinner_dropdown_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spOption.setAdapter(adapter);
spOption.setOnItemSelectedListener(this);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onClick(View v) {
String searchByName = etSearchBy.getText().toString();
String searchById = etSearchByID.getText().toString();
if(selectedOption == null || selectedOption == "All")
{
if(searchByName.matches("") || searchById.matches(""))
{
tvErrorMessage.setText("You must select a last name and car id");
} else
{
}
} else if(selectedOption == "Name")
{
if(!searchByName.matches(""))
{
OnwerAsyncTask asynTask = new OnwerAsyncTask();
List<Owner> lt = null;
try {
lt = asynTask.execute("").get();
} catch (Exception e) {
e.printStackTrace();
}
Owner myOwners[] = lt.toArray(new Owner[lt.size()]);
Bundle data = new Bundle();
data.putParcelableArray("test", myOwners);
} else
{
tvErrorMessage.setText("You must enter the last name of the owner.");
}
} else if (selectedOption == "ID")
{
if(!searchById.matches(""))
{
String st = null;
String d = st;
} else
{
tvErrorMessage.setText("You must enter the car id that you'd like to search.");
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
switch(pos)
{
case 0:
selectedOption = "All";
break;
case 1:
selectedOption ="Name";
break;
case 2:
selectedOption ="ID";
break;
default:
selectedOption = null;
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
selectedOption ="ALL";
}
}
package com.mb.carlovers.adapter;
import com.mb.carlovers.Car;
import com.mb.carlovers.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CarAdapter extends ArrayAdapter<Car> {
private Context context;
private int layoutResourceId;
private Car data[] = null;
public CarAdapter(Context context, int resource, Car[] data) {
super(context, resource, data);
this.context = context;
this.layoutResourceId = resource;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CarHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new CarHolder();
holder.tvMake = (TextView) row.findViewById(R.id.tvMake);
holder.tvModel = (TextView) row.findViewById(R.id.tvModel);
holder.tvYear = (TextView) row.findViewById(R.id.tvYear);
row.setTag(holder);
} else
{
holder = (CarHolder) row.getTag();
}
Car item = data[position];
holder.tvMake.setText(item.getMake().toString());
holder.tvModel.setText(item.getModel().toString());
holder.tvYear.setText(item.getYear().toString());
return row;
}
public static class CarHolder
{
TextView tvMake;
TextView tvModel;
TextView tvYear;
}
}
package com.mb.carlovers.adapter;
import com.mb.carlovers.Owner;
import com.mb.carlovers.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class OwnerAdapter extends ArrayAdapter<Owner> {
private Context context;
private int layoutResourceId;
private Owner data[] = null;
public OwnerAdapter(Context context, int textViewResourceId,Owner[] data) {
super(context, textViewResourceId, data);
this.context = context;
this.layoutResourceId = textViewResourceId;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
OwnerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new OwnerHolder();
holder.tvFName = (TextView) row.findViewById(R.id.tvFirstName);
holder.tvLName = (TextView) row.findViewById(R.id.tvLastName);
holder.tvCId = (TextView) row.findViewById(R.id.tvCarID);
row.setTag(holder);
} else
{
holder = (OwnerHolder) row.getTag();
}
Owner item = data[position];
holder.tvFName.setText(item.getFirstName());
holder.tvLName.setText("Example");
holder.tvCId.setText("1");
return row;
}
static class OwnerHolder
{
TextView tvFName;
TextView tvLName;
TextView tvCId;
}
}
package com.mb.carlovers.asynctask;
import java.util.ArrayList;
import java.util.List;
import com.mb.carlovers.Car;
import android.os.AsyncTask;
public class CarAsyncTask extends AsyncTask<String, Void, List<Car>> {
private List<Car> item = null;
#Override
protected List<Car> doInBackground(String... params) {
item = new ArrayList<Car>();
item.add(new Car("Chevy","Caprice","2002"));
item.add(new Car("Chevy","Malibu","2014"));
item.add(new Car("Dodge","Stratus","2002"));
item.add(new Car("Saturn","L300","2004"));
return item;
}
#Override
protected void onPostExecute(List<Car> result) {
super.onPostExecute(result);
}
}
package com.mb.carlovers.asynctask;
import java.util.ArrayList;
import java.util.List;
import com.mb.carlovers.Owner;
import android.os.AsyncTask;
public class OnwerAsyncTask extends AsyncTask<String, Void, List<Owner>> {
private List<Owner> items = null;
#Override
protected List<Owner> doInBackground(String... params) {
try
{
items = new ArrayList<Owner>();
Owner own = new Owner();
own.setFirstName("John");
own.setLastName("Smith");
own.setCarId("1");
items.add(own);
Owner own1 = new Owner();
own1.setFirstName("Samantha");
own1.setLastName("Right");
own1.setCarId("2");
items.add(own1);
Owner own2 = new Owner();
own2.setFirstName("Regie");
own2.setLastName("Miller");
own2.setCarId("3");
items.add(own2);
Owner own3 = new Owner();
own3.setFirstName("Mark");
own3.setLastName("Adam");
own3.setCarId("4");
items.add(own3);
} catch(Exception ex)
{
ex.toString();
}
return items;
}
#Override
protected void onPostExecute(List<Owner> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
// car_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Car Detail Page" />
</LinearLayout>
// car_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvMake"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/tvModel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/tvYear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
//customize_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="#id/android:empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No record to be displayed."
/>
</LinearLayout>
//Login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Login" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Name"
android:textSize="30sp"
android:layout_marginTop="10dp"
android:layout_gravity="center"
/>
<EditText
android:id="#+id/etUserName"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:ems="10"
android:layout_gravity="center"
android:layout_marginTop="10dp"
>
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:textSize="30sp"
android:layout_marginTop="10dp"
android:layout_gravity="center"
/>
<EditText
android:id="#+id/etPassword"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:ems="10"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:inputType="textPassword" />
<Button
android:id="#+id/bLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="center"
android:text="Login" />
</LinearLayout>
//owner_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvFirstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
<TextView
android:id="#+id/tvLastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
<TextView
android:id="#+id/tvCarID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
</LinearLayout>
// People.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1"
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search by last name"
android:textSize="30sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
/>
<EditText
android:id="#+id/etByLastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search by car id"
android:textSize="30sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10sp"
/>
<EditText
android:id="#+id/etCarID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:layout_marginLeft="10dp"
android:layout_marginTop="10sp"
/>
<Spinner
android:id="#+id/spOption"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/spOptions"
/>
<TextView
android:id="#+id/tvErrorMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FF0000"
android:layout_marginTop="10dp"
android:text="" />
<Button
android:id="#+id/bSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Button" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="2"
>
<fragment
android:id="#+id/fOwnerDetail"
android:name="com.mb.carlovers.OwnerDetail"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
<fragment
android:id="#+id/fragment1"
android:name="com.mb.carlovers.CarDetail"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
/>
</LinearLayout>
</LinearLayout>
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(ownerAdapter);
}
}
Your code has a lot of problems:
1 Never call lifecycle methods on your own like you do in the OwnerDetail class with super.onActivityCreated(savedInstanceState);
2 Bundle values = getActivity().getIntent().getExtras(); ... values.getParcelableArray("test"); will normally fail because this piece of code will get the activity reference, get the Intent that started the activity and then try to find data passed in under the test key in that Intent. You don't pass such data to the People activity so there will be nothing to be found. You'd normally want to pass a Bundle containing the data at the moment of the creation of the fragment.
3 If you use the fragment in the xml layout you'll not be able to use a Bundle to pass data, instead you either add the fragment manually with transactions and then use a Bundle or you create a setter method in the fragment class and use that. So instead of Bundle data = new Bundle(); data.putParcelableArray("test", myOwners);, which does nothing, get a reference to your fragment and pass the myOwners array through a method.
4 Your AsyncTask will be pretty useless if you use them with .get() because the get() method will wait the AsyncTask to finish, blocking the UI tread as well. Instead you should just start the AsyncTask and then in the onPostExecute() pass the data around.
Here is an example with a simple method which will not change most of your code(which will happen if you manually add the fragments):
// where you start the owner asynctask
if(!searchByName.matches("")) {
OnwerAsyncTask asynTask = new OnwerAsyncTask(People.this);
asynTask.execute("");
}
//...
Then change the OnwerAsyncTask like this:
public class OnwerAsyncTask extends AsyncTask<String, Void, List<Owner>> {
private List<Owner> items = null;
private FragmentActivity mActivity;
public OnwerAsyncTask(FragmentActivity activity) {
mActivity = activity;
}
// doInBackground()...
#Override
protected void onPostExecute(List<Owner> result) {
//I'm assuming that items is the data you want to return, so
// find the OwnerDetail fragment and directly assign the data
OwnerDetail fragment = (OwnerDetail)mActivity.getSupportFragmentManager().findFragmentById(R.id.fOwnerDetail);
fragment.setData(); // to setData you'll pass the data you have in the AsyncTask
// the items list? or you transform that into an array?
}
and in the OwnerDetail fragment:
public class OwnerDetail extends ListFragment {
OwnerAdapter ownerAdapter = null;
public void setData() {
// update the adapter, create a new one etc.
}

onListItemClick is not working for listview?

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

Categories

Resources