Search listview using filter - java

I have a project in android studio that loads data from an online database and put that data in a listview. Above the listview there is an EditText that i want to search the listview with the value that i write inside. I tried to adapt this tutorial to mine but i get many errors and crashes that i cannot fix becaue i am a noob. Can you help me to adapt the tutorial to my project please? Below is my code without the search filter. If you want i can upload my try with the errors. Thank you in advance!
AllStudents.java:
public class AllStudents extends AppCompatActivity {
ListView StudentListView;
ProgressBar progressBar;
String HttpUrl = "http://sissy-nickels.000webhostapp.com/AllStudentData.php";
List<String> IdList = new ArrayList<>();
String LessonName;
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
String FinalJSonObject;
HashMap<String,String> ResultHash = new HashMap<>();
String ParseResult ;
List<Student> studentList;
#Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(AllStudents.this, AddStudent.class));
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_allstudents);
StudentListView = (ListView)findViewById(R.id.listview2);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
LessonName = getIntent().getStringExtra("Lesson");
HttpWebCall(LessonName);
//Adding ListView Item click Listener.
StudentListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(AllStudents.this,SingleStudent.class);
// Sending ListView clicked value using intent.
intent.putExtra("ListViewValue", IdList.get(position).toString());
startActivity(intent);
//Finishing current activity after open next activity.
finish();
}
});
}
public void HttpWebCall(final String LessonName){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(AllStudents.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(AllStudents.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("LessonName",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpUrl);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(LessonName);
}
// JSON parse class started from here.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
Student student;
studentList = new ArrayList<Student>();
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
student = new Student();
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
student.StudentName = jsonObject.getString("Regnum").toString();
studentList.add(student);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
StudentListView.setVisibility(View.VISIBLE);
ListAdapter adapter = new ListAdapter(studentList, context);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}}
ListAdapter.java
public class ListAdapter extends BaseAdapter {
Context context;
List<Student> valueList=null;
public ListAdapter(List<Student> listValue, Context context)
{
this.context = context;
this.valueList = listValue;
if(valueList==null){
valueList = new ArrayList<>();
}
}
#Override
public int getCount()
{
return this.valueList.size();
}
#Override
public Object getItem(int position)
{
return this.valueList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewItem viewItem;
convertView = null;
if(convertView == null)
{
viewItem = new ViewItem();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInfiater.inflate(R.layout.listviewitem, null);
viewItem.TextViewStudentName = (TextView)convertView.findViewById(R.id.textView1);
convertView.setTag(viewItem);
}
else
{
viewItem = (ViewItem) convertView.getTag();
}
viewItem.TextViewStudentName.setText(valueList.get(position).StudentName);
return convertView;
}}class ViewItem{ TextView TextViewStudentName;}
Student.java:
public class Student {
public String StudentName ;}
listview.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient"
android:padding="15dp">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="#android:color/holo_blue_dark"
android:textSize="24dp" />
avtivity_allstudents.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_show_all_students"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.djale.login_register.AllStudents"
android:background="#drawable/gradient"
>
<EditText
android:id="#+id/search"
android:layout_width="250dp"
android:layout_height="30dp"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:background="#11000000"
android:ems="10"
android:drawableLeft="#drawable/ic_search_black_24dp"
android:hint=" Search by reg. number"
android:inputType="textPersonName"
android:textColorHint="#android:color/holo_blue_dark"
android:textSize="18sp" />
<ListView
android:id="#+id/listview2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_below="#+id/search" />
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible"
/>

You can do like this :
search=(EditText)findviewById(R.id.search);
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
searchList=new ArrayList<>();
for(studentList name: String){
if(name.toLowerCase().contains(editable.toString().toLowerCase())){
searchList.add(name);
}
}
//clear data in adapter
//add searchList to your adapter
}
});

