I have ArrayList and I want to sort and group all data by header in Android.
How it is possible in Android? please help me.below me from owner And set header Me And Joe Manager From owner And set Header in listview. How to do that in Android?
My code in below::
public class Request extends Activity {
private String assosiatetoken;
private ArrayList<All_Request_data_dto> list = new ArrayList<All_Request_data_dto>();
ListView lv;
Button back;
private Spinner spndata;
String[] reqspinner = { "Request Date", "Last Update", "Type", "Owner",
"State" };
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.request);
assosiatetoken = MyApplication.getToken();
new doinbackground(this).execute();
back = (Button) findViewById(R.id.button1);
spndata = (Spinner) findViewById(R.id.list_all_quize_req);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, reqspinner);
spndata.setAdapter(adapter);
lv = (ListView) findViewById(R.id.listrequestdata);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Intent edit = new Intent(Request.this, Request_webview.class);
// edit.putExtra("Cat_url", url_link);
startActivity(edit);
}
});
spndata.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
switch (position) {
case 0:
list = DBAdpter.requestUserData(assosiatetoken);
Collections.sort(list, byDate1);
// Collections.reverse(list);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).submitDate != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
case 1:
list = DBAdpter.requestUserData(assosiatetoken);
Collections.sort(list, byDate);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).lastModifiedDate != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
case 2:
list = DBAdpter.requestUserData(assosiatetoken);
Collections.sort(list, byDate3);
// Collections.reverse(list);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).state != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
case 3:
list = DBAdpter.requestUserData(assosiatetoken);
for (int i = 0; i < list.size(); i++) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
break;
default:
break;
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
static final Comparator<All_Request_data_dto> byDate = new Comparator<All_Request_data_dto>() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
java.util.Date d1 = null;
java.util.Date d2 = null;
try {
d1 = sdf.parse(ord1.lastModifiedDate);
d2 = sdf.parse(ord2.lastModifiedDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (d1.getTime() > d2.getTime() ? -1 : 1); // descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
static final Comparator<All_Request_data_dto> byDate1 = new Comparator<All_Request_data_dto>() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
java.util.Date d1 = null;
java.util.Date d2 = null;
try {
d1 = sdf.parse(ord1.submitDate);
d2 = sdf.parse(ord2.submitDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (d1.getTime() > d2.getTime() ? -1 : 1); // descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
static final Comparator<All_Request_data_dto> byDate3 = new Comparator<All_Request_data_dto>() {
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
String d1 = null;
String d2 = null;
d1 = ord1.state;
d2 = ord2.state;
return d1.compareToIgnoreCase(d2);
}
};
class doinbackground extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
private Context ctx;
public doinbackground(Context c) {
ctx = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ctx);
pd.setMessage("Loading...");
pd.show();
}
#Override
protected Void doInBackground(Void... Params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pd.cancel();
}
}
public class MyListAdapter extends BaseAdapter {
private ArrayList<All_Request_data_dto> list;
public MyListAdapter(Context mContext,
ArrayList<All_Request_data_dto> list) {
this.list = list;
}
public int getCount() {
return list.size();
}
public All_Request_data_dto getItem(int position) {
return list.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.custom_request_data, null);
TextView req_id = (TextView) convertView.findViewById(R.id.req_txt);
TextView date = (TextView) convertView.findViewById(R.id.date_txt);
TextView owner = (TextView) convertView
.findViewById(R.id.owner_txt);
TextView state = (TextView) convertView
.findViewById(R.id.state_txt);
req_id.setText(list.get(position).requestId + " - "
+ list.get(position).title);
date.setText(list.get(position).lastModifiedDate + " - "
+ list.get(position).submitDate);
owner.setText(list.get(position).owner);
state.setText(list.get(position).state);
// }
return convertView;
}
}
}
you can make separate list for each category and make a list of these lists and make another list for category names than you can you use ExpandableListView and Adapter for this is like bellow. Here in example, it is used 2d array you can replace this with your list.
public class ExpAdapter extends BaseExpandableListAdapter {
private Context myContext;
String[][] arrChildelements;
String[] arrGroup;
public ExpAdapter(Context context, String[] arrGroup, String[][] arrChild) {
myContext = context;
this.arrGroup = arrGroup;
this.arrChildelements = arrChild;
}
public Object getChild(int groupPosition, int childPosition) {
return null;
}
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
public int getChildrenCount(int groupPosition) {
return arrChildelements[groupPosition].length;
}
public Object getGroup(int groupPosition) {
return null;
}
public int getGroupCount() {
return arrGroup.length;
}
public long getGroupId(int groupPosition) {
return 0;
}
public boolean hasStableIds() {
return false;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) myContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.group_row, null);
}
TextView tvGroupName = (TextView) convertView
.findViewById(R.id.tvGroupName);
tvGroupName.setText(arrGroup[groupPosition]);
return convertView;
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) myContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.child_row, null);
}
TextView tvPlayerName = (TextView) convertView
.findViewById(R.id.tvPlayerName);
tvPlayerName.setText(arrChildelements[groupPosition][childPosition]);
return convertView;
}
}
you have to write down your own Adapter. You can extends the BaseAdapter, for instance, and override the following methods:
getCount() it iwill returns the number of items in your dataset
getView() it will inflates your view
getItemViewType() Get the type of View that will be created by getView() (the group element Baroque/Classic in your example) or the "normal" item.
getViewTypeCount () the number of type of Views you have.
I am not sure but if you try to short your list then try this for string
public void sort(List<arraylist> itemLocationList) {
if(itemLocationList!=null)
{
Collections.sort(itemLocationList, new Comparator<arraylist>() {
#Override
public int compare(list o1, list o2) {
return o1.res_name.compareToIgnoreCase(o2.res_name);
}
});
}
}
i got solution on my question .Thanks Jignesh!!!
public class Request extends Activity {
private String assosiatetoken;
private ArrayList<All_Request_data_dto> list = new ArrayList<All_Request_data_dto>();
ListView lv;
ExpandableListView exlistView;
ArrayList<String> catOwner = new ArrayList<String>();
ArrayList<String> uniCatOner = new ArrayList<String>();
ArrayList<ArrayList<All_Request_data_dto>> masterOwner = new ArrayList<ArrayList<All_Request_data_dto>>();
ArrayList<String> catState = new ArrayList<String>();
ArrayList<String> uniCatState = new ArrayList<String>();
ArrayList<ArrayList<All_Request_data_dto>> masterState = new ArrayList<ArrayList<All_Request_data_dto>>();
Button back;
private Spinner spndata;
String[] reqspinner = { "Request Date", "Last Update", "Type", "Owner",
"State" };
ArrayAdapter<String> adapter;
ExpAdapter expAdapter;
private void setOwner() {
for (int i = 0; i < list.size(); i++) {
catOwner.add(list.get(i).owner);
}
HashSet<String> hasSetstate = new HashSet<String>(catOwner);
uniCatOner = new ArrayList<String>(hasSetstate);
for (String str : uniCatOner) {
ArrayList<All_Request_data_dto> cats = new ArrayList<All_Request_data_dto>();
masterOwner.add(cats);
}
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < uniCatOner.size(); j++) {
if (uniCatOner.get(j).equals(list.get(i).owner)) {
masterOwner.get(j).add(list.get(i));
}
}
}
}
private void setState() {
for (int i = 0; i < list.size(); i++) {
catState.add(list.get(i).state);
}
HashSet<String> hasSetstate = new HashSet<String>(catState);
uniCatState = new ArrayList<String>(hasSetstate);
for (String str1 : uniCatState) {
ArrayList<All_Request_data_dto> cats = new ArrayList<All_Request_data_dto>();
masterState.add(cats);
}
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < uniCatState.size(); j++) {
if (uniCatState.get(j).equals(list.get(i).state)) {
masterState.get(j).add(list.get(i));
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.request);
assosiatetoken = MyApplication.getToken();
list = DBAdpter.requestUserData(assosiatetoken);
exlistView = (ExpandableListView) findViewById(R.id.ExpList);
setOwner();
setState();
new doinbackground(this).execute();
back = (Button) findViewById(R.id.button1);
spndata = (Spinner) findViewById(R.id.list_all_quize_req);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, reqspinner);
spndata.setAdapter(adapter);
lv = (ListView) findViewById(R.id.listrequestdata);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Intent edit = new Intent(Request.this, Request_webview.class);
// edit.putExtra("Cat_url", url_link);
startActivity(edit);
}
});
spndata.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
switch (position) {
case 0:
list = DBAdpter.requestUserData(assosiatetoken);
Collections.sort(list, byDate1);
exlistView.setFocusable(false);
// Collections.reverse(list);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).submitDate != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
case 1:
list = DBAdpter.requestUserData(assosiatetoken);
exlistView.setVisibility(View.GONE);
Collections.sort(list, byDate);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).lastModifiedDate != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
case 2:
list = DBAdpter.requestUserData(assosiatetoken);
exlistView.setVisibility(View.GONE);
Collections.sort(list, byDate3);
// Collections.reverse(list);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).state != null) {
lv.setAdapter(new MyListAdapter(
getApplicationContext(), list));
}
}
break;
case 3:
lv.setVisibility(View.GONE);
expAdapter = new ExpAdapter(Request.this, uniCatOner,
masterOwner);
exlistView.setAdapter(expAdapter);
break;
case 4:
lv.setVisibility(View.GONE);
expAdapter = new ExpAdapter(Request.this, uniCatState,
masterState);
exlistView.setAdapter(expAdapter);
break;
default:
break;
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
static final Comparator<All_Request_data_dto> byDate = new Comparator<All_Request_data_dto>() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
java.util.Date d1 = null;
java.util.Date d2 = null;
try {
d1 = sdf.parse(ord1.lastModifiedDate);
d2 = sdf.parse(ord2.lastModifiedDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (d1.getTime() > d2.getTime() ? -1 : 1); // descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
static final Comparator<All_Request_data_dto> byDate1 = new Comparator<All_Request_data_dto>() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
java.util.Date d1 = null;
java.util.Date d2 = null;
try {
d1 = sdf.parse(ord1.submitDate);
d2 = sdf.parse(ord2.submitDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (d1.getTime() > d2.getTime() ? -1 : 1); // descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
static final Comparator<All_Request_data_dto> byDate3 = new Comparator<All_Request_data_dto>() {
public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
String d1 = null;
String d2 = null;
d1 = ord1.state;
d2 = ord2.state;
return d1.compareToIgnoreCase(d2);
}
};
class doinbackground extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
private Context ctx;
public doinbackground(Context c) {
ctx = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ctx);
pd.setMessage("Loading...");
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pd.cancel();
}
}
public class MyListAdapter extends BaseAdapter {
private ArrayList<All_Request_data_dto> list;
public MyListAdapter(Context mContext,
ArrayList<All_Request_data_dto> list) {
this.list = list;
}
public int getCount() {
return list.size();
}
public All_Request_data_dto getItem(int position) {
return list.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.custom_request_data, null);
TextView req_id = (TextView) convertView.findViewById(R.id.req_txt);
TextView date = (TextView) convertView.findViewById(R.id.date_txt);
TextView owner = (TextView) convertView
.findViewById(R.id.owner_txt);
TextView state = (TextView) convertView
.findViewById(R.id.state_txt);
req_id.setText(list.get(position).requestId + " - "
+ list.get(position).title);
date.setText(list.get(position).lastModifiedDate + " - "
+ list.get(position).submitDate);
owner.setText(list.get(position).owner);
state.setText(list.get(position).state);
// }
return convertView;
}
}
}
Related
I have created a custom listview adapter to fit a button, a custom chronometer and a textview. When i scroll my listview, the rows that are "hidden" refresh themselves and so chronometers, how can i keep chronometers running even if they're hidden?
I am quite new to Android development so i may have done something wrong; I know that listview refresh its rows when scrolled but maybe there's something that i missed to make chronometers running in background
public class MyCustomAdapter extends BaseAdapter {
ArrayList<String> users;
Context context;
LayoutInflater inflater = null;
public MyCustomAdapter(Activity mainActivity, ArrayList<String> usersList) {
// TODO Auto-generated constructor stub
users = usersList;
context = mainActivity;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return users.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return users.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
private class Holder {
TextView tv;
CustomChrono cr;
Button but;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.customized_list_view, null);
holder.tv = (TextView) rowView.findViewById(R.id.names_laps);
holder.cr = (CustomChrono) rowView.findViewById(R.id.chronometer_laps);
holder.but = (Button) rowView.findViewById(R.id.stop_button);
holder.cr.start();
holder.but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//((ListView) parent).performItemClick(v, position, 0);
holder.cr.stop();
stopped = true;
}
});
holder.tv.setText(users.get(position));
rowView.setTag(holder);
return rowView;
}
}
Then I have my activity class where I use this adapter
public class RunnerLaps extends AppCompatActivity {
ListView list;
ArrayList<String> runner_array;
private Map<Runner,String> map = new HashMap<Runner,String>(10);
private boolean isClicked = true;
private boolean isStartedNow = false;
boolean stopped = false;
ArrayList<Runner> arr_runners;
ArrayList<Runner> runners_arrList;
private long previousClickTime1 = 0;
Runner r = null;
String m = "";
SerializableManager serializableManager;
String filename = "myfile";
FileOutputStream outputStream = null;
ObjectOutputStream objectOutputStream = null;
//Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_runner_laps);
Intent i = getIntent();
serializableManager = new SerializableManager();
runner_array = (ArrayList<String>) getIntent().getSerializableExtra("KEY");
ArrayList<Runner> running = getIntent().getExtras().getParcelableArrayList("arr2");
runners_arrList = new ArrayList<Runner>(runner_array.size());
for (String r : runner_array)
{
runners_arrList.add(new Runner(r));
}
for (int f = 0; f < runners_arrList.size();f++)
{
Log.d("Runner: " + f,runners_arrList.get(f).getName());
}
m = getIntent().getExtras().getString("booly");
for (int j = 0; j < runner_array.size(); j++) {
Runner r = new Runner(runner_array.get(j));
map.put(r, runner_array.get(j));
}
if (m!= null)
{
stopped = true;
}
list = (ListView) findViewById(R.id.laps_list);
final MyCustomAdapter adapter = new MyCustomAdapter(RunnerLaps.this,runner_array);
list.setAdapter(adapter);
//addRunners();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomChrono chr = (CustomChrono) view.findViewById(R.id.chronometer_laps);
r = runners_arrList.get(position);
r.setTemp(System.currentTimeMillis());
long temp = r.getTemp();
previousClickTime1 = temp;
if (previousClickTime1 != 0 && previousClickTime1 - temp < 300)
{
if (stopped == true)
{
chr.stop();
r.laps[r.counter] = chr.getText().toString();
r.increaseCounter();
Intent i = new Intent (RunnerLaps.this,Runner_Display.class);
i.putExtra("key",(Serializable) r);
i.putParcelableArrayListExtra("arr",arr_runners);
for (int h = 0; h < runners_arrList.size();h++)
{
System.out.println(runners_arrList.get(h).getName() + "\n");
System.out.println(runners_arrList.get(h).laps[0] + "\n");
System.out.println(runners_arrList.get(h).laps[1] + "\n");
System.out.println(runners_arrList.get(h).laps[2] + "\n");
}
startActivity(i);
}
else
{
r.laps[r.counter] = chr.getText().toString();
r.increaseCounter();
for (int h = 0; h < runner_array.size();h++)
{
System.out.println(runners_arrList.get(h).getName() + "\n");
System.out.println(runners_arrList.get(h).laps[0] + "\n");
System.out.println(runners_arrList.get(h).laps[1] + "\n");
System.out.println(runners_arrList.get(h).laps[2] + "\n");
}
}
}
else
{}
}
});
}
}
Below is the code where i m parsing JSON and this method gets called onResume() method.
private void parseJSONSubTypeEventsSelect(String response)
throws JSONException {
JSONObject jsonObject = new JSONObject(response);
JSONArray columns = jsonObject.getJSONArray("columns");
JSONArray rowsWrapper = jsonObject.getJSONArray("rows");
JsonHelper jsonHelper = new JsonHelper();
List<List<String>> listOfListRow = new ArrayList<List<String>>();
Map<String, List<String>> map = new HashMap<>();
try {
for (int i = 0; i < rowsWrapper.length(); i++) {
if (i == rowsWrapper.length()) {
break;
} else {
map.put(rowsWrapper.get(i).toString(),jsonHelper.toList(rowsWrapper.getJSONArray(i)));
rowListSubTypeEvents = jsonHelper.toList(rowsWrapper.getJSONArray(i));
listOfListRow.add(rowListSubTypeEvents);
}
}
// System.out.println(listOfListRow);
} catch (Exception e1) {
e1.printStackTrace();
}
I am Clearing the data here but the same data is printed twice
StandName.clear();
slNo.clear();
Rate.clear();
System.out.println("StandName before"+StandName);
System.out.println("slNo before"+slNo);
System.out.println("Rate before"+Rate);
StandName.add("Select Stand Name");
slNo.add("");
Rate.add("");
System.out.println("StandName after"+StandName);
System.out.println("slNo after"+slNo);
System.out.println("Rate after"+Rate);
for (List<String> listRows : listOfListRow) {
int k = 0;
for (String value : listRows) {
k++;
switch (k) {
case 1:
imageMapCoords.add(value);
// listOfListRow.add(logoFileNameList);
break;
case 2:
slNo.add(value);
// listOfListRow.add(logoFileName1List);
break;
case 3:
StandName.add(value);
// listOfListRow.add(logoFileName1List);
break;
case 4:
Rate.add(value);
// listOfListRow.add(logoFileName1List);
break;
case 5:
avail.add(value);
// listOfListRow.add(logoFileName1List);
break;
case 6:
allowSeatSelection.add(value);
// listOfListRow.add(logoFileName1List);
break;
case 7:
panaromicView.add(value);
// listOfListRow.add(logoFileName1List);
break;
}
}
}
tvVenue.setText(Venue.get(Venue.size() - 1));
System.out.println("Stand names from third activity"+StandName);
System.out.println("data sending to pojo slNo "+slNo);
System.out.println("data sending to pojo StandName"+StandName);
System.out.println("data sending to pojo Rate"+Rate);
for (int i = 0; i <= rowsWrapper.length(); i++) {
RowItemThird item = new RowItemThird(slNo.get(i),StandName.get(i), Rate.get(i));
rowItems.add(item);
}
adapter = new CustomBaseAdapterThird(this, rowItems);
adapter.notifyDataSetChanged();
// lvThird.setAdapter(adapter);
spinner.setAdapter(adapter);
pDialog.hide();
pDialog.dismiss();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
positionCheckStandName = StandName.get(position);
System.out.println("positionCheckStandName"+positionCheckStandName);
positionSlNo = slNo.get(position);
stringRate = Rate.get(position);
System.out.println("SLNO"+positionSlNo);
/* spinner.getSelectedItemPosition();*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Below is the pojo class
public class RowItemThird {
private String mSlNo;
private String mStandName;
private String mRate;
public RowItemThird(String slNo, String StandName, String Rate) {
mSlNo = slNo;
mStandName = StandName;
mRate = Rate;
}
public String getmSlNo() {
return mSlNo;
}
public void setmSlNo(String mSlNo) {
this.mSlNo = mSlNo;
}
public String getmStandName() {
return mStandName;
}
public void setmStandName(String mStandName) {
this.mStandName = mStandName;
}
public String getmRate() {
return mRate;
}
public void setmRate(String mRate) {
this.mRate = mRate;
}
}
Below is the BaseAdapter class to add items to spinner
public class CustomBaseAdapterThird extends BaseAdapter
{
private Context mContext;
private List<RowItemThird> mRowItems;
TextView slNO;
TextView StandName;
TextView Rate;
public CustomBaseAdapterThird(Context context, List<RowItemThird> rowItems)
{
mContext = context;
mRowItems = rowItems;
}
#Override
public int getCount() {
return mRowItems.size();
}
#Override
public Object getItem(int position) {
return mRowItems.get(position);
}
#Override
public long getItemId(int position) {
return mRowItems.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = null;
LayoutInflater mInflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflator.inflate(R.layout.event_list_item_third_sub_type_event_select, null);
slNO = (TextView) convertView.findViewById(R.id.textViewSLNo);
StandName = (TextView) convertView.findViewById(R.id.textViewStand);
Rate = (TextView) convertView.findViewById(R.id.textViewRate);
RowItemThird row = (RowItemThird) getItem(position);
slNO.setText(row.getmSlNo());
StandName.setText(row.getmStandName());
Rate.setText(row.getmRate());
return convertView;
}
}
Every time you are adding the data to the rowItems object, which you are passing to the spinner adapter
adapter = new CustomBaseAdapterThird(this, rowItems);
adapter.notifyDataSetChanged();
So clear the ``rowItems` data before adding the new data
rowItems.clear();
for (int i = 0; i <= rowsWrapper.length(); i++) {
RowItemThird item = new RowItemThird(slNo.get(i),StandName.get(i), Rate.get(i));
rowItems.add(item);
}
I have created an activity to get and show data to a custom list view.
Now I have changed this to fragment but onItemclick does not work.
SiteNews.java
public class SiteNews extends Fragment implements OnTabChangeListener,
OnPageChangeListener {
private TabHost tabHost;
private ViewPager viewPager;
private FragmentPagerNewsAdapter fragmentPagerNewsAdapter;
int i = 0;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.tabs_news_layout, container, false);
// put tabhost here:
// ***************************** part 1
// ***************************************************
i++;
// init tabhost
this.initializeTabHost(savedInstanceState);
// init ViewPager
this.initializeViewPager();
// ***************************** part 1
// ***************************************************
return v;
}
private void initializeViewPager() {
List<Fragment> fragmentsnews = new Vector<Fragment>();
fragmentsnews.add(new FragmentAllNews());
fragmentsnews.add(new FragmentUnreadNews());
this.fragmentPagerNewsAdapter = new FragmentPagerNewsAdapter(
getChildFragmentManager(), fragmentsnews);
this.viewPager = (ViewPager) v.findViewById(R.id.viewPagernews);
this.viewPager.setAdapter(this.fragmentPagerNewsAdapter);
this.viewPager.setOnPageChangeListener(this);
}
// fake content for tabhost
class FakeContent implements TabContentFactory {
private final Context mContext;
public FakeContent(Context context) {
mContext = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumHeight(0);
v.setMinimumWidth(0);
return v;
}
}
private void initializeTabHost(Bundle args) {
tabHost = (TabHost) v.findViewById(android.R.id.tabhost);
tabHost.setup();
for (int i = 1; i <= 2; i++) {
TabHost.TabSpec tabSpec;
tabSpec = tabHost.newTabSpec("Tab " + i);
tabSpec.setIndicator("Tab " + i);
tabSpec.setContent(new FakeContent(getActivity()));
tabHost.addTab(tabSpec);
}
tabHost.setOnTabChangedListener(this);
}
#Override
public void onTabChanged(String tabId) {
int pos = this.tabHost.getCurrentTab();
this.viewPager.setCurrentItem(pos);
HorizontalScrollView hScrollView = (HorizontalScrollView) v
.findViewById(R.id.hScrollViewnews);
View tabView = tabHost.getCurrentTabView();
int scrollPos = tabView.getLeft()
- (hScrollView.getWidth() - tabView.getWidth()) / 2;
hScrollView.smoothScrollTo(scrollPos, 0);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
this.tabHost.setCurrentTab(position);
}
}
FragmentAllnews.java
public class FragmentAllNews extends Fragment implements View.OnClickListener {
ViewGroup v;
ListView list;
CustomAdapterAllNews adapter;
JSONObject json_data;
JSONArray jArray;
NewsGetData newsGetData;
ArrayList<String> id, title_news, text_news, cat_id, status;
String data, url, msg, check, readnumber, ACTION_SCAN, contents;
ArrayList<News> newsha;
News n;
int sizearray;
Resources res;
ArrayList<News> items;
News ne;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = (ViewGroup) inflater.inflate(R.layout.tabfragmentallnews,
container, false);
list = (ListView) v.findViewById(R.id.listallnews);
res = getResources();
createarray();
/* items = new ArrayList<News>();
for (int k = 0; k < 25; k++) {
ne = new News();
ne.setTitle_news("title_news " + String.valueOf(k));
ne.setText_news("text_news " + String.valueOf(k));
ne.setCat_id(k);
ne.setStatus(k);
items.add(ne);
}*/
ReadData task1 = new ReadData();
task1.execute(new String[] { "url address" });
return v;
}
private void createarray() {
id = new ArrayList<String>();
title_news = new ArrayList<String>();
text_news = new ArrayList<String>();
cat_id = new ArrayList<String>();
status = new ArrayList<String>();
id.clear();
title_news.clear();
text_news.clear();
cat_id.clear();
status.clear();
}
private class ReadData extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute() {
dialog.setMessage("Reading Data...");
dialog.show();
}
String text = "";
ArrayList<String> list1;
#Override
protected Boolean doInBackground(String... urls) {
url = "php url address";
InputStream is1;
for (String url1 : urls) {
// Read from web to InputStream
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// HttpPost post = new HttpPost(url1);
HttpResponse response = client.execute(post);
is1 = response.getEntity().getContent();
} catch (ClientProtocolException e) {
Toast.makeText(getActivity(), e.toString(),
Toast.LENGTH_LONG).show();
return false;
} catch (IOException e) {
Toast.makeText(getActivity(), e.toString(),
Toast.LENGTH_LONG).show();
return false;
}
// end of Read from web to InputStream
// Convert from InputStream to String Text
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(is1,
"iso-8859-1"), 8);
String line = null;
while ((line = reader.readLine()) != null) {
text += line + "\n";
}
is1.close();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// end of Convert from InputStream to String Text
// Convert from Text to JSON and add to ArrayList list1
list1 = new ArrayList<String>();
try {
JSONArray jArray = new JSONArray(text);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonData = jArray.getJSONObject(i);
list1.add(jsonData.getString("title_news") + " - "
+ jsonData.getString("text_news"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// end of Convert from Text to JSON and add to ArrayList list1
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
if (result == true) {
// add list1 to ArrayAdapter
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(
getActivity(), android.R.layout.simple_list_item_1,
list1);
// set adapter into listStudent
// list.setAdapter(adapter1);
Toast.makeText(getActivity(), text, Toast.LENGTH_LONG).show();
data = text;
newsha = parseJSON3(data);
adddata(newsha);
} else {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG)
.show();
}
dialog.dismiss();
}
}
/*
* #Override public void onItemClick(AdapterView<?> parent, View
* clickedView, int pos, long id) { TextView tv1 = (TextView)clickedView;
* int commaIndex = tv1.getText().toString().indexOf(","); String st_id =
* tv1.getText().toString().substring(0, commaIndex);
*
* Intent in = new Intent(this, EditDataActivity.class);
* in.putExtra("st_id", st_id); startActivity(in);
*
* }
*/
public void onItemClick(int mPosition) {
try {
News tempValues = (News) newsha.get(mPosition);
Toast.makeText(getActivity(), tempValues.getText_news(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Toast.makeText(CustomListView,"no", Toast.LENGTH_LONG).show();
}
}
public ArrayList<News> parseJSON3(String result) {
ArrayList<News> userha = new ArrayList<News>();
try {
jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
n = new News();
n.setId(json_data.getInt("id"));
id.add(String.valueOf(json_data.getInt("id")));
n.setTitle_news(json_data.getString("title_news"));
title_news.add(json_data.getString("title_news"));
n.setText_news(json_data.getString("text_news"));
text_news.add(json_data.getString("text_news"));
n.setCat_id(json_data.getInt("cat_id"));
cat_id.add(String.valueOf(json_data.getInt("cat_id")));
n.setStatus(json_data.getInt("status"));
status.add(String.valueOf(json_data.getInt("status")));
userha.add(n);
}
sizearray = text_news.size();
if (sizearray <= 0) {
Toast.makeText(getActivity(), "get data error",
Toast.LENGTH_LONG).show();
} else {
}
} catch (JSONException e) {
// toast(9);
}
return userha;
}
private void adddata(ArrayList<News> newsha2) {
adapter = new CustomAdapterAllNews(getActivity(), newsha2, newsha2, res);
list.setAdapter(adapter);
}
#Override
public void onClick(View v) {
}
}
CustomAdapterAllNews.java
public class CustomAdapterAllNews extends BaseAdapter implements OnClickListener {
/*********** Declare Used Variables *********/
private Activity activitynews;
private ArrayList datanews;
private static LayoutInflater inflaternews=null;
public Resources resnews;
News tempValuesnews=null;
int i=0;
TableLayout tableLayout1news;
private List<News> worldpopulationlistnews = null;
private ArrayList<News> arraylistnews;
/************* CustomAdapter Constructor *****************/
public CustomAdapterAllNews(Activity a, ArrayList d, List<News> worldpopulationlist, Resources resLocal) {
/********** Take passed values **********/
activitynews = a;
datanews=d;
resnews = resLocal;
this.arraylistnews = new ArrayList<News>();
this.worldpopulationlistnews = worldpopulationlist;
this.arraylistnews.addAll(worldpopulationlist);
/*********** Layout inflator to call external xml layout () **********************/
inflaternews = (LayoutInflater)activitynews.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if(datanews.size()<=0)
return 1;
return datanews.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder to contain inflated xml file elements ***********/
public static class ViewHolder{
public TextView text;
public TextView text1;
public ImageView image;
}
/*********** Depends upon data size called for each row , Create each ListView row ***********/
#SuppressLint("InflateParams")
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
/********** Inflate tabitem.xml file for each row ( Defined below ) ************/
vi = inflaternews.inflate(R.layout.list_news, null);
/******** View Holder Object to contain tabitem.xml file elements ************/
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.textlistnews);
holder.text1=(TextView)vi.findViewById(R.id.text1listnews);
holder.image=(ImageView)vi.findViewById(R.id.imagelistnews);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
if(datanews.size()<=0)
{
holder.text.setText("No Data");
holder.text1.setText("نتیجه یافت نشد");
holder.image.setImageResource(resnews.getIdentifier("com.iranvizhe:drawable/"+"image00",null,null));
}
else
{
/***** Get each Model object from Arraylist ********/
tempValuesnews=null;
tempValuesnews = (News) datanews.get(position);
/************ Set Model values in Holder elements ***********/
holder.text.setText(tempValuesnews.getTitle_news());
holder.text1.setText(tempValuesnews.getText_news());
holder.image.setImageResource(resnews.getIdentifier("com.iranvizhe:drawable/image0",null,null));
/******** Set Item Click Listner for LayoutInflater for each row ***********/
vi.setOnClickListener(new OnItemClickListener(position));
}
return vi;
}
#Override
public void onClick(View v) {
Log.v("CustomAdapter", "=====Row button clicked");
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
// FragmentAllNews sct = (FragmentAllNews)activitynews;
// Tab1Fragment sct = (Tab1Fragment)activity;
// sct.onItemClick(mPosition);
}
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlistnews.clear();
if (charText.length() == 0) {
worldpopulationlistnews.addAll(arraylistnews);
}
else
{
for (News wp : arraylistnews)
{
if (wp.getTitle_news().toLowerCase(Locale.getDefault()).contains(charText)
| wp.getText_news().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlistnews.add(wp);
}
}
}
notifyDataSetChanged();
}
}
When I put this code:
// FragmentAllNews sct = (FragmentAllNews)activitynews;
// Tab1Fragment sct = (Tab1Fragment)activity;
// sct.onItemClick(mPosition);
on click does not work for me and I need on click in list view.
Don't use v.setOnclicklistener() in adapter, better use in fragment only as below
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
try {
News tempValues = (News) newsha.get(mPosition);
Toast.makeText(getActivity(), tempValues.getText_news(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Toast.makeText(CustomListView,"no", Toast.LENGTH_LONG).show();
}
}
});
i am trying to filter the listview using edit text at the top but it providing null pointer exception in the adapter2.filter(text) of add text changed listener . please provide me some suggestion`
Here is my edit text`
friendsList.setAdapter(new FriendListAdapter(this));
search.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = search.getText().toString().toLowerCase(Locale.getDefault());
System.out.println("test=="+text);
adapter2.filter(text);
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
//adapter.getFilter().filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
Here is my adapter
public class FriendListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
FriendsList friendsList;
Context context;
ViewHolder holder;
private boolean userSelected = false;
private RadioButton mCurrentlyCheckedRB;
private int mResourceId = 0;
private LayoutInflater mLayoutInflater;
private RadioButton mSelectedRB;
private int mSelectedPosition = -1;
public FriendListAdapter(FriendsList friendsList) {
this.friendsList = friendsList;
if (Utility.model == null) {
Utility.model = new FriendsGetProfilePics();
}
Utility.model.setListener(this);
mInflater = LayoutInflater.from(friendsList.getBaseContext());
}
#Override
public int getCount() {
return jsonArray.length();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewgroup) {
JSONObject jsonObject = null;
Model model = (Model) getItem(position);
try {
jsonObject = jsonArray.getJSONObject(position);
} catch (JSONException e1) {
e1.printStackTrace();
}
View hView = convertView;
if (convertView == null) {
hView = mInflater.inflate(R.layout.friend_item, null);
ViewHolder holder = new ViewHolder();
holder.profile_pic = (ImageView) hView
.findViewById(R.id.profile_pic);
holder.name = (TextView) hView.findViewById(R.id.name);
holder.info = (TextView) hView.findViewById(R.id.info);
holder.radiobt = (RadioButton) hView.findViewById(R.id.radio);
hView.setTag(holder);
}
ViewHolder holder = (ViewHolder) hView.getTag();
if (position == getCount() - 1 && userSelected == false) {
holder.radiobt.setChecked(true);
mCurrentlyCheckedRB = holder.radiobt;
} else {
holder.radiobt.setChecked(false);
}
holder.radiobt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if((position != mSelectedPosition && mSelectedRB != null)){
mSelectedRB.setChecked(false);
}
mSelectedPosition = position;
mSelectedRB = (RadioButton)v;
System.out.println("onItemClick ");
try {
if (graph_or_fql.equals("graph")) {
System.out.println("in if loop ");
friendId = jsonArray.getJSONObject(position).getLong("id");
image = jsonArray.getJSONObject(position).getString("picture");
// sb.append(friendId).append(",");
freind_id = String.valueOf(friendId);
} else {
System.out.println("in else loop ");
friendId = jsonArray.getJSONObject(position).getLong("uid");
image = jsonArray.getJSONObject(position).getString(
"pic_square");
// sb.append(friendId).append(",");
freind_id = String.valueOf(friendId);
}
check = true;
name = jsonArray.getJSONObject(position).getString("name");
Toast.makeText(getApplicationContext(), "You Selected : " + name,
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
e.getMessage();
}
}
});
if(mSelectedPosition != position){
holder.radiobt.setChecked(false);
}else{
holder.radiobt.setChecked(true);
if(mSelectedRB != null && holder.radiobt != mSelectedRB){
mSelectedRB = holder.radiobt;
}
}
try {
if (graph_or_fql.equals("graph")) {
holder.profile_pic.setImageBitmap(Utility.model.getImage(
jsonObject.getString("id"),
jsonObject.getString("picture")));
} else {
holder.profile_pic.setImageBitmap(Utility.model.getImage(
jsonObject.getString("uid"),
jsonObject.getString("pic_square")));
}
} catch (JSONException e) {
holder.name.setText("");
}
try {
holder.name.setText(jsonObject.getString("name"));
} catch (JSONException e) {
holder.name.setText("");
}
try {
if (graph_or_fql.equals("graph")) {
holder.info.setText(jsonObject.getJSONObject("location")
.getString("name"));
} else {
JSONObject location = jsonObject
.getJSONObject("current_location");
holder.info.setText(location.getString("city") + ", "
+ location.getString("state"));
}
} catch (JSONException e) {
holder.info.setText("");
}
return hView;
}
// Filter Class
public void filter(String charText) {
System.out.println("in adapter filter");
charText = charText.toLowerCase(Locale.getDefault());
System.out.println("1");
rowitems.clear();
System.out.println("2");
if (charText.length() == 0) {
System.out.println("3");
rowitems.addAll(listData);
} else {
for (Model wp : listData) {
if (wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
rowitems.add(wp);
}
}
}
notifyDataSetChanged();
}
private class ViewHolder {
ImageView profile_pic;
TextView name;
TextView info;
// CheckBox check;
RadioButton radiobt;
}
}
Here is my main activity
public class FriendsList extends Activity implements OnItemClickListener{
private Handler mHandler;
public static Long friendId;
public static String name = "";
protected ListView friendsList;
protected static JSONArray jsonArray;
protected String graph_or_fql;
public Button bt;
public static String image = "0";
public boolean check = false;
public static String freind_id = "";
public boolean select = false;
public RadioButton radiobtn;
public ListView friendList;
private List<Model> rowitems=null;
ArrayList<Model> listData;
AdapterList adapter;
EditText search;
FriendListAdapter adapter2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
setContentView(R.layout.friends_list);
//radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
bt = (Button) findViewById(R.id.com_facebook_picker_done_button);
radiobtn = (RadioButton) findViewById(R.id.radio);
search=(EditText) findViewById(R.id.editText100);
Bundle extras = getIntent().getExtras();
String apiResponse = extras.getString("API_RESPONSE");
graph_or_fql = extras.getString("METHOD");
try {
if (graph_or_fql.equals("graph")) {
jsonArray = new JSONObject(apiResponse).getJSONArray("data");
} else {
jsonArray = new JSONArray(apiResponse);
}
} catch (JSONException e) {
e.printStackTrace();
e.getMessage();
return;
}
friendsList = (ListView) findViewById(R.id.friends_list);
// friendsList.setAdapter(new FriendListAdapter(this));
adapter2=new FriendListAdapter(this);
friendsList.setAdapter(adapter2);
friendsList.setOnItemClickListener(this);
search.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
adapter2.getFilter().filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
i am passing the facebook friend list to the listview.please provide some suggestion
Thanks in advance
For filter the listview using edit text at the top .
I used this code.
Make one list called searchResults than in onTextChanged method of edittext simply do this-
String searchString = `your edittext object`.getText().toString();
int textLength = searchString.length();
searchResults.clear();
for (int i = 0; i < `your main list of items`.size(); i++) {
String name = `your main list of items`.get(i).get("`your key`").toString();
System.out.println(" name " + name);
if (textLength <= title.length()) {
// compare the String in EditText with Names in the
// ArrayList
if (searchString.equalsIgnoreCase(name.substring(0, textLength))) {
searchResults.add(`your main list of items`.get(i));
System.out.println("the array list is "+ `your main list of items`.get(i));
mAdapter = new Adapter(this, searchResults);
`your ListView object`.setAdapter(mAdapter);
}
}
}
if (searchResults.isEmpty()) {
Toast toast = Toast.makeText(getApplicationContext(),"No Items Matched",Toast.LENGTH_SHORT);
toast.show();
mAdapter = new Adapter(this, searchResults);
`your ListView object`.setAdapter(mAdapter);
}
mAdapter.notifyDataSetChanged();
and on setOnItemClickListener just check searchResults.isEmpty() if true than use your your main list of items and if false than use searchResults list.
May be it will help you.try this.
change your filter with following code:
#Override
public Filter getFilter() {
//Log.d("in filter", "yes");
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
and set your list in this function and after set your list :
oReturn.values = YourList;
and finall
return oReturn;
and in Your search.addTextChangedListener(new TextWatcher()) just in onTextChanged add following line:
adapter2.getFilter().filter(s.toString());
Try this,
adapter2=new FriendListAdapter(this);
friendsList.setAdapter(adapter2);
I'm new to android. I have developed a calendar for my App and i want the user to be able to switch between months smoothly.
So I decided to use the ViewPager and to make it use unlimited amount of months i have implement this solution:
http://code.google.com/p/electricsleep/source/browse/trunk/src/com/androsz/electricsleepbeta/app/HistoryMonthActivity.java
Unfortunately it doesn't work for me. When I try to scroll left or right the next month to be showed comes until I scroll with the finger, but when i release my finger the earlier showed month comes again but the date on the indicator remains the right.
I post the code:
calendarView = new GridView(this);
calendarView.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
calendarView.setNumColumns(7);
adapter = new GridCellAdapter(getApplicationContext(), R.id.calendar_day_gridcell, newdatum);
adapter.notifyDataSetChanged();
calendarView.setAdapter(adapter);
calendarView.setTag(newdatum.toString());
viewpager = (ViewPager) this.findViewById(R.id.calviewpager);
viewpager.setAdapter(new MonthPagerAdapter());
viewpager.setOffscreenPageLimit(3);
mTitleIndicator = (TitlePageIndicator) findViewById(R.id.indicator);
mTitleIndicator.setViewPager(viewpager, 1);
mTitleIndicator.setOnPageChangeListener(new PageListener());
}
private class PageListener implements OnPageChangeListener{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
final DateTime old0 = DateTime.parse(viewpager.getChildAt(0).getTag().toString());
final DateTime old1 = DateTime.parse(viewpager.getChildAt(1).getTag().toString());
final DateTime old2 = DateTime.parse(viewpager.getChildAt(2).getTag().toString());
if (focusedPage == 0) {
Log.d("FOCUSEDPAGE=0",newdatum.toString());
DateTime minus = new DateTime();
minus=old0.minusMonths(1);
viewpager.getChildAt(0).setTag(minus.toString());
viewpager.getChildAt(1).setTag(old2.toString());
viewpager.getChildAt(2).setTag(old1.toString());
}
else if (focusedPage == 2) {
Log.d("FOCUSEDPAGE=2",newdatum.toString());
DateTime plus = new DateTime();
plus=old2.plusMonths(1);
viewpager.getChildAt(0).setTag(old1.toString());
viewpager.getChildAt(1).setTag(old2.toString());
viewpager.getChildAt(2).setTag(plus.toString());
}
mTitleIndicator.setCurrentItem(1);
}
}
#Override
public void onPageSelected(int position) {
newdatum=DateTime.parse(viewpager.getChildAt(position).getTag().toString());
focusedPage = position;
}
}
private class MonthPagerAdapter extends PagerAdapter{
ViewPager container;
private GridView addMonthViewAt(int position, DateTime date) {
final GridView gv = new GridView(CalendarActivity.this);
gv.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
gv.setNumColumns(7);
gv.setTag(date.toString());
setGridCellAdapterToDate(date, gv);
container.addView(gv, position);
return gv;
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeViewAt(position);
}
#Override
public void finishUpdate(View container) {
}
#Override
public int getCount() {
return 3;
}
#Override
public Object instantiateItem(View container, int pos) {
this.container = (ViewPager) container;
DateTime newdate=newdatum.plusMonths(pos-1);
Log.d("INSTATIATE",newdate.toString());
return addMonthViewAt(pos, newdate);
}
#Override
public String getPageTitle(int position) {
final GridView gv = (GridView) container.getChildAt(position);
DateTime dt=DateTime.parse(gv.getTag().toString());
String title=dt.monthOfYear().getAsText()+" "+dt.getYear();
Log.d("GET PAGE TITLE",dt.toString());
return title;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View container) {
}
}
private void setGridCellAdapterToDate(DateTime newdate, GridView gridview){
GridCellAdapter adapt = new GridCellAdapter(getApplicationContext(), R.id.calendar_day_gridcell, newdate);
adapt.notifyDataSetChanged();
gridview.setAdapter(adapt);
}
And the GridCellAdapter code:
public class GridCellAdapter extends BaseAdapter implements OnClickListener{
private final Context _context;
private final List<String> list;
private Button gridcell;
public GridCellAdapter(Context context, int textViewResourceId, DateTime datum){
super();
this._context = context;
this.list = new ArrayList<String>();
printMonth(datum);
}
public String getItem(int position){
return list.get(position);
}
public int getCount(){
return list.size();
}
private void printMonth(DateTime cal){
int daysInMonth = cal.dayOfMonth().getMaximumValue();
int daysInPrevMonth = cal.minusMonths(1).dayOfMonth().getMaximumValue()+1;
int trailingSpaces = cal.withDayOfMonth(1).dayOfWeek().get()-1;
SQLiteAdapter sql= new SQLiteAdapter(getApplicationContext());
sql.openToWrite(month(cal));
if(sql.tableExists()){
String back="blue";
for(int i=0;i<7;i++)
list.add("DAY:"+cal.withDayOfWeek(i+1).toString()+": ");
for (int i = 0; i < trailingSpaces; i++){
if(sql.rowExists(cal.minusMonths(1).withDayOfMonth((daysInPrevMonth-trailingSpaces)+i).toString("yyyy-MM-dd")))
back="green";
else back="blue";
list.add("GREY:"+cal.minusMonths(1).withDayOfMonth((daysInPrevMonth-trailingSpaces)+i).toString("yyyy-MM-dd")+": "+":"+back);
}
for (int i = 1; i <= daysInMonth; i++){
if(sql.rowExists(cal.withDayOfMonth(i).toString("yyyy-MM-dd")))
back="green";
else back="blue";
if (cal.withDayOfMonth(i).toString("yyyy-MM-dd").equals(DateTime.now().toString("yyyy-MM-dd"))){
list.add("WHITE:"+cal.withDayOfMonth(i).toString("yyyy-MM-dd")+":"+checkIsFeiertag(cal.withDayOfMonth(i)).toString()+":"+back);
}
else{
checkIsFeiertag(cal.withDayOfMonth(i));
list.add("BLUE:"+cal.withDayOfMonth(i).toString("yyyy-MM-dd")+":"+checkIsFeiertag(cal.withDayOfMonth(i)).toString()+":"+back);
}
}
for (int i = 0; i < list.size() % 7; i++){
if(sql.rowExists(cal.plusMonths(1).withDayOfMonth(i+1).toString("yyyy-MM-dd")))
back="green";
else back="blue";
list.add("GREY:"+cal.plusMonths(1).withDayOfMonth(i+1).toString("yyyy-MM-dd")+": "+":"+back);
}
}
else{
for(int i=0;i<7;i++)
list.add("DAY:"+cal.withDayOfWeek(i+1).toString()+": "+": ");
for (int i = 0; i < trailingSpaces; i++){
list.add("GREY:"+cal.minusMonths(1).withDayOfMonth((daysInPrevMonth-trailingSpaces)+i).toString("yyyy-MM-dd")+": "+": ");
}
for (int i = 1; i <= daysInMonth; i++){
if (cal.withDayOfMonth(i).toString("yyyy-MM-dd").equals(DateTime.now().toString("yyyy-MM-dd"))){
list.add("WHITE:"+cal.withDayOfMonth(i).toString("yyyy-MM-dd")+":"+checkIsFeiertag(cal.withDayOfMonth(i)).toString()+": ");
}
else{
checkIsFeiertag(cal.withDayOfMonth(i));
list.add("BLUE:"+cal.withDayOfMonth(i).toString("yyyy-MM-dd")+":"+checkIsFeiertag(cal.withDayOfMonth(i)).toString()+": ");
}
}
for (int i = 0; i < list.size() % 7; i++){
list.add("GREY:"+cal.plusMonths(1).withDayOfMonth(i+1).toString("yyyy-MM-dd")+": "+": ");
}
}
sql.close();
}
public long getItemId(int position){
return position;
}
#SuppressLint("NewApi")
public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
if(row == null){
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.calendar_day_gridcell, parent, false);
}
gridcell = (Button) row.findViewById(R.id.calendar_day_gridcell);
String[] day_color = list.get(position).split(":");
DateTime datum = DateTime.parse(day_color[1]);
if(!(day_color[0].equals("DAY"))){
gridcell.setText(String.valueOf(datum.getDayOfMonth()));
gridcell.setTag(datum.toString("yyyy-MM-dd"));
gridcell.setOnClickListener(this);
if (!day_color[2].equals(" "))
gridcell.setTextColor(Color.RED);
else if (day_color[0].equals("GREY"))
{
gridcell.setTextColor(Color.LTGRAY);
}
else if (day_color[0].equals("WHITE"))
{
gridcell.setTextColor(Color.WHITE);
}
else if (day_color[0].equals("BLUE"))
{
gridcell.setTextColor(getResources().getColor(R.color.static_text_color));
}
if(day_color[3].equals("green")){
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
gridcell.setBackgroundDrawable(getResources().getDrawable(R.drawable.calendar_tile_green));
} else {
gridcell.setBackground(getResources().getDrawable(R.drawable.calendar_tile_green));
}
}
}
else {
gridcell.setText(datum.toString("EE"));
gridcell.setClickable(false);
}
gridcell.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
if(gridcell.getBackground()==getResources().getDrawable(R.drawable.calendar_tile_green)){
SQLiteAdapter sql= new SQLiteAdapter(context);
DateTime bt = DateTime.parse(gridcell.getTag().toString());
sql.openToWrite(month(bt));
sql.getRows(month(bt));
sql.close();
}
return true;
}
});
return row;
}
Of course I'm accepting different solutions to provide the same smoothing scrolling.