No searching results after onTextChanged in android Listview [duplicate] - android

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I can't resolve this problem. I want to add search functionality by EditText. Results should dynamically display after typing letters but now there is no results.
Thanks for Your quick response :)
ParkingActivity.java
public class ParkingActivity extends FragmentActivity {
private final String URL_TO_HIT = "http://www-users.mat.umk.pl/~discordia/dane.json";
private ListView lvParking;
private EditText inputSearch;
public ParkingAdapter adapter;
public ArrayList<ParkingModel> parkingModelList = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_activity);
lvParking = (ListView) findViewById(R.id.lvParking);
inputSearch = (EditText) findViewById(R.id.editText);
new JSONTask().execute(URL_TO_HIT);
}
public class JSONTask extends AsyncTask<String,String, List<ParkingModel> > {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<ParkingModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("parkingInfo");
ArrayList<ParkingModel> parkingModelList = new ArrayList<>();
Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
/**
* below single line of code from Gson saves you from writing the json parsing yourself which is commented below
*/
ParkingModel parkingModel = gson.fromJson(finalObject.toString(), ParkingModel.class);
parkingModelList.add(parkingModel);
}
return parkingModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(final List<ParkingModel> result) {
super.onPostExecute(result);
if(result != null) {
adapter = new ParkingAdapter(getApplicationContext(), R.layout.row, result);
lvParking.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
ParkingActivity.this.adapter.getFilter().filter(cs);
}
#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
}
});
lvParking.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ParkingModel parkingModel = result.get(position);
Intent intent = new Intent(ParkingActivity.this, DetailActivity.class);
intent.putExtra("parkingModel", new Gson().toJson(parkingModel));
startActivity(intent);
}
});
}
}
}
public class ParkingAdapter extends ArrayAdapter {
private List<ParkingModel> parkingModelList;
private int resource;
private LayoutInflater inflater;
public ParkingAdapter(Context context, int resource, List<ParkingModel> objects) {
super(context, resource, objects);
parkingModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView = inflater.inflate(resource, null);
holder.tvLokalizacja = (TextView)convertView.findViewById(R.id.tvLokalizacja);
holder.tvIle_wolnych_zwyklych = (TextView)convertView.findViewById(R.id.tvIle_wolnych_zwyklych);
holder.tvIle_wszystkich_zwyklych = (TextView)convertView.findViewById(R.id.tvIle_wszystkich_zwyklych);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvLokalizacja.setText(parkingModelList.get(position).getLokalizacja());
holder.tvIle_wolnych_zwyklych.setText("Wolne: " + parkingModelList.get(position).getIle_wolnych_zwyklych());
holder.tvIle_wszystkich_zwyklych.setText("Wszystkie:" + parkingModelList.get(position).getIle_wszystkich_zwyklych());
return convertView;
}
class ViewHolder{
private TextView tvLokalizacja;
private TextView tvIle_wolnych_zwyklych;
private TextView tvIle_wszystkich_zwyklych;
}
}
#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_parking, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
This is my model which I use to create final array with data.
ParkingModel.java
public class ParkingModel {
private String lokalizacja;
private int ile_wolnych_zwyklych;
private int ile_wszystkich_zwyklych;
public String getLokalizacja() {
return lokalizacja;
}
public void setLokalizacja(String lokalizacja) {
this.lokalizacja = lokalizacja;
}
public int getIle_wolnych_zwyklych() {
return ile_wolnych_zwyklych;
}
public void setIle_wolnych_zwyklych(int ile_wolnych_zwyklych) {
this.ile_wolnych_zwyklych = ile_wolnych_zwyklych;
}
public int getIle_wszystkich_zwyklych() {
return ile_wszystkich_zwyklych;
}
public void setIle_wszystkich_zwyklych(int ile_wszystkich_zwyklych) {
this.ile_wszystkich_zwyklych = ile_wszystkich_zwyklych;
}
}
Here is my xml file.
list_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ParkingActivity">
<EditText
android:layout_width="319dp"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:inputType="text"
android:layout_gravity="center_horizontal" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lvParking" />
</LinearLayout>

Because in onPostExecute of JSONTask you have created new object of ParkingAdapter class and below that
ParkingActivity.this.adapter.getFilter().filter(cs); you are using this line.
this is always null;
To set adapter just use
adapter = new ParkingAdapter(getApplicationContext(), R.layout.row, result);
lvParking.setAdapter(adapter);

change this line
ParkingAdapter adapter = new ParkingAdapter(getApplicationContext(), R.layout.row, result);
To This
adapter = new ParkingAdapter(getApplicationContext(), R.layout.row, result);

Related

The textview is not stable in custom listview android