You can add TextChangedListener to your search box (which is a EditText). In onTextChanged(), filter list & update ListView accordingly.
In AllStudents.java, try making these changes:
public class AllStudents extends AppCompatActivity {
.....
#Override
protected void onCreate(Bundle savedInstanceState) {
....
StudentListView.setOnItemClickListener(...)
// add TextChangedListener to search box.
// It listens for user's entered text & filter students' list by name
EditText searchEditText = (EditText) findViewById(R.id.search);
searchEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged (CharSequence s, int start, int count, int after) {
}
// when text is entered in search box, filter list by search text
#Override
public void onTextChanged(CharSequence cs, int start, int before, int count) {
filterStudents(cs);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
// check student's name whether contain text entered in search box
private void filterStudents (CharSequence cs) {
List<Student> filteredList = new ArrayList<>();
if (TextUtils.isEmpty(cs)) {
// no text is entered for search, do nothing
return;
}
// build new student list which filtered by search text.
for (Student student : studentList) {
if (student.StudentName.contains(cs)) {
filteredList.add(student);
}
}
// show filtered list in listview
ListAdapter adapter = new ListAdapter(filteredList, this);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}

Related

ListView OnItemClickListener Crash when selecting json object

The application crashes when I tried to retrieve the JSON object to be used from searchActivity.java to searchDetail.java. It seems that the function getInfo() causes this problem. Initially, the list_data in getInfo() has size of 10, however after calling it from the searchActivity.java, the size becomes 0. Thus, may I know what can I do to solve this problem?
DataParser.java
public class DataParser extends AsyncTask<Void,Void,Integer> {
Context c;
ArrayList<Herb> herb=new ArrayList<>();
ArrayList<HashMap<String, String>> list_data = new ArrayList<HashMap<String, String>>();
HashMap<String,String> data = new HashMap<>();
public DataParser(ListView lv){
this.lv = lv;
}
public DataParser(Context c, String jsonData, ListView lv) {
this.c = c;
this.jsonData = jsonData;
this.lv = lv;
}
#Override
protected Integer doInBackground(Void... params) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result==0)
{
Toast.makeText(c,"Unable To Parse",Toast.LENGTH_SHORT).show();
}else {
//BIND DATA TO LISTVIEW
CustomAdapter adapter=new CustomAdapter(c,herb);
lv.setAdapter(adapter);
}
}
private int parseData()
{
try
{
JSONArray ja=new JSONArray(jsonData);
JSONObject jo=null;
herb.clear();
Herb Herb;
for(int i=0;i<ja.length();i++)
{
jo=ja.getJSONObject(i);
String id=jo.getString("h_id");
String name=jo.getString("h_name");
String imageUrl=jo.getString("h_image");
Herb=new Herb();
Herb.setId(id);
Herb.setName(name);
Herb.setImageUrl(imageUrl);
herb.add(Herb);
data.put("id",id);
data.put("name",name);
data.put("imageUrl",imageUrl);
list_data.add(data);
}
DataStorage.map = getInfo();
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
public ArrayList<HashMap<String, String>> getInfo(){
return this.list_data = list_data;
}
}
searchActivity.java
public class searchActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
ListView lv= (ListView) findViewById(R.id.HerbListView);
Downloader dl = new Downloader(searchActivity.this,urlAddress,lv);
dl.execute();
final DataParser dp = new DataParser(lv);
lv.setOnItemClickListener (new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try{
ArrayList<HashMap<String, String>> list_data = DataStorage.map;
String hid = list_data.get(position).get("id");
String name = list_data.get(position).get("name");
String imageUrl = list_data.get(position).get("imageUrl");
Intent intent = new Intent(searchActivity.this, searchDetail.class);
intent.putExtra("id", hid);
intent.putExtra("name", name);
intent.putExtra("imageUrl", imageUrl);
startActivity(intent);
}
catch (NullPointerException e){
e.printStackTrace();
}
}
});
}
}
searchDetail.java
public class searchDetail extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_detail);
String name = getIntent().getStringExtra("name");
String imageUrl = getIntent().getStringExtra("imageUrl");
TextView txt1= (TextView) findViewById(R.id.txtHName);
ImageView img= (ImageView) findViewById(R.id.imageHerb);
txt1.setText(name);
Picasso.with(this).load(imageUrl).fit().into(img);
}
}
DataStorage.java
public class DataStorage {
public static ArrayList<HashMap<String,String>> map = new ArrayList<>();
}
activity_search_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imageHerb"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:scaleType="fitXY" />
<TextView
android:id="#+id/lblHName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/imageHerb"
android:paddingTop="10dp"
android:text="Herb Name: " />
<TextView
android:id="#+id/txtHName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/imageHerb"
android:layout_toEndOf="#id/lblHName"
android:paddingTop="10dp"
android:text="TextView" />
</RelativeLayout>
current logcat generated
java.lang.IllegalStateException: Circular dependencies cannot exist in RelativeLayout
P/S: I cant find any circular dependencies in the activity_search_detail.xml
First execute the DataParser class ..new DataParser( lv).execute() or in ur case dp.execute() u are missing this statement.. If you are not executing the AsyncTask class it wont do any task in doInBackground(). Hopefully it will solve your problem.. dp.getinfo() will always return a blank list... make another class called class holdHashmapList {
public static ArrayList<Hashmap<String,String>> map= new ArrayList<>();} and in dataParser class holdHashmapList.map =getInfo();} and in onItemClick listener...Arralist<map<>> = holdHashmapList.map; Your hashmap that u are building will always contain the last last object... in parseData function... so before of data.put("id"); just add data=new HashMap<>();
you have to execute DataParser(dp) in order to populate your list_data in SearchActivity. only initializing DataParser won't populate the list_data.
public class searchActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
ListView lv= (ListView) findViewById(R.id.HerbListView);
Downloader dl = new Downloader(searchActivity.this,urlAddress,lv);
dl.execute();
final DataParser dp = new DataParser(lv);
dp.execute(); // update
lv.setOnItemClickListener (new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long
id) {
try{
ArrayList<HashMap<String, String>> list_data = dp.getInfo();
String hid = list_data.get(position).get("id");
String name = list_data.get(position).get("name");
String imageUrl = list_data.get(position).get("imageUrl");
Intent intent = new Intent(searchActivity.this, searchDetail.class);
intent.putExtra("id", hid);
intent.putExtra("name", name);
intent.putExtra("imageUrl", imageUrl);
startActivity(intent);
}
catch (NullPointerException e){
e.printStackTrace();
}
}
});
}

