I am new in Android development, I want to bind a Json array to android AutocompleteTextView in Form (Registration form).
the Json array is showed in below
{"Status":true,"errorType":null,"InstituteList":[{"InstituteID":"1","InstituteName":"Demo Institute"},{"InstituteID":"16","InstituteName":"Sheridan College"},{"InstituteID":"17","InstituteName":"iCent Prosp"},{"InstituteID":"18","InstituteName":"Seneca College"}]}
here the Type Institution Name is the auto completeTextView. The main requirement is that, I can bind the values like in the Json response InstituteName on the front end and When click on the Submit Button it needs to take the InstituteID Object.
Currently I can bind the InstituteName Object to AutocompleteTextView and Working fine.
But the Submit Action was not performing perfectly.
I cant getting the InstituteID in my codes for performing
Here is my code.
Getting response from web service as json array and binding in asyncTask.
#Override
protected void onPostExecute(String res) {
try
{
Log.i("Intitute List",res);
JSONObject responseObject = new JSONObject(res);
String status=responseObject.getString("Status");
ArrayList<String> listInstituteNames = new ArrayList<>();
JSONArray detailsArray = responseObject.getJSONArray("InstituteList");
for (int i = 0; i <detailsArray.length() ; i++) {
JSONObject obj = detailsArray.getJSONObject(i);
listInstituteNames.add(obj.getString("InstituteName"));
}
//Log.i("InstituteName", String.valueOf(listInstituteNames));
myStringArray = listInstituteNames;
AutoCompleteAdapter adapter = new AutoCompleteAdapter(SignUpActivity.this, android.R.layout.simple_dropdown_item_1line, android.R.id.text1, listInstituteNames);
autoTextView.setThreshold(1);
autoTextView.setAdapter(adapter);
}
catch (JSONException e1) {
e1.printStackTrace();
}
AutoCompleteAdapter.java
package Adapter;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
public class AutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
private ArrayList<String> fullList;
private ArrayList<String> mOriginalValues;
private ArrayFilter mFilter;
public AutoCompleteAdapter(Context context, int resource, int textViewResourceId, List<String> objects) {
super(context, resource, textViewResourceId, objects);
fullList = (ArrayList<String>) objects;
mOriginalValues = new ArrayList<String>(fullList);
}
#Override
public int getCount() {
return fullList.size();
}
#Override
public String getItem(int position) {
return fullList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return super.getView(position, convertView, parent);
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ArrayFilter();
}
return mFilter;
}
private class ArrayFilter extends Filter {
private Object lock;
#Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (mOriginalValues == null) {
synchronized (lock) {
mOriginalValues = new ArrayList<String>(fullList);
}
}
if (prefix == null || prefix.length() == 0) {
synchronized (lock) {
ArrayList<String> list = new ArrayList<String>(mOriginalValues);
results.values = list;
results.count = list.size();
}
} else {
final String prefixString = prefix.toString().toLowerCase();
ArrayList<String> values = mOriginalValues;
int count = values.size();
ArrayList<String> newValues = new ArrayList<String>(count);
for (int i = 0; i < count; i++) {
String item = values.get(i);
if (item.toLowerCase().contains(prefixString)) {
newValues.add(item);
}
}
results.values = newValues;
results.count = newValues.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if(results.values!=null){
fullList = (ArrayList<String>) results.values;
}else{
fullList = new ArrayList<String>();
}
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
AutoCompleteTextView Section in XML File..
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="#+id/autoCompt"
android:orientation="vertical">
<AutoCompleteTextView
android:id="#+id/instname_field"
android:layout_width="match_parent"
android:hint="Type Institution Name"
android:paddingLeft="10dp"
android:textColor="#fff"
android:background="#b8d1e5"
android:layout_height="40dp"
android:textSize="20dp"
android:ems="10"/>
</LinearLayout>
How can I solve this Issue. Thanks.
You can see #blackBelt comment that is the right way to do that.
But here i am explain you another method which is easy to understand using Hashmap instead of Object class .
HashMap<String, String> map_name_value = new HashMap<String, Stirng>();
for (int i = 0; i <detailsArray.length() ; i++) {
JSONObject obj = detailsArray.getJSONObject(i)
listInstituteNames.add(obj.getString("InstituteName"))
map_name_value.put(obj.getString("InstituteName"),obj.getString("InstituteID"));
}
Then while clicking the item.
Do this:
autoTextView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View arg1, int pos,
long id) {
Editable message = autoTextView.getText();
String item_name = message.toString();
String item_id = map_name_value.get(item_name);
//your stuff
}
});
//item_name is name of institute
// item_id is id of institute
Related
I keep getting a null pointer exception when ever I try to run a fragment that must use an expandable list view item. I'm guessing it has something to do with the fragment because the similar code runs on an activity.
Here is the error (Logcat) message:
11-02 14:11:27.136 12947-12947/com.example.vhuhwavho.ctistudentportal E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.vhuhwavho.ctistudentportal, PID: 12947
java.lang.NullPointerException
at com.example.vhuhwavho.ctistudentportal.ForYouFragment.onCreateView(ForYouFragment.java:117)
at android.app.Fragment.performCreateView(Fragment.java:1700)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:684)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1453)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5487)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Here is the fragment code:
package com.example.vhuhwavho.ctistudentportal;
import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import static android.content.Context.MODE_PRIVATE;
/**
* Created by Vhuhwavho on 2017/10/31.
*/
public class ForYouFragment extends Fragment {
// To keep track of the counter, we need to add a global variable to the project,
// along with a key for saving and restoring.
static final String KEY_STUDENT_NUMBER = "studentNumber";
String studentNumber = "";
private static final int CODE_GET_REQUEST = 1024;
private static final int CODE_POST_REQUEST = 1025;
private Button mSubmit;
private Context mContext;
private LayoutInflater mInflater;
private View view;
private List < String > listHeadings;
private List < String > image_urls;
private List < Bitmap > images;
private List < String > messages;
private LinkedHashMap < String, GroupInfo > gMessages = new LinkedHashMap < String, GroupInfo > ();
private ArrayList < GroupInfo > list = new ArrayList < GroupInfo > ();
private ExpandableListAdapter listAdapter;
private ExpandableListView simpleExpandableListView;
//Connectivity manage instance
private ConnectivityManager mConnMgr;
// Image view reference
private ImageView imageView;
int imageCounter = 0, imageCounterSize = 0;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.for_you_fragment, container, false);
String extraStr;
try {
extraStr = getArguments().getString("studentNumber");
Log.e("try studentNumber", "tried student number");
} catch (NullPointerException e) {
studentNumber = "PT2014-1282";
Log.e("catch studentNumber", "catched student number");
}
requestForYou();
//get reference of the ExpandableListView
simpleExpandableListView = (ExpandableListView) this.getActivity().findViewById(R.id.simpleExpandableListView);
if ( simpleExpandableListView == null )
Log.d("Null or Not", "simpleExpandableList == null");
// create the adapter by passing your ArrayList data
listAdapter = new ExpandableListAdapter (this.getActivity().getApplicationContext(), list);
// attach the adapter to the expandable list view
simpleExpandableListView.setAdapter(listAdapter);
//expand all the Groups
expandAll();
// setOnChildClickListener listener for child row click
simpleExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
//get the group header
GroupInfo headerInfo = list.get(groupPosition);
//get the child info
ChildInfo detailInfo = headerInfo.getHeadingList().get(childPosition);
//display it or do something with it
Toast.makeText(getActivity(), " Clicked on :: " + headerInfo.getHeading()
+ "/" , Toast.LENGTH_LONG).show();
return false;
}
});
// setOnGroupClickListener listener for group heading click
simpleExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
//get the group header
GroupInfo headerInfo = list.get(groupPosition);
//display it or do something with it
return false;
}
});
listHeadings = new ArrayList<>();
messages = new ArrayList<>();
image_urls = new ArrayList<>();
return view;
} // end of onCreateView method
// To receive notifications of application state change, 2 methods are needed
// the onSaveInstanceState() and onRestoreInstanceState() methods
#Override
public void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_STUDENT_NUMBER, studentNumber);
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated (savedInstanceState);
if (savedInstanceState != null) {
studentNumber = savedInstanceState.getString(KEY_STUDENT_NUMBER);
}
}
// save the data before the activity closes
#Override
public void onPause () {
super.onPause();
SharedPreferences settings = this.getActivity().getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(KEY_STUDENT_NUMBER, studentNumber);
editor.commit();
}
//method to expand all groups
private void expandAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
simpleExpandableListView.expandGroup(i);
}
}
//method to collapse all groups
private void collapseAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
simpleExpandableListView.collapseGroup(i);
}
}
private void requestForYou () {
PerformNetworkRequest request = new PerformNetworkRequest(API.URL_REQUEST_FOR_YOU, CODE_GET_REQUEST);
request.execute();
}
private void refreshForYou( JSONArray forYou) throws JSONException {
for ( int i = 0; i < forYou.length(); i++ ) {
JSONObject whats_happening = forYou.getJSONObject(i);
String heading = whats_happening.getString( "heading" );
String image_url = whats_happening.getString( "url" );
String message = whats_happening.getString( "message" );
listHeadings.add ( heading ) ;
messages.add ( message );
image_urls.add ( image_url );
Log.d("ForYouFragment", "refreshForYou");
}
imageCounterSize = listHeadings.size();
if ( mConnMgr != null ) {
// Get active network info
NetworkInfo networkInfo = mConnMgr.getActiveNetworkInfo();
// If any active network is available and internet connection is available
if ( networkInfo != null && networkInfo.isConnected() ) {
for ( String url : image_urls ) {
// Start a new Image Download Async Task
new DownloadImageTask().execute( url );
}
} else {
// If network is off or internet is not available, inform the user
Toast.makeText(this.getActivity(), "Network not Available", Toast.LENGTH_SHORT).show();
}
}
Log.d("ForYouFragment", "Finished refreshForYou");
for ( int loadData = 0; loadData < imageCounterSize; loadData++ ) {
addMessage ( listHeadings.get( loadData ) , messages.get( loadData ) , images.get( loadData ));
}
}
//here we maintain our products in various departments
private int addMessage ( String heading, String message, Bitmap image ){
int groupPosition = 0;
//check the hash map if the group already exists
GroupInfo headerInfo = gMessages.get(heading);
//add the group if doesn't exists
if( headerInfo == null ) {
headerInfo = new GroupInfo();
headerInfo.setHeading(heading);
gMessages.put(heading, headerInfo);
list.add(headerInfo);
}
//get the children for the group
ArrayList<ChildInfo> productList = headerInfo.getHeadingList();
//size of the children list
int listSize = productList.size();
//add to the counter
listSize++;
//create a new child and add that to the group
ChildInfo detailInfo = new ChildInfo();
detailInfo.setSequence ( String.valueOf( listSize ) );
detailInfo.setMessage ( message );
productList.add ( detailInfo );
headerInfo.setHeadingList ( productList );
//find the group position inside the list
groupPosition = list.indexOf(headerInfo);
return groupPosition;
}
public class PerformNetworkRequest extends AsyncTask<Void, Void, String> {
String url;
HashMap < String, String > params; // Store the names of the subjects enrolled
int requestCode;
PerformNetworkRequest ( String URL, int code ) {
url = URL;
requestCode = code;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute( String s ) {
Log.d("fetchWhatsHappening", "onPostExecute Register Response: " + s.toString());
super.onPostExecute( s );
try {
JSONObject root_object = new JSONObject( s );
JSONArray array = root_object.getJSONArray("for_you");
Log.d("GET URL", "Checking URL... " + API.URL_REQUEST_FOR_YOU );
if (!root_object.getBoolean("error")) {
Toast.makeText( getActivity(), root_object.getString("message"), Toast.LENGTH_SHORT ).show();
refreshForYou ( array );
} else {
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
#Override
protected String doInBackground(Void... voids) {
RequestHandler requestHandler = new RequestHandler();
if (requestCode == CODE_POST_REQUEST)
return requestHandler.sendPostRequest(url, params);
if (requestCode == CODE_GET_REQUEST)
return requestHandler.sendGetRequest(url);
return null;
} // end of doInBackground method
} // end of PerformNetworkRequest class
/*--------------------------- Setting ListView and Downloading Images ------------------------*/
public class GroupInfo {
private String heading;
private Bitmap image;
private ArrayList < ChildInfo > list = new ArrayList < ChildInfo >();
public String getHeading() {
return heading;
}
public void setHeading ( String heading ) {
this.heading = heading;
}
public void setImage (Bitmap image) {
this.image = image;
}
public Bitmap getImage () {
return image;
}
public ArrayList < ChildInfo > getHeadingList() {
return list;
}
public void setHeadingList(ArrayList<ChildInfo> headingList) {
this.list = headingList;
}
}
public class ChildInfo {
private String sequence = "";
private String message = "";
public String getSequence() {
return sequence;
}
public void setSequence(String sequence) {
this.sequence = sequence;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
LayoutInflater inflater;
private ArrayList<GroupInfo> forYou;
public ExpandableListAdapter (Context applicationContext, ArrayList<GroupInfo> forYou ) {
this.context = context;
this.forYou = forYou;
inflater = ( LayoutInflater.from( applicationContext ) );
}
#Override
public Object getChild( int groupPosition, int childPosition ) {
ArrayList < ChildInfo > headingList = forYou.get(groupPosition).getHeadingList();
return headingList.get(childPosition);
}
#Override
public long getChildId( int groupPosition, int childPosition ) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View view, ViewGroup parent) {
view = inflater.inflate(R.layout.for_you_list_item, null);
ChildInfo detailInfo = (ChildInfo) getChild( groupPosition, childPosition );
TextView childItem = (TextView) view.findViewById( R.id.forYouMessage );
childItem.setText( detailInfo.getMessage().trim() );
return view;
}
#Override
public int getChildrenCount ( int groupPosition ) {
ArrayList < ChildInfo > headingList = forYou.get( groupPosition ).getHeadingList();
return headingList.size();
}
#Override
public Object getGroup(int groupPosition) {
return forYou.get(groupPosition);
}
#Override
public int getGroupCount() {
return forYou.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isLastChild, View view,
ViewGroup parent) {
view = inflater.inflate(R.layout.for_you_heading_list_view, null);
GroupInfo headerInfo = (GroupInfo) getGroup(groupPosition);
TextView heading = (TextView) view.findViewById(R.id.forYouHeading);
ImageView image = (ImageView) view.findViewById(R.id.forYouIcon);
heading.setText(headerInfo.getHeading().trim());
image.setImageBitmap(headerInfo.getImage());
return view;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
} // end of ExpandableListAdapter
private class DownloadImageTask extends AsyncTask < String, Void, Bitmap > {
#Override
protected Bitmap doInBackground(String... urls) {
return downloadImage ( urls[0] );
}
#Override
protected void onPostExecute (Bitmap bitmap) {
if ( imageCounter < imageCounterSize ) {
if (bitmap == null) {
Drawable vectorDrawable = ResourcesCompat.getDrawable(getActivity().getResources(), R.drawable.no_image, null);
Bitmap no_image = ((BitmapDrawable) vectorDrawable).getBitmap();
images.add(no_image);
}
else if (bitmap != null) { // Add the newly downloaded image to the list
images.add( bitmap );
}
imageCounter++;
}
} // end of onPostExecute
}
public Bitmap downloadImage (String path) {
final String TAG = "Download Task";
Bitmap bitmap = null;
InputStream inStream;
try {
// Create a URL Connection object and set its parameters
URL url = new URL(path);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// Set connection time out of 5 seconds
urlConn.setConnectTimeout(5000);
// Set connection time out of 2.5 seconds
urlConn.setReadTimeout(2500);
// Set HTTP request method
urlConn.setRequestMethod("GET");
urlConn.setDoInput(true);
// Perform network request
inStream = urlConn.getInputStream();
// Convert the input stream to Bitmap object
bitmap = BitmapFactory.decodeStream(inStream);
} catch (MalformedURLException e) {
Log.e(TAG, "URL error : " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "Download Failed : " + e.getMessage());}
return bitmap;
}
}
Here's the for_you_fragment.xml file with the ExpandableListView:
<?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">
<ExpandableListView
android:id="#+id/simpleExpandableListView"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:divider="#f00"
android:childDivider="#0f0"
android:dividerHeight="1dp" />
</RelativeLayout>
Here's the list_item.xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/forYouMessage"
android:textSize="16dip"
android:paddingLeft="10dp"
android:paddingStart="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Here is the list_view.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">
<ImageView
android:id="#+id/forYouIcon"
android:layout_width="fill_parent"
android:layout_height="200dp" />
<TextView
android:id="#+id/forYouHeading"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/forYouIcon"
android:text="..."
android:textStyle="bold" />
</RelativeLayout>
You are passing wrong context here:
//get reference of the ExpandableListView
simpleExpandableListView = (ExpandableListView) this.getActivity().findViewById(R.id.simpleExpandableListView);
You have to pass the view which you are inflating as follow:
simpleExpandableListView = (ExpandableListView) view.findViewById(R.id.simpleExpandableListView);
I was reviewing code on Android but don't understand what is happenning when notifyDataSetChanged() is called on an object of a class extending BaseAdapter.
In the code, channelListAdapter.notifyDataSetChanged() was called.
Here is the code of the ChannelListAdapter class:
public class ChannelListAdapter extends BaseAdapter {
Field[] fields;
Context context;
List<Channels> channelList = null;
String dateString, likeData, ab, imageData;
Channels item;
DBVideos dbVideos;
VideoListAdapter videoListAdapter;
MostRecentFragment parentFragment;
public boolean loadingMoreChannels;
public boolean noMoreChannelFound;
Map<String, Boolean> map = new HashMap<String, Boolean>();
Map<String, Integer> totalLikeCount = new HashMap<String, Integer>();
public Map<String, Boolean> timerMap = new HashMap<String, Boolean>();
Map<String, List<Videos>> mapVideos = new HashMap<String, List<Videos>>();
public ChannelListAdapter(Context context) {
this.context = context;
}
public Map<String, List<Videos>> getMapVideos() {
return mapVideos;
}
public void setMapVideos(Map<String, List<Videos>> mapVideos) {
this.mapVideos = mapVideos;
}
public ChannelListAdapter(Context context, List<Channels> channelList) {
this.context = context;
// listener = new NewsFeedListener(context, map, totalLikeCount);
// listener.setListAdapter(this);
this.channelList = channelList;
}
public ChannelListAdapter(Context context, List<Channels> channelList, MostRecentFragment parentFragment) {
this.context = context;
this.parentFragment = parentFragment;
this.channelList = channelList;
}
public String getLastFeedModificationTime() {
Channels lastNews = channelList.get(channelList.size() - 1);
return lastNews.getLastModifyDate();
}
public void setNewsList(List<Channels> channelList) {
this.channelList = channelList;
}
#Override
public int getCount() {
return channelList.size();
}
#Override
public Object getItem(int position) {
return channelList.get(position);
}
#Override
public long getItemId(int position) {
return channelList.indexOf(getItem(position));
}
public static class ViewHolder {
public TextView channelTitle;
public ImageView imgProcess;
ListView videoListView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = (View) mInflater.inflate(R.layout.channel_list_item, null);
holder.channelTitle = (TextView) convertView.findViewById(R.id.tv_channel_name);
holder.imgProcess = (ImageView) convertView.findViewById(R.id.img_process);
holder.videoListView = (ListView) convertView.findViewById(R.id.list_videos);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
item = (Channels) getItem(position);
final ViewHolder finalHolder = holder;
holder.channelTitle.setText(item.getTitle());
if (mapVideos.size() > 0 && mapVideos.containsKey(item.getId())) {
} else {
Glide.with(context).load("http://4.bp.blogspot.com/-rSoHhekcu9A/T6PQ6d8mKSI/AAAAAAAAASg/hStx9Mg18fc/s1600/22.gif").asGif().placeholder(R.drawable.img_loading).crossFade()
.into(holder.imgProcess);
String url = null;
url = context.getString(R.string.url_6e_channel_context)+CommonUtils.getEncodedUrl(context, context.getString(R.string.url_to_retive_all_video_selected_channel_first)+item.getId())+"+ContentType:Indigo+Video'&rowlimit=3&"+CommonUtils.getEncodedUrl(context,context.getString(R.string.url_to_retive_all_video_selected_channel_sec));
System.out.println("url ="+url);
ServiceCallAsync sca = new ServiceCallAsync(context, null,"Get", null, url, new AsyncResponse() {
#Override
public void processFinish(Object output) {
ServiceResponse serviceResponse = (ServiceResponse) output;
if(serviceResponse.getCode()==200){
parseDataAndStoreinDb(serviceResponse.getData(),finalHolder);
}else{
}
}
});
sca.execute();
}
if (position == channelList.size() - 1) {
if (parentFragment != null && !loadingMoreChannels && !noMoreChannelFound) {
loadingMoreChannels = true;
parentFragment.loadMore();
}
}
return convertView;
}
protected void parseDataAndStoreinDb(String data, ViewHolder finalHolder) {
List<Videos> videosList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(data);
JSONObject dObj = mainObj.getJSONObject("d");
JSONObject queryObj = dObj.getJSONObject("query");
JSONObject primaryQueryObj = queryObj.getJSONObject("PrimaryQueryResult");
JSONObject releventObj = primaryQueryObj.getJSONObject("RelevantResults");
JSONObject tableObj = releventObj.getJSONObject("Table");
JSONObject rowsObj = tableObj.getJSONObject("Rows");
JSONArray resultArray = rowsObj.getJSONArray("results");
for(int i = 0; i<resultArray.length();i++){
Map<String ,String> videoFieldsMap=new HashMap<String, String>();
JSONObject resultObj= resultArray.getJSONObject(i);
JSONObject cellesObj= resultObj.getJSONObject("Cells");
JSONArray resultInnerArray = cellesObj.getJSONArray("results");
for(int j = 0; j<resultInnerArray.length();j++){
JSONObject obj= resultInnerArray.getJSONObject(j);
//System.out.println("obj ="+obj.getString("Key"));
videoFieldsMap.put(obj.getString("Key"), obj.getString("Value"));
}
videoFieldsMap.put("ListId", item.getId());
Videos video = convertMapToVideoModel(videoFieldsMap);
System.out.println("video convertedMap ="+video);
videosList.add(video);
}
if(dbVideos == null ){
dbVideos = new DBVideos(context);
}
dbVideos.insertVideos(videosList);
// mapVideos.put(item.getId(), videosList);
setVideoListAdapter(videosList,finalHolder);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void setVideoListAdapter(List<Videos> list, ViewHolder finalHolder) {
if(videoListAdapter == null){
videoListAdapter = new VideoListAdapter(context, list,parentFragment);
}
videoListAdapter.setVideoList(list);
System.out.println("list ="+list.size());
System.out.println("list ="+list.get(1));
finalHolder.videoListView.setAdapter(videoListAdapter);
finalHolder.videoListView.setVisibility(View.VISIBLE);
finalHolder.imgProcess.setVisibility(View.GONE);
ListHeightUtils.setListViewHeightBasedOnChildren(finalHolder.videoListView);
}
private Videos convertMapToVideoModel(Map<String, String> videoFieldsMap){
Class clazz=Videos.class;
Object object = null;
System.out.println("videoFieldsMap ="+videoFieldsMap);
try{
object=clazz.newInstance();
for(Field field:clazz.getDeclaredFields()){
field.setAccessible(true);
System.out.println("field =="+videoFieldsMap.get(field));
field.set(object, videoFieldsMap.get(field.getName()));
}
System.out.println("object ="+object.toString());
}catch(Exception e){
e.printStackTrace();
}
return (Videos)object;
}
}
The Adapter defines the rules to display a list of items in a View - it is usually in the context of a ListView or RecyclerView (but really can be a multitude of things). The view is not aware of when the underlying dataset changes, so after its initial draw, it needs to be told when its data is no longer the most up-to-date.
Say you have the following list:
[A, B, C]
At some point, the user hits an API and the list is updated:
[A, B, C, D, E, F]
The ListView where this list is displayed will still only show:
[A, B, C]
When you call notifyDataSetChanged() on the adapter that is attached to the ListView, it will then update the ListView to show the full new dataset:
[A, B, C, D, E, F]
It is possible too, depending on what kind of adapter you're using, to notify that the entire dataset has changed, or to do more specific update calls like RecyclerView's notifyItemChanged, notifyItemRemoved, notifyItemMoved etc.
From the docs notifyDataSetChanged() :
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
There might be requirement in your application where you want to update the ListView when ever the data set binded to that listview has undergone change like add , update or delete .
To achieve this Android provides a way to call notifyDataSetChanged() for an ArrayAdapter or a BaseAdapter which will update the listview .
See an example here.
1.My search functionality works fine using edittext,but for example if I type "1" than delete it the listview shows null,how can I make listview shows JSON again after I type something then delete it?
2.If I change to search COUNTRY rather than RANK ,I need to type full character like "INDIA" how can I just type "in" then it can appear INDIA?
thanks
MainActivity.java
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String URL="url";
static String FLAG = "flag";
EditText mEditText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
mEditText = (EditText) findViewById(R.id.inputSearch);
mEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
ArrayList<HashMap<String, String>> arrayTemplist = new ArrayList<HashMap<String, String>>();
String searchString = mEditText.getText().toString();
for (int i = 0; i < arraylist.size(); i++) {
String currentString = arraylist.get(i).get(MainActivity.RANK);
if (searchString.equalsIgnoreCase(currentString)) {
arrayTemplist.add(arraylist.get(i));
}
}
adapter = new ListViewAdapter(MainActivity.this, arrayTemplist);
listview.setAdapter(adapter);
}
});
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// 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>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://ndublog.twomini.com/123.txt.txt");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("worldpopulation");
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("rank", jsonobject.getString("rank"));
map.put("country", jsonobject.getString("country"));
map.put("population", jsonobject.getString("population"));
map.put("url",jsonobject.getString("url"));
map.put("flag", jsonobject.getString("flag"));
// 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) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
ListViewAdapter.java
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
public class ListViewAdapter extends BaseAdapter {
Context context;
LayoutInflater inflater;
public ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#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 rank;
TextView country;
TextView population;
TextView url;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
population = (TextView) itemView.findViewById(R.id.population);
url=(TextView)itemView.findViewById(R.id.url);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
rank.setText(resultp.get(MainActivity.RANK));
country.setText(resultp.get(MainActivity.COUNTRY));
population.setText(resultp.get(MainActivity.POPULATION));
url.setText(resultp.get(MainActivity.URL));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("rank", resultp.get(MainActivity.RANK));
// Pass all data country
intent.putExtra("country", resultp.get(MainActivity.COUNTRY));
// Pass all data population
intent.putExtra("population",resultp.get(MainActivity.POPULATION));
intent.putExtra("url",resultp.get(MainActivity.URL));
// Pass all data flag
intent.putExtra("flag", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
Edit this code below,thanks
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ListActivity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String URL="url";
static String FLAG = "flag";
EditText mEditText;
String globalQuery="";
ArrayList<HashMap<String, String>> globalList = new ArrayList<HashMap<String, String>>();
ListViewAdapter globalListAdapter,globalAdapter=null;
public void filteredList()
{
//First of all checks for our globalList is not a null one.
if(globalList!=null)
{
ArrayList<HashMap<String, String>> tempList = new ArrayList<HashMap<String, String>>();
//Checks our search term is empty or not.
ListViewAdapter globalAdapter = null;
if(!globalQuery.trim().equals(""))
{
boolean isThereAnyThing=false;
for(int i=0;i<globalList.size();i++)
{
//Get the value of globalList that is HashMap indexed at i.
HashMap<String, String> tempMap=globalList.get(i);
//Now getting all your HashMap values into local variables.
String rank=tempMap.get(MainActivity.RANK);
String country=tempMap.get(MainActivity.COUNTRY);
String population=tempMap.get(MainActivity.POPULATION);
String url=tempMap.get(MainActivity.URL);
String flag=tempMap.get(MainActivity.FLAG);
//Now all the core checking goes here for which one of these was typed like rank or country or population .....
if(rank.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || country.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || population.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || url.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || flag.regionMatches(true, 0, globalQuery,0, globalQuery.length()))
{
//If anything matches then it will add to tempList
tempList.add(tempMap);
isThereAnyThing=true;
}
}
//Checks for is there anything matched from the ArrayList with the user type search query
if(isThereAnyThing)
{
//then set the globalAdapter with the new HashMaps tempList
globalAdapter = new ListViewAdapter(MainActivity.this, tempList);
listview.setAdapter(globalAdapter);
setListAdapter(globalAdapter);
((ListViewAdapter)globalAdapter).notifyDataSetChanged();
}
else
{
//If else set list adapter to null
setListAdapter(null);
}
}
else
{
// Do something when there's no input
if(globalAdapter==null)
{
//If no user inputs then it will list everything in the globalList.
justListAll();
}
else
{
final ListViewAdapter finalGlobalAdapter = globalAdapter;
runOnUiThread(new Runnable()
{
public void run()
{
((ListViewAdapter) finalGlobalAdapter).notifyDataSetChanged();
}
});
}
}
// updating listview
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
mEditText = (EditText) findViewById(R.id.inputSearch);
mEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (s.toString().length() > 0) {
// Search
globalQuery=s.toString();
//This method will filter all your categories just calling this method.
filteredList();
} else {
globalQuery="";
//If the text is empty the list all the content of the list adapter
justListAll();
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
ArrayList<HashMap<String, String>> arrayTemplist = new ArrayList<HashMap<String, String>>();
String searchString = mEditText.getText().toString();
if(searchString.equals("")){new DownloadJSON().execute();}
else{
for (int i = 0; i < arraylist.size(); i++) {
String currentString = arraylist.get(i).get(MainActivity.COUNTRY);
if (searchString.contains(currentString)) {
//pass the character-sequence instead of currentstring
arrayTemplist.add(arraylist.get(i));
}
}
}
adapter = new ListViewAdapter(MainActivity.this, arrayTemplist);
listview.setAdapter(adapter);
}
});
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// 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>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://ndublog.twomini.com/123.txt.txt");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("worldpopulation");
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("rank", jsonobject.getString("rank"));
map.put("country", jsonobject.getString("country"));
map.put("population", jsonobject.getString("population"));
map.put("url",jsonobject.getString("url"));
map.put("flag", jsonobject.getString("flag"));
// 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) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
public void justListAll()
{
ListViewAdapter globalAdapter = new ListViewAdapter(MainActivity.this, globalList);
listview.setAdapter(adapter);
setListAdapter(globalAdapter);
((ListViewAdapter)globalAdapter).notifyDataSetChanged();
}
}
Thank you for asking the question in a good way as per the SO guidelines.
Iam sure this will solve your question.
//First of all declare a global variables
String globalQuery="";
ArrayList<HashMap<String, String>> globalList = new ArrayList<HashMap<String, String>>();
ListViewAdapter globalListAdapter;
public void afterTextChanged(Editable s) {
if (s.toString().length() > 0) {
// Search
globalQuery=s.toString();
//This method will filter all your categories just calling this method.
filteredList();
} else {
globalQuery="";
//If the text is empty the list all the content of the list adapter
justListAll();
}
}
public void justListAll()
{
globalAdapter = new ListViewAdapter(MainActivity.this, globalList);
listview.setAdapter(adapter);
setListAdapter(globalAdapter);
((ListViewAdapter)globalAdapter).notifyDataSetChanged();
}
public void filteredList()
{
//First of all checks for our globalList is not a null one.
if(globalList!=null)
{
ArrayList<HashMap<String, String>> tempList = new ArrayList<HashMap<String, String>>();
//Checks our search term is empty or not.
if(!globalQuery.trim().equals(""))
{
boolean isThereAnyThing=false;
for(int i=0;i<globalList.size();i++)
{
//Get the value of globalList that is HashMap indexed at i.
HashMap<String, String> tempMap=globalList.get(i);
//Now getting all your HashMap values into local variables.
String rank=tempMap.get(MainActivity.RANK);
String country=tempMap.get(MainActivity.COUNTRY);
String population=tempMap.get(MainActivity.POPULATION);
String url=tempMap.get(MainActivity.URL);
String flag=tempMap.get(MainActivity.FLAG);
//Now all the core checking goes here for which one of these was typed like rank or country or population .....
if(rank.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || country.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || population.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || url.regionMatches(true, 0, globalQuery,0, globalQuery.length()) || flag.regionMatches(true, 0, globalQuery,0, globalQuery.length()))
{
//If anything matches then it will add to tempList
tempList.add(tempMap);
isThereAnyThing=true;
}
}
//Checks for is there anything matched from the ArrayList with the user type search query
if(isThereAnyThing)
{
//then set the globalAdapter with the new HashMaps tempList
globalAdapter = new ListViewAdapter(MainActivity.this, tempList);
listview.setAdapter(globalAdapter);
setListAdapter(globalAdapter);
((ListViewAdapter)globalAdapter).notifyDataSetChanged();
}
else
{
//If else set list adapter to null
setListAdapter(null);
}
}
else
{
// Do something when there's no input
if(globalAdapter==null)
{
//If no user inputs then it will list everything in the globalList.
justListAll();
}
else
{
runOnUiThread(new Runnable()
{
public void run()
{
((ListViewAdapter)globalAdapter).notifyDataSetChanged();
}
});
}
}
// updating listview
}
}
Only a thing you want to do is populate all the JSON parsed values to the global ArrayList globalList.
Hope it answers the whole question with extra packups.
When you delete the character, the text in the EditText view is null therefore it is looking for null and the list displays null. Make sure you perform a null check before searching through your JSON array.
It looks like you just need to change this line:
String currentString = arraylist.get(i).get(MainActivity.RANK);
to
String currentString = arraylist.get(i).get(MainActivity.COUNTRY);
do the following change to your edittext watcher... if the edittext.gettext().tostring().equals("") ...then just execute the asynctask
public void onTextChanged(CharSequence s, int start, int before, int count) {
ArrayList<HashMap<String, String>> arrayTemplist = new ArrayList<HashMap<String, String>>();
String searchString = mEditText.getText().toString();
if(searchString.equals(""))
{
new DownloadJSON().execute();
//this will set you the whole json again to your listview
}
else
{
for (int i = 0; i < arraylist.size(); i++) {
String currentString = arraylist.get(i).get(MainActivity.RANK);
if (searchString.equalsIgnoreCase(currentString)) {
arrayTemplist.add(arraylist.get(i));
}
}
adapter = new ListViewAdapter(MainActivity.this, arrayTemplist);
listview.setAdapter(adapter);
}
}
and in case of COUNTRY..why its behaving diff...it think you have to match the edittext substring with the arraylist
just replace the following code
if (searchString.equalsIgnoreCase(currentString)) {
arrayTemplist.add(arraylist.get(i));
}
with
if (searchString.contains(currentString)) {
//pass the character-sequence instead of currentstring
arrayTemplist.add(arraylist.get(i));
}
for COUNTRY search...
public void onTextChanged(CharSequence s, int start, int before, int count) {
ArrayList<HashMap<String, String>> arrayTemplist = new ArrayList<HashMap<String, String>>();
String searchString = mEditText.getText().toString();
if(searchString.equals(""))
{
new DownloadJSON().execute();
//this will set you the whole json again to your listview
}
else
{
for (int i = 0; i < arraylist.size(); i++) {
String currentString = arraylist.get(i).get(MainActivity.COUNTRY);
if ( searchString .equalsIgnoreCase(currentString .substring(0,searchString .length()-1))) {
arrayTemplist.add(arraylist.get(i));
}
}
adapter = new ListViewAdapter(MainActivity.this, arrayTemplist);
listview.setAdapter(adapter);
}
}
I am using Geocoder to fetch matching addresses from a String.
I am trying to display the returned addresses to an AutoCompleteTextView.
I can see the values properly when I Log.i("Result:"," "+list_of_addresses);
Since we are talking about dynamic list loading I am calling adapter.NotifyDataSetChanged();
I am using addTextChangedListener to listen to the changes in the text input by the user
This is what the code looks like
public class Map extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
final Geocoder gc = new Geocoder(getApplicationContext(), Locale.getDefault());
final ArrayList<String> address_name = new ArrayList<String>();
final AutoCompleteTextView search = (AutoCompleteTextView) findViewById(R.id.search);
search.setThreshold(1);
final ArrayAdapter<String> adapter =new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line,address_name);
search.setAdapter(adapter); //moved this line out of the try block
search.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
List<Address> list = null;
Address address = null;
try {
list = gc.getFromLocationName(s.toString(), 10);
Log.i("List:", ""+list); //CAN see this log
} catch (IOException e) {
e.printStackTrace();
}
for(int i=0; i<list.size(); i++){
address = list.get(i);
address_name.add(address.getFeatureName().toString());
Log.i("Address: ", address.getFeatureName().toString()); //CANto see this Log
}
if(!list.isEmpty()){
list.clear();
}
adapter.notifyDataSetChanged();
search.showDropDown();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
}
}
Inside the for loop I am unable to see the log.i("Addresses:",address.getFeatureName.toString());
But when i change the for loop condition to i<=list.size() I do get the Log output but the application forcecloses with this error java.lang.IndexOutOfBoundsException: Invalid index 10, size is 10
Maybe that's why I am unable to see the Address list?
EDIT: I changed the for loop condition to i<list.size() also added search.showDropDown() after notifying dataset changed.
Any help would be appreciated! Thankyou.
You seem to have a problem with getting it to work. I'll paste what works for me really well, only relevant sections for AutoComplete.
onCreate
pickUpAutoComplete = new AutoComplete(this, R.layout.pickupautocomplete);
pickUpAutoComplete.setNotifyOnChange(true);
locationText = (AutoCompleteTextView) findViewById(R.id.locationText);
locationText.setOnItemClickListener(this);
locationText.setOnFocusChangeListener(this);
locationText.setAdapter(pickUpAutoComplete);
layout xml
<AutoCompleteTextView
android:id="#+id/locationText"
style="#style/registerLargestTextSize"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:layout_margin="10dp"
android:layout_weight="6"
android:background="#ffffff"
android:completionThreshold="3"
android:focusable="true"
android:gravity="center"
android:hint="home location"
android:lines="3"
android:maxLines="3"
android:minLines="3"
android:paddingBottom="3dp"
android:paddingLeft="6dp"
android:paddingRight="6dp"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbarStyle="outsideOverlay"
android:textColor="#b2b2b2"
android:textStyle="bold" />
AutoComplete Class, Don't forget to replace your API KEY
public class AutoComplete extends ArrayAdapter<String> implements Filterable {
private static final String LOG_TAG = "carEgiri";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
private static final String API_KEY = "**YOUR API KEY HERE**";
private ArrayList<String> resultList;
public AutoComplete(IPostAutoCompleteUIChange context,
int textViewResourceId) {
super((Context) context, textViewResourceId);
}
#Override
public int getCount() {
if (resultList == null)
return 0;
return resultList.size();
}
#Override
public String getItem(int index) {
return resultList.get(index);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
The problem is related to a wrong or empty override of adapter methods:
#Override
public UPorPackageItem getItem(int index) {
return mValues.get(index);
}
#Override
public int getCount() {
if (mValues == null)
return 0;
return mValues.size();
}
you must implement the above method.
It will works
i am use this for setting checkbox in listview i have follow all step as per given tutorial, but there are some critical issue with output, is that when i am select first checkbox and scroll down it will change selected item and automatically appear 3rd.
so i think there are something wrong with getview. so please help me out this ....
here is my code ::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
public class Favorites extends ListActivity {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
ArrayList alAppName;
float[] rate;
boolean[] bSelected;
ArrayList<Comment> alPackagenm;
Drawable[] alIcon;
ViewHolder holder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
for (int i = 0; i < strAr.length; i++) {
System.out.println("strAr[" + i + "] " + strAr[i]);
}
for (String s : strAr) {
list.add(new RowModel(s));
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> {
private ArrayList<Model> mlist;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar,
float rating, boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(
CompoundButton buttonView, boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
}
});
holder.chkbxFavrowsel.setTag(mlist.get(position));
holder.ratingBar1.setOnRatingBarChangeListener(l);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
return (row);
}
}
}
I really don't understand your code exactly what you are trying to do. I haven't seen before this you are checking holder == null where as it should be convertView == null. If you have a scrolling issue you can check my blog post
holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
...
}
else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
Use Below Code to your MainActivity.java file.
public class ListViewActivity extends Activity {
ListView mLstView1;
Button mBtn1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLstView1 = (ListView) findViewById(R.id.mLstView1);
String[] lv_items = { "Dipak", "Rahul", "Hiren", "Nandlal", "Keyur",
"Kapil", "Dipak", "Rahul", "Hiren", "Nandlal", "Keyur",
"Kapil" };
;
mLstView1.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, lv_items));
mLstView1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mBtn1 = (Button) findViewById(R.id.mBtn1);
mBtn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Using a List to hold the IDs, but could use an array.
List<Integer> checkedIDs = new ArrayList<Integer>();
// Get all of the items that have been clicked - either on or
// off
final SparseBooleanArray checkedItems = mLstView1
.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++) {
// And this tells us the item status at the above position
final boolean isChecked = checkedItems.valueAt(i);
if (isChecked) {
// This tells us the item position we are looking at
final int position = checkedItems.keyAt(i);
// Put the value of the id in our list
checkedIDs.add(position);
System.out.println("Position is:- " + position);
}
}
}
});
}
}