actually I Have a custom listview which contains a countdown timer and the countdown timer is created by a handler, now the list loads fine and everything seems to be correct but when I start to scroll the countdown timer becomes shaky and unstable the values seems to overlap each other means the lastrow values are printed in the first row and things like that, the values are up and down and it does not work properly, here the API sends a long value which is passed to handler and the handler converts that to a countdown timer, so where does the problem lies , whenever I refresh the list it becomes all fine, but as I start scrolling the same problem comes again.. here is my code
public class fixtures extends Fragment {
private ListView fixtureListView;
String Balance,userEmail;
SwipeRefreshLayout mSwipeRefreshLayout;
private static final String FORMAT = "%02d:%02d:%02d";
List<ListView_fixture_conveyer> fixture_conveyerList;
ListView_fixture_conveyer fixtureList;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fixtures, viewGroup, false);
fixtureListView = view.findViewById(R.id.fixture_list);
mSwipeRefreshLayout = view.findViewById(R.id.swipeToRefresh);
User user = SharedPrefManager.getInstance(getActivity()).getUser();
userEmail= user.getEmail();
new JSONTask().execute("http://www.judgement6.com/judgement_files/fixture_json.php");
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(Objects.requireNonNull(getActivity()))
.defaultDisplayImageOptions(options)
.build();
com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
fixture_conveyerList.clear();
new JSONTask().execute("http://www.judgement6.com/judgement_files/fixture_json.php");
mSwipeRefreshLayout.setRefreshing(false);
}
});
return view;
}
#SuppressLint("StaticFieldLeak")
public class JSONTask extends AsyncTask<String, String, List<ListView_fixture_conveyer>> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(getActivity(), "loading,please wait...", null, true, true);
}
#Override
protected List<ListView_fixture_conveyer> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder buffer = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("list");
fixture_conveyerList = new ArrayList<ListView_fixture_conveyer>();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
Log.e("fixtureObject",finalObject.toString());
fixtureList = new ListView_fixture_conveyer();
fixtureList.setTournament(finalObject.getString("tournament"));
fixtureList.setTeam1_photo(finalObject.getString("team1_photo"));
fixtureList.setTeam2_photo(finalObject.getString("team2_photo"));
fixtureList.setTeam1_name(finalObject.getString("team1_name"));
fixtureList.setTeam2_name(finalObject.getString("team2_name"));
fixtureList.setTime(finalObject.getString("Time"));
fixture_conveyerList.add(fixtureList);
}
return fixture_conveyerList;
} catch (IOException | JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<ListView_fixture_conveyer> result) {
super.onPostExecute(result);
if (result !=null) {
loading.dismiss();
ListAdapter adapter = new ListAdapter(getActivity(), R.layout.custom_list_fixture, result);
fixtureListView.setAdapter(adapter);
}
else
{
Toast.makeText(getActivity(), "No Internet Connection!", Toast.LENGTH_LONG).show();
loading.dismiss();
}
}
}
public class ListAdapter extends ArrayAdapter {
private List<ListView_fixture_conveyer> fixture_conveyerList;
private int resource;
private LayoutInflater inflater;
ListAdapter(Context context, int resource, List<ListView_fixture_conveyer> objects) {
super(context, resource, objects);
fixture_conveyerList = objects;
this.resource = resource;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(resource, null);
}
final TextView team1_name,team2_name;
final TextView tournament,time;
ImageView team1_photo,team2_photo;
team1_photo = convertView.findViewById(R.id.team1);
team2_photo = convertView.findViewById(R.id.team2);
team1_name = convertView.findViewById(R.id.team1_name);
team2_name = convertView.findViewById(R.id.team2_name);
tournament= convertView.findViewById(R.id.tournament);
time= convertView.findViewById(R.id.timecounter);
ImageLoader.getInstance().displayImage(fixture_conveyerList.get(position).getTeam1_photo(), team1_photo);
ImageLoader.getInstance().displayImage(fixture_conveyerList.get(position).getTeam2_photo(), team2_photo);
team1_name.setText(fixture_conveyerList.get(position).getTeam1_name());
team2_name.setText(fixture_conveyerList.get(position).getTeam2_name());
tournament.setText(fixture_conveyerList.get(position).getTournament());
time.setText(fixture_conveyerList.get(position).getTime());
Log.e("mytimer",fixture_conveyerList.get(position).getTime());
if (!("false").equals(fixture_conveyerList.get(position).getTime())){
Log.e("inside_mytimer",fixture_conveyerList.get(position).getTime());
long newValue=Long.parseLong(fixture_conveyerList.get(position).getTime());
new CountDownTimer(newValue, 1000) {
#SuppressLint({"DefaultLocale", "SetTextI18n"})
public void onTick(long millisUntilFinished) {
time.setText("" + String.format(FORMAT,
TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
public void onFinish() {
time.setText("Fixture closed");
}
}.start();
}
else{
time.setText("Fixture closed");
}
return convertView;
}
}
}
Here is my model class code
public class ListView_fixture_conveyer {
private String tournament;
private String team1_photo;
private String team2_photo;
private String team1_name;
private String team2_name;
private String time;
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getTeam1_name() {
return team1_name;
}
public void setTeam1_name(String team1_name) {
this.team1_name = team1_name;
}
public String getTeam2_name() {
return team2_name;
}
public void setTeam2_name(String team2_name) {
this.team2_name = team2_name;
}
public String getTournament() {
return tournament;
}
public void setTournament(String tournament) {
this.tournament = tournament;
}
public String getTeam1_photo() {
return team1_photo;
}
public void setTeam1_photo(String team1_photo) {
this.team1_photo = team1_photo;
}
public String getTeam2_photo() {
return team2_photo;
}
public void setTeam2_photo(String team2_photo) {
this.team2_photo = team2_photo;
}
}
Edit (Tested)
---> For Timer issue , you need to take time variable in your class and update variable with Handler use it with reload data. Like,
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
for (int i = 0, dataLength = fixture_conveyerList.size(); i < dataLength; i++) {
ListView_fixture_conveyer item = fixture_conveyerList.get(i);
item.timeRemaining -= 1000;
}
adapter.notifyDataSetChanged();
timerHandler.postDelayed(this, 1000); //run every Second
}
};
List Adapter Class
public class ListAdapter extends ArrayAdapter {
private List<ListView_fixture_conveyer> fixture_conveyerList;
private int resource;
private LayoutInflater inflater;
ViewHolder holder;
ListAdapter(Context context, int resource, List<ListView_fixture_conveyer> objects) {
super(context, resource, objects);
fixture_conveyerList = objects;
this.resource = resource;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
timerHandler.postDelayed(timerRunnable, 50); //start unique timer
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(resource, null);
holder = new ViewHolder();
holder.team1_photo = convertView.findViewById(R.id.team1);
holder.team2_photo = convertView.findViewById(R.id.team2);
holder.team1_name = convertView.findViewById(R.id.team1_name);
holder.team2_name = convertView.findViewById(R.id.team2_name);
holder.tournament = convertView.findViewById(R.id.tournament);
holder.time = convertView.findViewById(R.id.timecounter);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ImageLoader.getInstance().displayImage(fixture_conveyerList.get(position).getTeam1_photo(), holder.team1_photo);
ImageLoader.getInstance().displayImage(fixture_conveyerList.get(position).getTeam2_photo(), holder.team2_photo);
holder.team1_name.setText(fixture_conveyerList.get(position).getTeam1_name());
holder.team2_name.setText(fixture_conveyerList.get(position).getTeam2_name());
holder.tournament.setText(fixture_conveyerList.get(position).getTournament());
holder.time.setText(fixture_conveyerList.get(position).timeRemaining);
Log.e("mytimer", fixture_conveyerList.get(position).getTime());
if (!("false").equals(fixture_conveyerList.get(position).getTime())) {
Log.e("inside_mytimer", fixture_conveyerList.get(position).getTime());
long newValue = fixture_conveyerList.get(position).timeRemaining;
if (newValue > 0) {
holder.time.setText(String.format(FORMAT,
TimeUnit.MILLISECONDS.toHours(newValue),
TimeUnit.MILLISECONDS.toMinutes(newValue) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(newValue)),
TimeUnit.MILLISECONDS.toSeconds(newValue) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(newValue))));
} else {
holder.time.setText("Fixture closed");
}
} else {
holder.time.setText("Fixture closed");
}
return convertView;
}
}