Android Firebase : Search in Custom Listview

I creating an app that has a custom listview. My problem is it not functioning properly. Look at the image below . That's my custom listview.
Image 1
Then when i want try to search . This happen .
Image 2
As you can see. The text in the Edittext is not matching with the result in custom listview. But when i try to click the result in custom listview. it redirect me on the page of the edittext string. My only problem is the text result in custom listview is not matching with the text input in the edittext.
This is my codes.
ListViewAdapter.java
public class LstViewAdapter extends ArrayAdapter<ArrayList> implements Filterable {
private Context context;
private int resource;
private int id;
private LstViewAdapter adapter;
private ArrayList arrayList;
private FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
private Filter filter;
public LstViewAdapter(Context context, int resource, int id, ArrayList arrayList){
super(context, resource, id, arrayList);
this.context = context;
this.resource = resource;
this.id = id;
this.arrayList = arrayList;
this.adapter = this;
}
// Hold views of the ListView to improve its scrolling performance
private static class ViewHolder {
public TextView type;
public ImageButton removeButton;
}
public View getView(final int position, final View convertView, ViewGroup parent) {
View rowView = convertView;
// Inflate the list_item.xml file if convertView is null
if(rowView==null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView= inflater.inflate(resource, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.type= (TextView) rowView.findViewById(R.id.txt);
viewHolder.removeButton= (ImageButton) rowView.findViewById(btn_del);
rowView.setTag(viewHolder);
}
final String x = (String) arrayList.get(position);
final String y = arrayList.get(position).toString().trim();
// Set text to each TextView of ListView item
ViewHolder holder = (ViewHolder) rowView.getTag();
holder.type.setText(x);
holder.removeButton.setBackgroundResource(R.drawable.deletes);
holder.removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
AlertDialog.Builder builder2=new AlertDialog.Builder(context);
builder2.setTitle("Delete Class");
builder2.setMessage("Do you want to delete class "+y+"?");
final EditText input = new EditText(context);
input.setHint("hint");
builder2.setIcon(R.drawable.deletes);
builder2.setPositiveButton("Delete",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
arrayList.remove(position);
notifyDataSetChanged();
Toast.makeText(v.getContext(), "Class " + y + " has been deleted", Toast.LENGTH_SHORT).show();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("users").child("teacher").child(user.getUid().toString().trim()).child("class").child(y);
mDatabase.setValue(null);
}
});
builder2.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder2.show();
}
});
return rowView;
}
#Override
public Filter getFilter() {
if (filter == null)
filter = new AppFilter<String>(arrayList);
return filter;
}
private class AppFilter<T> extends Filter {
private String sourceObjects;
public AppFilter(String objects) {
sourceObjects = new AppFilter<String>(arrayList);
synchronized (this) {
sourceObjects.addAll(objects);
}
}
#Override
protected FilterResults performFiltering(CharSequence chars) {
String filterSeq = chars.toString().toLowerCase();
FilterResults result = new FilterResults();
if (filterSeq != null && filterSeq.length() > 0) {
String filter = new AppFilter<String>(arrayList);
for (T object : sourceObjects) {
// the filtering itself:
if (object.toString().toLowerCase().contains(filterSeq))
filter.add(object);
}
result.count = filter.size();
result.values = filter;
} else {
// add all objects
synchronized (this) {
result.values = sourceObjects;
result.count = sourceObjects.size();
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// NOTE: this function is *always* called from the UI thread.
String filtered = (String) results.values;
notifyDataSetChanged();
clear();
for (int i = 0, l = filtered.size(); i < l; i++)
add((String) filtered.get(i));
notifyDataSetInvalidated();
}
}
}
MainActivity
public class MyClassesActivity extends AppCompatActivity {
private Button btnCreateClass;
private DatabaseReference mDatabase;
private ListView mUserList;
private ArrayList<String> mUsername = new ArrayList<>();
private FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
private FirebaseAuth auth;
final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid().toString().trim();
String selectedItem, value;
LstViewAdapter arrayAdapter;
private EditText inputSearch;
int textlength = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_classes);
getSupportActionBar().setTitle("My Classes");
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
btnCreateClass = (Button) findViewById(R.id.createclass);
mUserList = (ListView) findViewById(R.id.userlist);
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.setVisibility(View.GONE);
//get current user
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
arrayAdapter= new LstViewAdapter(this, R.layout.listitem,R.id.txt, mUsername);
mUserList.setAdapter(arrayAdapter);
mDatabase = FirebaseDatabase.getInstance().getReference().child("users").child("teacher").child(user.getUid().toString().trim()).child("class");
mDatabase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
value = dataSnapshot.getKey().toString().trim();
mUsername.add(value);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
btnCreateClass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MyClassesActivity.this, CreateClassActivity.class);
startActivity(intent);
}
});
mUserList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedItem = (String) parent.getItemAtPosition(position);
Intent intent = new Intent(MyClassesActivity.this, StudentListActivity.class);
intent.putExtra("secname", selectedItem);
startActivity(intent);
}
});
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
arrayAdapter.getFilter().filter(cs);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_class, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
if (id == R.id.search) {
inputSearch.setVisibility(View.VISIBLE);
inputSearch.requestFocus();
//Do something
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
listitem.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:descendantFocusability="blocksDescendants">
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginRight="10dp"
android:layout_alignParentLeft="true" />
<ImageButton
android:id="#+id/btn_del"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:src="#drawable/deletes"
android:onClick="onClick"
android:background="#android:color/transparent"
android:layout_alignParentRight="true" />

How to sort alphabetically in custom ListView

I need sort alphabetically in my custom ListView. In list_item, I have TextImage and two TextView (app name, package name) and can't understand how sort by alphabet app name:
My list item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal">
<ImageView
android:id="#+id/app_icon"
android:layout_width="56dp"
android:layout_height="56dp"
android:padding="4dp"
android:scaleType="centerCrop"
android:contentDescription="#null"
tools:src="#mipmap/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center|center_vertical"
android:orientation="vertical"
android:paddingLeft="8dp">
<TextView
android:id="#+id/tv_app_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textStyle="bold"
tools:text="Application name"/>
<TextView
android:id="#+id/tv_app_package"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textStyle="bold"
tools:text="app.package.name"/>
</LinearLayout>
</LinearLayout>
And my adapter:
public class ListViewAdapter extends ArrayAdapter{
private Context context;
private List mItem;
private PackageManager packageManager;
public ListViewAdapter(Context context, int list_item, List items) {
super(context, R.layout.list_item, items);
this.context = context;
this.mItem = items;
packageManager = context.getPackageManager();
}
public int getCount(){
return ((null != mItem) ? mItem.size() : 0);
}
#Override
public ApplicationInfo getItem(int position) {
return (null != mItem) ? (ApplicationInfo) mItem.get(position) : null;
}
public long getItemId(int position){
return position;
}
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
if (null == view) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_item, null);
}
ApplicationInfo data = (ApplicationInfo) mItem.get(position);
if (null != data){
TextView appName = (TextView) view.findViewById(R.id.tv_app_name);
TextView appPackage = (TextView) view.findViewById(R.id.tv_app_package);
ImageView icon = (ImageView) view.findViewById(R.id.app_icon);
appName.setText(data.loadLabel(packageManager));
appPackage.setText(data.packageName);
icon.setImageDrawable(data.loadIcon(packageManager));
}
return view;
}
}
My fragment in which show ListView
public class ResultFragment extends ListFragment {
private PackageManager packageManager = null;
private ListViewAdapter listViewAdapter = null;
private List mItem;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
packageManager = getContext().getPackageManager();
new LoadApplications().execute();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ApplicationInfo applicationInfo = (ApplicationInfo) mItem.get(position);
try{
Intent intent = packageManager.getLaunchIntentForPackage(applicationInfo.packageName);
if (intent != null){
startActivity(intent);
}
}catch (ActivityNotFoundException e){
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
}catch (Exception e){
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private List<ApplicationInfo> checkForLauncherIntent(List<ApplicationInfo> list){
ArrayList mItem = new ArrayList();
for(ApplicationInfo info : list) {
try{
if(packageManager.getLaunchIntentForPackage(info.packageName) != null) {
mItem.add(info);
}
} catch(Exception e) {
e.printStackTrace();
}
}
return mItem;
}
private class LoadApplications extends AsyncTask<Void, Void, Void>{
private ProgressDialog progressDialog = null;
#Override
protected Void doInBackground(Void... params){
mItem = checkForLauncherIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listViewAdapter = new ListViewAdapter(getActivity(), R.layout.list_item, mItem);
return null;
}
#Override
protected void onPostExecute(Void result){
setListAdapter(listViewAdapter);
progressDialog.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute(){
progressDialog = ProgressDialog.show(getActivity(), null, "Loading file info...");
super.onPreExecute();
}
}
}
Please help me by sorting my list alphabetically.
From Android Documentation
public abstract android.content.Intent
getLaunchIntentForPackage(java.lang.String packageName)
Returns a
"good" intent to launch a front-door activity in a package. This is
used, for example, to implement an "open" button when browsing through
packages. The current implementation looks first for a main activity
in the category Intent.CATEGORY_INFO, and next for a main activity in
the category Intent.CATEGORY_LAUNCHER. Returns null if neither are
found.
Parameters: packageName - The name of the package to inspect.
Returns: A fully-qualified Intent that can be used to launch the main
activity in the package. Returns null if the package does not contain
such an activity, or if packageName is not recognized.
You need to make some changes in your code
private ArrayList<ResolveInfo> checkForLauncherIntent(List<ApplicationInfo> list){
ArrayList<ResolveInfo> mItems = new ArrayList();
for(ApplicationInfo info : list) {
try{
if(packageManager.getLaunchIntentForPackage(info.packageName) != null) {
Intent intent = packageManager.getLaunchIntentForPackage(info.packageName));
ResolveInfo app = packageManager.resolveActivity(intent,0);
mItems.add(app);
}
} catch(Exception e) {
e.printStackTrace();
}
}
return mItems;
}
in your asn task
private class LoadApplications extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params){
ArrayList<ResolveInfo> mItem = checkForLauncherIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listViewAdapter = new ListViewAdapter(ctx, mItem);
return null;
}
#Override
protected void onPostExecute(Void result){
super.onPostExecute(result);
listView.setAdapter(listViewAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ResolveInfo resolveInfo = listViewAdapter.getItem(position);
ActivityInfo activityInfo = resolveInfo.activityInfo;
ComponentName name = new ComponentName(activityInfo.applicationInfo.packageName,activityInfo.name);
Intent intent = new Intent();
intent.setComponent(name);
startActivity(intent);
}
});
}
#Override
protected void onPreExecute(){
super.onPreExecute();
//progressDialog = ProgressDialog.show(getActivity(), null, "Loading file info...");
}
}
In your adapter constructor
public class ListViewAdapter extends BaseAdapter {
private Context context;
private ArrayList<ResolveInfo> mItem;
private PackageManager packageManager;
public ListViewAdapter(Context context, ArrayList<ResolveInfo> items) {
this.context = context;
this.mItem = items;
packageManager = context.getPackageManager();
Collections.sort(mItem,new ResolveInfo.DisplayNameComparator(packageManager));
}
public int getCount(){
return mItem.size();
}
#Override
public ResolveInfo getItem(int position) {
return mItem.get(position);
}
public long getItemId(int position){
return position;
}
public View getView(int position, View convertView, ViewGroup parent){
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.testa, null);
}
ResolveInfo app = mItem.get(position);
TextView appName = (TextView) convertView.findViewById(R.id.tv_app_name);
TextView appPackage = (TextView) convertView.findViewById(R.id.tv_app_package);
ImageView icon = (ImageView) convertView.findViewById(R.id.app_icon);
ActivityInfo activity = app.activityInfo;
appPackage.setText(activity.applicationInfo.packageName);
appName.setText(app.loadLabel(packageManager));
icon.setImageDrawable(app.loadIcon(packageManager));
return convertView;
}
}
Find the entire project At Github
First change The Chinese to pinyin you can use the jar pinyin4j-2.5.0.jar
then maybe you can try this method
Arrays.sort(arrayList,String.CASE_INSENSITIVE_ORDER);
Do this it will work
Create a class comparator like this
public class CustomComparator implements Comparator<ApplicationInfo> {
#Override
public int compare(ApplicationInfo o1, ApplicationInfo o2) {
return o1.loadLabel(packageManager).toString().compareTo(o2.loadLabel(packageManager).toString());
}
}
Now use this class in the Async Task where you are creating the adapter
Collections.sort(mItem, new CustomComparator());
listViewAdapter = new ListViewAdapter(context, mItem);
it will sort your list
Let me know in case of more issue
use this method when you need to sort in listview,
Collections.sort(apps, new Comparator<App>() {
#Override
public int compare(App lhs, App rhs) {
//here getTitle() method return app name...
return lhs.getTitle().compareTo(rhs.getTitle());
}
});
Please try this.
public class MainActivity extends AppCompatActivity {
private ArrayList<UserInfo> userInfos;
private CustomListAdapter customListAdapter;
private ListView customListView;
private String[] names={
"3 Khan",
"2 Ahmed",
"1 Iqbal"
};
private String[] professions={
"Rank 1",
"Rank 2",
"Rank 3"
};
private int[] photos={
R.drawable.sample_5,
R.drawable.sample_1,
R.drawable.sample_6
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setSupportActionBar((Toolbar)findViewById(R.id.toolbar));
customListView=(ListView)findViewById(R.id.custom_list_view);
userInfos=new ArrayList<>();
Arrays.sort(names,String.CASE_INSENSITIVE_ORDER);
customListAdapter=new CustomListAdapter(userInfos,this);
customListView.setAdapter(customListAdapter);
getDatas();
customListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this, "Name : " + names[i] + "\n Profession : " + professions[i], Toast.LENGTH_SHORT).show();
}
});
}
// getting all the datas
private void getDatas(){
for(int count=0;count<names.length;count++){
userInfos.add(new UserInfo(names[count],professions[count],photos[count]));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_option,menu);
MenuItem menuItem=menu.findItem(R.id.search);
SearchView searchView=(SearchView)menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
newText=newText.toString();
ArrayList<UserInfo> newUserInfos=new ArrayList<>();
for(UserInfo userInfo:userInfos){
String name=userInfo.getName().toLowerCase();
String profession=userInfo.getProfession().toLowerCase();
if(name.contains(newText) || profession.contains(newText)){
newUserInfos.add(userInfo);
}
}
customListAdapter.filterResult(newUserInfos);
customListAdapter.notifyDataSetChanged();
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}```

Not able to get the XML DOM parsed data on Main thread of process

I am not getting the desired output from the code.
I used XML DOM parsing to fetch title, pubdate, description and image from link: http://autosportsindia.com/feed
Through the code written no output is obtained. Even though Logcat shows that data is being fetched from the link.
Kindly tell me what is the fault in my code. Suggest any other method of XML parsing with code or link.
public class MainActivity extends AppCompatActivity implements ResultsCallBack {
PlaceholderFragment taskFragment;
ListView articlesListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
taskFragment = new PlaceholderFragment();
getSupportFragmentManager().beginTransaction().add(taskFragment, "MyFragment").commit();
} else {
taskFragment = (PlaceholderFragment) getSupportFragmentManager().findFragmentByTag("MyFragment");
}
taskFragment.startTask();
articlesListView = (ListView) findViewById(R.id.articlesListView);
}
#Override
public void onPreExecute() {
}
#Override
public void onPostExecute(ArrayList<HashMap<String, String>> results) {
articlesListView.setAdapter(new MyAdapter(this, results));
}
public static class PlaceholderFragment extends Fragment {
AutoSportsIndia downloadTask;
ResultsCallBack callBack;
public PlaceholderFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
callBack = (ResultsCallBack) activity;
if(downloadTask!=null)
{
downloadTask.onAttach(callBack);
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
public void startTask() {
if (downloadTask != null) {
downloadTask.cancel(true);
} else {
downloadTask = new AutoSportsIndia(callBack);
downloadTask.execute();
}
}
#Override
public void onDetach() {
super.onDetach();
callBack = null;
if(downloadTask!=null) {
downloadTask.onDetach();
}
}
}
public static class AutoSportsIndia extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
ResultsCallBack callBack =null;
public AutoSportsIndia(ResultsCallBack callBack) {
this.callBack = callBack;
}
public void onAttach(ResultsCallBack callBack) {
this.callBack = callBack;
}
public void onDetach() {
callBack = null;
}
protected void onPreExecute() {
if(callBack!=null)
{
callBack.onPreExecute();
}
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
String downloadURL = "http://autosportsindia.com/feed";
ArrayList<HashMap<String, String>> results = new ArrayList<>();
try {
URL url = new URL(downloadURL);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
InputStream inputStream = connection.getInputStream();
processXML(inputStream);
} catch (Exception e) {
L.m(e + "");
}
return results;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
if(callBack!=null)
{
callBack.onPostExecute(result);
}
}
public ArrayList<HashMap<String, String>> processXML(InputStream inputStream) throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document xmlDocument = documentBuilder.parse(inputStream);
Element rootElement = xmlDocument.getDocumentElement();
L.m("" + rootElement.getTagName());
NodeList itemsList = rootElement.getElementsByTagName("item");
NodeList itemChildren = null;
Node currentItem = null;
Node currentChild = null;
int count = 0;
ArrayList<HashMap<String, String>> results = new ArrayList<>();
HashMap<String, String> currentMap = null;
for (int i = 0; i < itemsList.getLength(); i++) {
currentItem = itemsList.item(i);
itemChildren = currentItem.getChildNodes();
currentMap = new HashMap<>();
for (int j = 0; j < itemChildren.getLength(); j++) {
currentChild = itemChildren.item(j);
if (currentChild.getNodeName().equalsIgnoreCase("title")) {
currentMap.put("title", currentChild.getTextContent());
String temp="title: "+currentChild.getTextContent();
L.m(temp);
}
if (currentChild.getNodeName().equalsIgnoreCase("pubDate")) {
String temp1="pubDate: "+currentChild.getTextContent();
currentMap.put("pubDate", currentChild.getTextContent());
L.m(temp1);
}
if (currentChild.getNodeName().equalsIgnoreCase("description")) {
currentMap.put("description", currentChild.getTextContent());
String temp="description: "+currentChild.getTextContent();
L.m(temp);
}
if (currentChild.getNodeName().equalsIgnoreCase("media:thumbnail")) {
count++;
if (count == 2) {
L.m(currentChild.getAttributes().item(0).getTextContent());
currentMap.put("imageURL", currentChild.getAttributes().item(0).getTextContent());
}
}
if (currentMap != null && !currentMap.isEmpty()) {
results.add(currentMap);
}
}
count = 0;
}
return results;
}
}
}
interface ResultsCallBack {
public void onPreExecute();
public void onPostExecute(ArrayList<HashMap<String, String>> results);
}
class MyAdapter extends BaseAdapter {
ArrayList<HashMap<String, String>> dataSource = new ArrayList<>();
Context context;
LayoutInflater layoutInflater;
public MyAdapter(Context context, ArrayList<HashMap<String, String>> dataSource) {
this.context = context;
this.dataSource = dataSource;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return dataSource.size();
}
#Override
public Object getItem(int position) {
return dataSource.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyHolder holder = null;
if(row == null)
{
row = layoutInflater.inflate(R.layout.custom_view, parent, false);
holder = new MyHolder(row);
row.setTag(holder);
}
else
{
holder = (MyHolder)row.getTag();
}
HashMap<String, String> currentItem = dataSource.get(position);
holder.articleTitleText.setText(currentItem.get("title"));
holder.articlePublishedDateText.setText(currentItem.get("pubDate"));
// holder.articleImage.setImageURI(Uri.parse(currentItem.get("imageURL")));
holder.articleDescriptionText.setText(currentItem.get("description"));
return row;
}
}
class MyHolder {
TextView articleTitleText;
TextView articlePublishedDateText;
ImageView articleImage;
TextView articleDescriptionText;
public MyHolder(View view) {
articleTitleText = (TextView)
view.findViewById(R.id.articleTitleText);
articlePublishedDateText = (TextView) view.findViewById(R.id.articlePublishedDate);
articleImage = (ImageView) view.findViewById(R.id.articleImage);
articleDescriptionText = (TextView) view.findViewById(R.id.articleDescriptionText);
}
}
XML pages:-
activity_main.xml
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/articlesListView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
custom_view.xml
<TextView
android:id="#+id/articleTitleText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:padding="12dp"
android:text="Title"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#444"/>
<TextView
android:id="#+id/articlePublishedDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/articleTitleText"
android:paddingBottom="4dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="4dp"
android:text="Date"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#444"/>
<View
android:id="#+id/separator1"
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_below="#+id/articlePublishedDate"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:background="#e67e22"/>
<ImageView
android:id="#+id/articleImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/separator1"
android:scaleType="fitCenter"
android:src="#drawable/ic_launcher"/>
<TextView
android:id="#+id/articleDescriptionText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/articleImage"
android:padding="12dp"
android:text="Description"
android:textColor="#444"/>
The processXML method builds and returns an ArrayList<HashMap<String, String>>.
It is called in the doInBackground method, but the return value is discarded. doInBackground then returns a local results object, which is an empty list.
If you had debugged your way through the processXML and doInBackground methods, you would have seen this. When I asked in a comment whether "you tried debugging your code, stepping through and seeing the values being processed", you obviously didn't.

using checkbox in android for displaying toast message in listview

What i have done::I have got s list of items from server & display in listview
each row of list has a checkbox in it, list view also has a button on top as show in figure below
What i need to do ::
out of six rows if i select three rows using checkbox on click of
button next showed in figure i must be able to display the toast
message of selected elements
I don't know how to fill the parts of onclick function of
checkButtonClick() in code
ListViewAdapterForAtomicListItemtype.java
public class ListViewAdapterForAtomicListItemtype extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapterForAtomicListItemtype(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item_for_atomic_list_item_type, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.textView_id_atomic_list_item_type);
// Capture position and set results to the TextViews
name.setText(resultp.get(MainActivity.NAME));
return itemView;
}
}
listview_main_atomic_list_itemtype.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/button1" />
<Button
android:id="#+id/button_of_listview_main_atomic_list_itemtype_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="DisplayItems" />
</RelativeLayout>
listview_item_for_atomic_list_item_type.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView_id_atomic_list_item_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<CheckBox
android:id="#+id/checkBox_atomic_list_item_type_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
</RelativeLayout>
BLD_IndividualListOfItems_Starters.java
public class BLD_IndividualListOfItems_Starters extends Activity{
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapterForAtomicListItemtype adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
String TYPE_FILTER;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main_atomic_list_itemtype);
TYPE_FILTER = getIntent().getExtras().getString("key_title");
Log.v("---- Value-Start---", TYPE_FILTER);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(BLD_IndividualListOfItems_Starters.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
String newurl = "?" + "Key=" + TYPE_FILTER;
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7005/RestaurantAtomicListItemType/"+newurl);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(MainActivity.NAME, jsonobject.getString("MasterListMenuName"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapterForAtomicListItemtype(BLD_IndividualListOfItems_Starters.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
private void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.button_of_listview_main_atomic_list_itemtype_id);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
{EDIT}
BLD_IndividualListOfItems_Starters.java
public class BLD_IndividualListOfItems_Starters extends Activity{
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapterForAtomicListItemtype adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
String TYPE_FILTER;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main_atomic_list_itemtype);
TYPE_FILTER = getIntent().getExtras().getString("key_title");
Log.v("---- Value-Start---", TYPE_FILTER);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(BLD_IndividualListOfItems_Starters.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
String newurl = "?" + "Key=" + TYPE_FILTER;
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7005/RestaurantAtomicListItemType/"+newurl);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(MainActivity.NAME, jsonobject.getString("MasterListMenuName"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapterForAtomicListItemtype(BLD_IndividualListOfItems_Starters.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
private void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.button_of_listview_main_atomic_list_itemtype_id);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder result = new StringBuilder();
for(int i=0;i<arraylist.size();i++)
{
if(adapter.mCheckStates.get(i)==true)
{
result.append(arraylist.get(i).get(MainActivity.NAME));
result.append("\n");
}
}
Toast.makeText(BLD_IndividualListOfItems_Starters.this, result, 1000).show();
}
});
}
}
ListViewAdapterForAtomicListItemtype.java
public class ListViewAdapterForAtomicListItemtype extends BaseAdapter implements android.widget.CompoundButton.OnCheckedChangeListener{
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
SparseBooleanArray mCheckStates;
public ListViewAdapterForAtomicListItemtype(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
mCheckStates = new SparseBooleanArray(data.size());
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item_for_atomic_list_item_type, parent, false);
// Get the position
CheckBox chkSelect =(CheckBox) itemView.findViewById(R.id.checkBox_atomic_list_item_type_id);
chkSelect.setTag(position);
chkSelect.setChecked(mCheckStates.get(position, false));
chkSelect.setOnCheckedChangeListener(this);
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.textView_id_atomic_list_item_type);
// Capture position and set results to the TextViews
name.setText(resultp.get(MainActivity.NAME));
return itemView;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
you can also use for MULTIPLE CHOICE OF LISTVIEW.
StringBuilder result;
After Click on Button you can do this:
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
result = new StringBuilder();
for (int i = 0; i < arraylist.size(); i++) {
if (adapter.mysparse.get(i) == true) {
result.append(arraylist.get(i).get(MainActivity.NAME));
result.append("\n");
}
}
Intent n = new Intent(MainActivity.this, DisplayActivity.class);
n.putExtra("buffer", result.toString());
startActivity(n);
}
});
And in your DisplayActivity you can do like this:
package com.example.singleitemlistview;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class DisplayActivity extends Activity {
ListView lv;
ArrayList<String> myList;
String myName;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Intent n = getIntent();
myName = n.getStringExtra("buffer");
myList = new ArrayList<String>();
lv = (ListView) findViewById(R.id.listViewData);
myList.add(myName);
lv.setAdapter(new ArrayAdapter<String>(DisplayActivity.this,
android.R.layout.simple_list_item_1, myList));
}
}
Use a SparseBooleanArray.
More info #
https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
In your adapter implement CompoundButton.OnCheckedChangeListener
public class ListViewAdapterForAtomicListItemtype extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{
SparseBooleanArray mCheckStates;
public ListViewAdapterForAtomicListItemtype(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
mCheckStates = new SparseBooleanArray(data.size());
}
Then in getView
CheckBox chkSelect =(CheckBox) item.findViewById(R.id.CheckBox
android:id="#+id/checkBox_atomic_list_item_type_id");
chkSelect.setTag(position);
chkSelect.setChecked(mCheckStates.get(position, false));
chkSelect.setOnCheckedChangeListener(this);
Override the following methods
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
In onClick of Button
StringBuilder result = new StringBuilder();
for(int i=0;i<arraylist.size();i++)
{
if(adapter.mCheckStates.get(i)==true)
{
result.append(arrayList.get(i).get(MainActivtiy.Name));
result.append("\n");
}
}
Toast.makeText(ActivityName.this, result, 1000).show();
Note:
It is better to use a ViewHolder Pattern.
http://developer.android.com/training/improving-layouts/smooth-scrolling.html
StringBuffer result = new StringBuffer();
result.append("TEXTVIEW 1 : ").append(chkbox1.isChecked());
result.append("\nTEXTVIEW 2 : ").append(chkbox2.isChecked());
result.append("\nTEXTVIEW 3 :").append(chkbox3.isChecked());
//and so on.........
Toast.makeText(MyAndroidAppActivity.this, result.toString(),
Toast.LENGTH_LONG).show();
I think this wat you need. Just update you got solution or not. this code must be in the next button onclickListener.
Try it out nd vote and ping if works. before tat update wats happening.
ADDED:
mainListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String ss;
ss=(String) ((TextView) view).getText();
This code is to check which item is clicked.
by this with lenght of the list , check in for loop to check whether its checkbox is clicked or not.
Aftert that you can easily append that list of checked items.
Never tried but should work..you can use following code inside onClick() to get CheckBox status for each row.
if (adapter!=null&&adapter.getCount()>0) {
for(int i=0;i<adapter.getCount();i++){
View view=(View)adapter.getItem(i);
CheckBox chk=(CheckBox)view.findViewById(R.id.checkbox);
TextView txt=(TextView)view.findViewById(R.id.textview);
if (chk.isChecked()) {
//do something here
}
}
}

Categories

Resources