how can i setOnItemClickListener in this code And i wanted to check for the internet while app is running

//This is where the codes start actually.I want to open an activity from a listOnclick listner i have tried alot but i was not able to set the listners can someone please help me here i am i new bee
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
lvMovies = findViewById(R.id.lvMovies);
}
this is where i starts the Jsontask
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_dry_clean:
new JSONTask().execute("");
return true;
case R.id.press:
new JSONTask().execute("https:/");
return true;
}
return false;
}
};
this is where AsyncTask starts.
public class JSONTask extends AsyncTask<String, String, List<MovieModel>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
#Override
protected List<MovieModel> doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL(params[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream stream = httpURLConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentobject = new JSONObject(finalJson);
JSONArray parentarray = parentobject.getJSONArray("movies");
List<MovieModel> movieModelList = new ArrayList<>();
for (int i = 0; i < parentarray.length(); i++) {
JSONObject finalObject = parentarray.getJSONObject(i);
MovieModel movieModel = new MovieModel();
movieModel.setClothesname(finalObject.getString("clothesname"));
movieModel.setPrice(finalObject.getInt("price"));
movieModel.setImage(finalObject.getString("image"));
///adding the final object in the list*/
movieModelList.add(movieModel);
}
return movieModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null)
httpURLConnection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<MovieModel> result) {
super.onPostExecute(result);
dialog.dismiss();
MovieAdapter adapter = new MovieAdapter(getApplicationContext(), R.layout.row, result);
lvMovies.setAdapter(adapter);
}
}
// this is the adapter
public class MovieAdapter extends ArrayAdapter {
private List<MovieModel> movieModelList;
private int resource;
private LayoutInflater inflater;
public MovieAdapter(Context context, int resource, List<MovieModel> objects) {
super(context, resource, objects);
movieModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, #Nullable View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(resource, null);
holder.tvMovie = convertView.findViewById(R.id.clothes_name);
holder.tvYear = convertView.findViewById(R.id.price);
holder.ivMovieIcon = convertView.findViewById(R.id.list_view_icon);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Do you want to start a new activity when an item in listview clicked?
you can use holder.setOnClickListener
otherwise, give us more details about what you want
you can use this code for RecyclerView adapter
public class MovieAdapterextends RecyclerView.Adapter<MovieAdapter.OrderHolder> {
private List<MovieModel> movieModelList;
private int resource;
private LayoutInflater inflater;
public MovieAdapter(Context context, int resource, List<MovieModel> objects) {
super(context, resource, objects);
movieModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public OrderHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.row_video, parent, false);
return new OrderHolder(view);
}
#Override
public void onBindViewHolder(final OrderHolder holder, final int position) {
VideoObject videoObject = list.get(position);
//put your code here to set text for textview like that
holder.txvTitle.setText(videoObject.getVideo_title());
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playVideo(videoObject.getVideo_code(), videoObject.getVideo_image());
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//write your code to start activity
Intent intent=new Intent(context,YOUR_ACTIVITY.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class OrderHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView clothes_name;
private TextView clothes_name;
private ImageView list_view_icon;
OrderHolder(View itemView) {
super(itemView);
clothes_name= itemView.findViewById(R.id.clothes_name);
price= itemView.findViewById(R.id.price);
list_view_icon= itemView.findViewById(R.id.list_view_icon);
}
#Override
public void onClick(View view) {
}
}
}

Adapter not displaying correct data

I am developing an application in which i am getting a large json data from the server. i want to display it in the list view. But i am getting the same value repeated. The no of items shown by the list view is proper. only same data repeated in all the list items.
Here is my code.
public class HistoryActivity extends AppCompatActivity {
private Toolbar toolbar;
String strServerResponse = null;
ProgressDialog nDialog;
ArrayList<String>clicklat;
ArrayList<String>clicklong;
ArrayList<String>dttime;
ArrayList<Pojo> history;
HistoryAdapter myAdapter;
ListView list;
public String date, inTime, outTime, inLat, inLong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("History");
clicklat=new ArrayList<String>();
clicklong=new ArrayList<String>();
dttime=new ArrayList<String>();
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
list = (ListView) findViewById(R.id.historyList);
history = new ArrayList<Pojo>();
new NetCheck().execute();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ArrayList<String>clicklat= new ArrayList<String>(history.get(position).getLati());
ArrayList<String>clicklong= new ArrayList<String>(history.get(position).getLongi());
ArrayList<String>dttime= new ArrayList<String>(history.get(position).getDatetime());
Intent i = new Intent(HistoryActivity.this, DetailsActivity.class);
i.putStringArrayListExtra("clicklat", clicklat);
i.putStringArrayListExtra("clicklong", clicklong);
i.putStringArrayListExtra("clickdatetime", dttime);
startActivity(i);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class NetCheck extends AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
nDialog.dismiss();
// TODO Auto-generated method stub
myAdapter = new HistoryAdapter(HistoryActivity.this, history);
list.setAdapter(myAdapter);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(
"http://myurl");
httpRequest.setHeader("Content-Type", "application/json");
SharedPreferences mmm = getSharedPreferences(
"MyPref", MODE_PRIVATE);
String logempid = mmm.getString("id", null);
JSONObject json = new JSONObject();
json.put("empid", logempid);
Log.e("JSON Object", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
httpRequest.setEntity(se);
HttpResponse httpRes = httpClient.execute(httpRequest);
java.io.InputStream inputStream = httpRes.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
strServerResponse = sb.toString();
Log.e("Server Response", "" + strServerResponse.toString());
if (strServerResponse != null) {
try {
JSONArray arr = new JSONArray(strServerResponse);
for (int k = 0; k < arr.length(); k++) {
JSONObject jsonObj1 = arr.getJSONObject(k);
Pojo pojo = new Pojo();
JSONArray subArrayLat = jsonObj1.getJSONArray("lati_long");
List<String> lati= new ArrayList<String>();
List<String> longi= new ArrayList<String>();
List<String> dateandtime= new ArrayList<String>();
for (int i = 0; i < subArrayLat.length(); i++) {
String lat = subArrayLat.getJSONObject(i).getString("Latitude").toString();
String loong = subArrayLat.getJSONObject(i).getString("Longitude").toString();
String datetimee = subArrayLat.getJSONObject(i).getString("date_time").toString();
lati.add(lat);
longi.add(loong);
dateandtime.add(datetimee);
}
pojo.setLati(lati);//adding latitude list
pojo.setLongi(longi); //adding longitude list
pojo.setDatetime(dateandtime);
String dateee = arr.getJSONObject(k).getString("login_date");
String timeeee = arr.getJSONObject(k).getString("login_time");
String timeeee2 = arr.getJSONObject(k).getString("logout_time");
pojo.setDate(dateee);
pojo.setLoginTime(timeeee);
pojo.setLogoutTime(timeeee2);
history.add(pojo);
}
} catch (JSONException e) {
e.printStackTrace();
}
And this is Adapter
public class HistoryAdapter extends BaseAdapter {
private Context activity;
TextView tv_date;
TextView tv_loginTime;
TextView tv_logoutTime;
ArrayList<Pojo> list;
private ArrayList<Pojo> arraylist = null;
public static LayoutInflater inflater;
private Context context;
public HistoryAdapter(Context a, ArrayList<Pojo> history) {
// TODO Auto-generated constructor stub
activity = a;
list = history;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arraylist = new ArrayList<Pojo>();
this.arraylist.addAll(list);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if(convertView == null) {
v = inflater.inflate(R.layout.history_item, parent, false);
}
final Pojo pojo = list.get(position);
tv_date = (TextView) v.findViewById(R.id.historyDate);
tv_loginTime = (TextView) v.findViewById(R.id.historyLoginTime);
tv_logoutTime = (TextView) v.findViewById(R.id.historyLogoutTime);
tv_date.setText(pojo.getDate());
tv_loginTime.setText(pojo.getLoginTime());
tv_logoutTime.setText(pojo.getLogoutTime());
return v;
}
}
and setters and getters
public class Pojo {
public static String empid11;
public static String loginTime;
public static String date;
public static String logoutTime;
public static List<String> lat;
public static List<String> datetime;
public static List<String> longi;
public static List<String> inlogin;
public static List<String> inDate;
public List<String> getInTime(){
return this.inlogin;
}
public List<String> getInDate(){
return this.inDate;
}
public void setInDate(List<String> inDate){
this.inDate = inDate;
}
public List<String> getLati(){
return this.lat;
}
public List<String> getLongi(){
return this.longi;
}
public void setLati(List<String> lat){
this.lat = lat;
}
public void setLongi(List<String> longi){
this.longi = longi;
}
public void setId(String empid) {
this.empid11 = empid;
}
public String getId() {
return empid11;
}
public void setLoginTime(String loginTime) {
this.loginTime = loginTime;
}
public String getLoginTime() {
return loginTime;
}
public void setLogoutTime(String logoutTime) {
this.logoutTime = logoutTime;
}
public String getLogoutTime() {
return logoutTime;
}
public void setDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public List<String> getDatetime(){
return this.datetime;
}
public void setDatetime(List<String> datetime){
this.datetime = datetime;
}
}
Hello see the modifiy version of your adapter. Let me know if you have any problem with it.
public class HistoryAdapter extends BaseAdapter
{
private Context activity;
TextView tv_date;
TextView tv_loginTime;
TextView tv_logoutTime;
private ArrayList<Pojo> arraylist = null;
public static LayoutInflater inflater;
private Context context;
public HistoryAdapter(Context a) {
activity = a;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arraylist = new ArrayList<Pojo>();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void addHistoryData(ArrayList<Pojo> newDataset){
if(arraylist != null){
arraylist.addAll(newDataset);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder mViewHolder = null;
if(convertView == null)
{
mViewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.history_item, parent, false);
mViewHolder.tv_date = (TextView) convertView.findViewById(R.id.historyDate);
mViewHolder.tv_loginTime = (TextView)convertView.findViewById(R.id.historyLoginTime);
mViewHolder.tv_logoutTime = (TextView)convertView.findViewById(R.id.historyLogoutTime);
convertView.setTag(mViewHolder);
}else{
mViewHolder = (ViewHolder) convertView.getTag();
}
final Pojo pojo = list.get(position);
mViewHolder.tv_date.setText(pojo.getDate());
mViewHolder.tv_loginTime.setText(pojo.getLoginTime());
mViewHolder.tv_logoutTime.setText(pojo.getLogoutTime());
return v;
}
public class ViewHolder{
TextView tv_date
TextView tv_loginTime;
TextView tv_logoutTime;
}
}
In next the activity NetCheck class when web service response come change like below :
history.add(pojo);
myAdapter.addHistoryData(history);
myAdapter.notifiyDatasetChanged();
There may be problem you are getting repeated value in array, please check your array first.

How to populate partial Data into ListView

Still i am populating all JSON data into ListView, but now i want to populate (records into ListView) based on visibility, when user scrolls I want to show progess bar for 5 seconds and then want to populate more records (those will be visible to user) and so on...
I don't want to populate all data into ListView for the first time !
MainActivity.java:
public class MainActivity extends Activity {
ArrayList<Main> arrayList;
MainAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayList = new ArrayList<Main>();
new JSONAsyncTask().execute("....");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new MainAdapter(getApplicationContext(), R.layout.row, arrayList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), arrayList.get(position).getTitle(), Toast.LENGTH_LONG).show();
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Main main = new Main();
main.setTitle(object.getString("title"));
Log.v("title:", object.getString("title"));
arrayList.add(main);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
MainAdapter.java:
public class MainAdapter extends BaseAdapter {
ArrayList<Main> arrayList;
LayoutInflater layoutInflater;
int resource;
ViewHolder viewHolder;
public MainAdapter(Context context, int resource, ArrayList<Main> arrayList) {
this.layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.resource = resource;
this.arrayList = arrayList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View view = convertView;
if (view == null) {
viewHolder = new ViewHolder();
view = layoutInflater.inflate(resource, null);
viewHolder.tvName = (TextView) view.findViewById(R.id.tvName);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.tvName.setText(arrayList.get(position).getTitle());
return view;
}
static class ViewHolder {
public TextView tvName;
}
}
You can try using this library (Android-Infinite-Scroll-Listview)
I've used it before and it's easy to work with.

filter search in android

I am making a filter search to my listview. My listview code is executing well. I put an edittext object and I will make the filter search. How can i make this? My codes are below.
package com.nexum.imageloadingromjson;
public class MainActivity extends Activity {
private ListView list;
private MyAdapter adapter;
private final String parsingUrl = "someurl";
private String tag_coord = "Coord";
private String tag_lat = "Lat";// Double
private String tag_lon = "Lon";// Double
private String tag_image = "Image";
private String tag_InIzmir = "InIzmir";// Boolean
private String tag_name = "Name";
private ImageLoader imageLoader;
private EditText filteredittext;
private ProgressDialog pDialog;
private static int clickedItemPosition = -1;
private final int REQUEST_CODE_DETAIL = 1;
ArrayList<CoordItem> items;
ArrayList<CoordItem> filterlist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
items = new ArrayList<CoordItem>();
filterlist = new ArrayList<CoordItem>();
adapter = new MyAdapter(this, R.layout.list_item, items);
list = (ListView) findViewById(R.id.exampList);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
filteredittext = (EditText)findViewById(R.id.filtersearchedittext);
filteredittext.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
viewitems.clear();
String search = filteredittext.getText().toString();
for (int i = 0; i < items.size(); i++) {
if(items.get(i).name.equals(search)){
viewitems.add(items.get(i));
adapter.notifyDataSetChanged();
}
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
pDialog = new ProgressDialog(this);
pDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
pDialog.setMessage("Veriler alınıyor...");
new ListViewLoad().execute();
list.setOnItemClickListener(new OnItemClickListener() {
#SuppressLint("ShowToast")
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
/*
* String bulunma = ""; if (items.get(position).inIzmir) {
* bulunma+="İzmir de bulundu."; }else{
* bulunma+="İzmir de bulunmadı."; } String
* s="Name:"+items.get(position).name+"\nInIzmir:"+bulunma;
* Toast.makeText(getApplicationContext(), s,
* Toast.LENGTH_LONG).show();
*/
clickedItemPosition = position;
Intent myIntent = new Intent(MainActivity.this,
DetailActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable(
"parcelable_key",
new CoordItem(items.get(position).name, items
.get(position).img, items.get(position).lat,
items.get(position).lon,
items.get(position).inIzmir));
myIntent.putExtras(bundle);
// Güncelleme olayı burada baÅŸlıyor
// startActivityForResult(myIntent, REQUEST_CODE_DETAIL);
startActivityForResult(myIntent, REQUEST_CODE_DETAIL);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_DETAIL && resultCode == RESULT_OK
&& data != null) {
CoordItem coorditem = new CoordItem(data.getStringExtra("name"),
items.get(clickedItemPosition).img, Double.parseDouble(data
.getStringExtra("lat")), Double.parseDouble(data
.getStringExtra("lon")),
items.get(clickedItemPosition).inIzmir);
items.set(clickedItemPosition, coorditem);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Guncelleme yapıldı.",
Toast.LENGTH_SHORT).show();
}
}
private class ListViewLoad extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String json = getStringFromURL(parsingUrl);
try {
final JSONArray jArray = new JSONArray(json);
for (int i = 0; i < jArray.length(); i++) {
JSONObject c = jArray.getJSONObject(i);
JSONObject coord = c.getJSONObject(tag_coord);
double lat = coord.getDouble(tag_lat);
double lon = coord.getDouble(tag_lon);
String image = c.getString(tag_image);
boolean InIzmir = c.getBoolean(tag_InIzmir);
String name = c.getString(tag_name);
CoordItem item = new CoordItem(name, image, lat, lon,
InIzmir);
items.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
adapter.notifyDataSetChanged();
pDialog.dismiss();
}
}
private class MyAdapter extends ArrayAdapter<CoordItem> {
private LayoutInflater inflater;
public MyAdapter(Context context, int textViewResourceId,
ArrayList<CoordItem> objects) {
super(context, textViewResourceId, objects);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
this.inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
if (items != null)
return items.size();
else
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewholder = null;
if (convertView == null) {
viewholder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item, parent,
false);
viewholder.listItemImage = (ImageView) convertView
.findViewById(R.id.listItemImage);
viewholder.listItemName = (TextView) convertView
.findViewById(R.id.listItemName);
viewholder.listItemInIzmir = (TextView) convertView
.findViewById(R.id.listItemInIzmir);
viewholder.listItemLatitude = (TextView) convertView
.findViewById(R.id.listItemLatitude);
viewholder.listItemLongitude = (TextView) convertView
.findViewById(R.id.listItemLongitude);
convertView.setTag(viewholder);
} else {
viewholder = (ViewHolder) convertView.getTag();
}
viewholder.listItemName.setText(items.get(position).name);
if (items.get(position).inIzmir) {
viewholder.listItemInIzmir.setText("Izmirde.");
} else {
viewholder.listItemInIzmir.setText("Izmirde degil.");
}
DisplayImageOptions options = new DisplayImageOptions.Builder().delayBeforeLoading(1000).build();
imageLoader.displayImage(items.get(position).img,viewholder.listItemImage,options);
return convertView;
}
public Drawable getDrawableFromUrl(URL url) {
try {
InputStream is = (InputStream) url.getContent();
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (Exception e) {
return null;
}
}
}
static class ViewHolder {
ImageView listItemImage;
TextView listItemName, listItemInIzmir, listItemLatitude,
listItemLongitude;
}
public String getStringFromURL(String url) {
// Making HTTP request
String json = "";
InputStream is = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// return JSON String
return json;
}
}
What must i write to onTextChanged method in these codes? I researched but I didn't find codes for this class. Or I did not edit.
For searching on listview check the link here.
How can I filter ListView data when typing on EditText in android
If you want make custom search you can use the code below
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<EditText
android:id="#+id/search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Main Activity
public class MainActivity extends Activity {
ArrayList<NewData> mTemp=new ArrayList<NewData>(); //temporary list for search data
ArrayList<NewData> mPostingData=new ArrayList<NewData>(); //data to post in listview
ArrayList< NewData> mOri = new ArrayList<NewData>() ;//original data
// You can have two arraylist instead of three. 1. for original values 2. one for search result.
Myadapter ma;
EditText search;
NewData nd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int i = 0; i < 20; i++)
{
// Add your Json Parsed Data here
// each item from json add it to hash map in NewData class. Arraylist of 0 contains jsondata of customer1
nd=new NewData();
nd.newDatacus.put(NewData.TAG_CUSTOMER_CODE, "i"+i);
nd.newDatacus.put(NewData.TAG_CUSTOMER_NAME, "a"+i);
nd.newDatacus.put(NewData.TAG_CUSTOMER_MOBILE, "number");
nd.newDatacus.put(NewData.TAG_CUSTOMER_ADDRESS, "address");
mOri.add(nd);
}
ma= new Myadapter(MainActivity.this);
mPostingData=mOri;
mTemp=mOri;
ListView lv= (ListView) findViewById(R.id.list);
lv.setAdapter(ma);
search= (EditText) findViewById(R.id.search); //editext
search.addTextChangedListener(new TextWatcher() { //supply edittext value to filter
public void onTextChanged(CharSequence s, int start, int before, int count) {
ma.getFilter().filter(s);
ma.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
class Myadapter extends ArrayAdapter
{
LayoutInflater mInflater;
public void setData(ArrayList<NewData> mPpst) { //function to set data based on search result
mPostingData = mPpst;//contains class items data.
}
#Override
public Filter getFilter() { //implement getFilter
return new Filter() {
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count >= 0) {
setData((ArrayList<NewData>) results.values);//if results of search is null set the searched results data
} else {
setData(mOri);// set original values
}
notifyDataSetInvalidated();//refresh listview
}
//this performs filtering data.//check if data matches whats typed in editext
//add it to list if found. return list (founditems)
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if (!TextUtils.isEmpty(constraint)) {
constraint = constraint.toString().toLowerCase();
ArrayList<NewData> foundItems = new ArrayList<NewData>();
if(mTemp!=null)
{
for(int i=0;i<mTemp.size();i++)
{
if (mTemp.get(i).newDatacus.get(NewData.TAG_CUSTOMER_CODE).toString().contains(constraint)) {
System.out.println("My datas"+mTemp.get(i).newDatacus.get(NewData.TAG_CUSTOMER_CODE).toString());
foundItems.add(mTemp.get(i));
}
else
{
}
}
}
result.count = foundItems.size();//search results found return count
result.values = foundItems;// return values
}
else
{
result.count=-1;// no search results found
}
return result;
}
};
}
public Myadapter(Context context) {
super(context, 0);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mPostingData.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(mOri == null ){
return null;
}
// When convertView is not null, we can reuse it directly, there is no need
// to reinflate it. We only inflate a new View when the convertView supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list, null);
convertView.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.t1=(TextView) convertView.findViewById(R.id.textView1);
holder.t2 = (TextView) convertView.findViewById(R.id.textView2);
holder.t3 = (TextView) convertView.findViewById(R.id.textView3);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
holder.t1.setText(mPostingData.get(position).newDatacus.get(NewData.TAG_CUSTOMER_CODE).toString());
holder.t2.setText(mPostingData.get(position).newDatacus.get(NewData.TAG_CUSTOMER_NAME).toString());
holder.t3.setText(mPostingData.get(position).newDatacus.get(NewData.TAG_CUSTOMER_MOBILE).toString());
return convertView;
}
}
class ViewHolder
{
TextView t1,t2,t3;
}
}
list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:text="TextView" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:text="TextView" />
</LinearLayout>
NewData Class- Holds all data in hashmap
public class NewData {
public static final String TAG_CUSTOMER_CODE = "customer_code";
public static final String TAG_CUSTOMER_NAME = "customer_name";
public static final String TAG_CUSTOMER_MOBILE = "customer_mobile";
public static final String TAG_CUSTOMER_ADDRESS = "customer_address";
Hashtable newDatacus=new Hashtable();
public NewData()
{
newDatacus.put(NewData.TAG_CUSTOMER_CODE,new String());
newDatacus.put(NewData.TAG_CUSTOMER_ADDRESS,new String());
newDatacus.put(NewData.TAG_CUSTOMER_NAME,new String());
newDatacus.put(NewData.TAG_CUSTOMER_MOBILE,new String());
newDatacus.put(NewData.TAG_CUSTOMER_ADDRESS,new String());
}
}
Please try with the below code.
you must integrate this line .. where you are setting adapter .
listView.setAdapter(new MyAddapter(this));
array_sort.clear();
array_sort.addAll(Service_Listitems);
then use below lines.
edittext_search.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){
try {
Service_Listitems.clear();// Clear your arraylist initially
for (int i = 0; i < array_sort.size(); i++) {
if (array_sort.get(i) instanceof yourServiceSetterGetterClass) {
yourServiceSetterGetterClass cp1 = (yourServiceSetterGetterClass)array_sort.get(i);
String strOrig = "";
if (cp1.getFirstName() == null) {
strOrig = "";
} else {
strOrig = cp1.getFirstName().toUpperCase().trim();
}
String str = edittext_search.getText().toString().toUpperCase().trim();
if (strOrig.startsWith(str)) { Service_Listitems.add(cp1);
}
}
}
listView.setAdapter(new MyAddapter(this));
} catch (Exception e) {
e.printStackTrace();
}
}
});;
EDIT
ArrayList<CoordItem> Service_Listitems= new ArrayList<CoordItem>();
private ArrayList<Object> array_sort = new ArrayList<Object>();
or you can use like below also
private ArrayList<CoordItem> array_sort = new ArrayList<CoordItem>();

Categories

Resources