I just started to program for Android.
I'm building this app for my internship but I'm stock with the search function.
I have a CVS file were I set the value in a ArrayList, for this I build a CSV adapter and call this adapter in my Fragment. Now everything works fine I get my list with all the values I want, the problem is the list consist of 1000 records. This is why I want to implement a searchview so that the user can search for the desire value.
Now I want when the user choose the search and starts typing the Arrylist is searched and starts to filter the possible options in the list. This way when the desire value is shown the user can select this one.
I've been trying to do this 3 days already, I know I have to do something in the onQueryTextChange and onQueryTextsubmit. But so far no luck :(
Can someone help me solve this please I would really appreciate it. Tnx in advance.
public class CSVAdapter extends ArrayAdapter<airports> {
Context ctx;
public CSVAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
//Store a reference to the Context so we can use it to load a file from Assets.
this.ctx = context;
//Load the data.
loadArrayFromFile();
}
#Override
public View getView(final int pos, View convertView, final ViewGroup parent){
RelativeLayout row = (RelativeLayout)convertView;
if(null == row){
//No recycled View, we have to inflate one.
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.departure_point_fragment, null);
}
TextView anameTxt = (TextView)row.findViewById(R.id.airport_name);
TextView acityTxt = (TextView)row.findViewById(R.id.airport_city);
TextView acountryTxt = (TextView)row.findViewById(R.id.airport_country);
TextView icaoTxt = (TextView)row.findViewById(R.id.airport_code);
anameTxt.setText(getItem(pos).getAname());
acityTxt.setText(getItem(pos).getAcity());
acountryTxt.setText(getItem(pos).getAcountry());
icaoTxt.setText(getItem(pos).getIcao());
return row;
}
private void loadArrayFromFile(){
try {
// Get input stream and Buffered Reader for our data file.
InputStream is = ctx.getAssets().open("airports.csv");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
//Read each line
while ((line = reader.readLine()) != null) {
//Split to separate the name from the capital
String[] RowData = line.split(",");
//Create a State object for this row's data.
airports cur = new airports();
cur.setAname(RowData[0]);
cur.setAcity(RowData[1]);
cur.setAcountry(RowData[2]);
cur.setIcao(RowData[3]);
cur.setLat(RowData[4]);
cur.setLon(RowData[5]);
cur.setAltitude(RowData[6]);
cur.setTimezone(RowData[7]);
cur.setDst(RowData[8]);
//Add the State object to the ArrayList (in this case we are the ArrayList).
this.add(cur);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class airports {
private String aname;
private String acity;
private String acountry;
private String icao;
private String lat;
private String lon;
private String altitude;
private String timezone;
private String dst;
public String getAname() {
return aname;
}
public void setAname(String aname) {
this.aname = aname;
}
public String getAcity() {
return acity;
}
public void setAcity(String acity) {
this.acity = acity;
}
public String getAcountry() {
return acountry;
}
public void setAcountry(String acountry) {
this.acountry = acountry;
}
public String getIcao() {
return icao;
}
public void setIcao(String icao) {
this.icao = icao;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLon() {
return lon;
}
public void setLon(String lon) {
this.lon = lon;
}
public String getAltitude() {
return altitude;
}
public void setAltitude(String altitude) {
this.altitude = altitude;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public String getDst() {
return dst;
}
public void setDst(String dst) {
this.dst = dst;
}
}
public class departurePointFragment extends SherlockListFragment implements SearchView.OnQueryTextListener{
private CSVAdapter mAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.listview, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState); getSherlockActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSherlockActivity().getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
setHasOptionsMenu(true);
mAdapter =new CSVAdapter(getActivity(), -1);
setListAdapter(mAdapter);
getListView();
setRetainInstance(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.searching, menu);
MenuItem item = menu.findItem(R.id.menu_search);
SearchView itemview = (SearchView) item.getActionView();
// Execute this when searching
itemview.setOnQueryTextListener(this);
super.onCreateOptionsMenu(menu, inflater);
Log.d("Nicola", "2");
}
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String query) {
Log.d("Nicola", "100");
return true;
}
}
Took a while to figure this out, but here it goes :)
Add this to your adapter:
ArrayList<airports> airportsArray = new ArrayList<airports>();
public ArrayList<airports> getAirportsArray()
{
return airportsArray;
}
(you can rightclick on the ArrayList declaration, the choose Source->Generate Getters and Setters)
After reading the CSV file you can add these objects to the newly created ArrayList, changing:
this.add(cur);
to
this.add(cur);
airportsArray.add(cur);
Then in your fragment, in the onQueryTextChange method, do the following:
this.mAdapter.clear(); // This clears the existing list
// Loop through the airports
for (airports item : mAdapter.getAirportsArray())
{
// Does the name contains what you are searching for?
// You can add more criteria here using the || (OR) operator
if (item.getAname().contains(query))
{
// If so, add it
mAdapter.add(item);
}
}
mAdapter.notifyDataSetChanged(); // Notify the adapter that the dataset changed
return true;
Hope that helps, good luck!
Related
Hello I am creating an app which reads a file and its contents should be shown in recyclerview, I have done it but only first line is showing remaining lines are not showing
My file contains data as shown below
123
345
567
I have used buffered reader and input stream to read file
Here is the class for recyclerAdapter
public class RecyclerAdapter extends
RecyclerView.Adapter<RecyclerAdapter.Phone> {
List<PhoneNumber> phoneNumbers;
public RecyclerAdapter(List<PhoneNumber> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
#NonNull
#Override
public Phone onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.text,viewGroup,false);
Phone phone = new Phone(view);
return phone;
}
#Override
public void onBindViewHolder(#NonNull Phone phone, int i) {
phone.textView.setText(phoneNumbers.get(i).number);
}
#Override
public int getItemCount() {
return phoneNumbers.size();
}
public class Phone extends RecyclerView.ViewHolder {
TextView textView;
public Phone(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.txt);
}
}
}
Here is the code of my class
public class ScheduledFragment extends Fragment {
String[] strings;
RecyclerView listView;
List<PhoneNumber> phoneNumbers;
public ScheduledFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_scheduled, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
listView = view.findViewById(R.id.list);
ReadFile();
initialiseAdapter();
}
private void initialiseAdapter() {
listView.setHasFixedSize(true);
listView.setLayoutManager(new LinearLayoutManager(getContext()));
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(phoneNumbers);
listView.setAdapter(recyclerAdapter);
}
private void ReadFile() {
phoneNumbers = new ArrayList<>();
try {
InputStream inputStream = getActivity().getAssets().open("phone.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
boolean hasNext = true;
while (hasNext) {
String line = bufferedReader.readLine();
phoneNumbers.add(new PhoneNumber(line));
hasNext = line != null;
}
inputStream.close();
} catch (IOException e) {
//log the exception
}
}
}
class PhoneNumber {
String number;
public PhoneNumber() {
}
public PhoneNumber(String number) {
this.number = number;
}
}
I am only getting first line show in recyclerview
Expected results:
123
345
567
results I am getting:
123
Try to improve your while, you don't need a variable for this:
while (true) {
String line = bufferedReader.readLine();
if(line == null) {
break;
} else if (line.equals("")) {
phoneNumbers.add(new PhoneNumber("\n"));
/*I'm not sure if you really want "/n" breaks*/
} else {
phoneNumbers.add(new PhoneNumber(line));
}
Log.d("test", line);
}
ps: for convention use capital letters only for Classes not methods (readFile not ReadFile)
I am using a recyclerView to show a grid of movie posters. The posters are contained in a List<> along with their respective title and so on.
I implemented a searchView widget and I can successuflly get a List of matching results. But I can't hide the other ones.
As you understand I don't want to delete the irrelevant movies from the adapter or the user would not be able to see them again.
This is the code:
public class SearchUtils {
public static List<String> search(List<Show> list, String keyword){
List<String> results = new ArrayList<>();
for (Show curVal : list){
String curTitle = curVal.getTitle().toLowerCase().trim();
if (curTitle.contains(keyword)){
results.add(curTitle);
}else{
results = new ArrayList<>();
}
}
return results;
}
}
ListFragment.java
public class ListFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<Show>> {
private static final String LOG_TAG = "ListFragment";
private static final String ARG_SCOPE = "com.dcs.shows.activity_to_launch";
private static final String BASE_URL = "http://api.themoviedb.org/3";
private TextView tv;
private ProgressBar pb;
private int scope;
private RecyclerView mRecyclerView;
private ShowAdapter mShowAdapter;
private SearchView mSearchView;
public static ListFragment newInstance(int target) {
Bundle args = new Bundle();
args.putInt(ARG_SCOPE, target);
ListFragment fragment = new ListFragment();
fragment.setArguments(args);
return fragment;
}
public ListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scope = getArguments().getInt(ARG_SCOPE);
setHasOptionsMenu(true);
Log.i(LOG_TAG, "onCreate#Scope is: " + scope);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list, container, false);
mShowAdapter = new ShowAdapter(new ArrayList<Show>());
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
GridLayoutManager glm = new GridLayoutManager(getActivity(), 4);
mRecyclerView.setLayoutManager(glm);
mRecyclerView.addItemDecoration(new SpacesItemDecoration(8, getActivity()));
mRecyclerView.setAdapter(mShowAdapter);
mRecyclerView.addOnScrollListener(new EndlessRecyclerViewScrollListener(glm) {
#Override
public void onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to the bottom of the list
}
});
pb = (ProgressBar)rootView.findViewById(R.id.progress_view);
ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// fetch data
getLoaderManager().initLoader(1, null, this);
} else {
// display error
pb.setVisibility(View.GONE);
}
return rootView;
}
List<Show> searchList;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
getActivity().getMenuInflater().inflate(R.menu.main, menu);
final MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
mSearchView = (SearchView) myActionMenuItem.getActionView();
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
if(!mSearchView.isIconified()) {
mSearchView.setIconified(true);
}
myActionMenuItem.collapseActionView();
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if(s != null || !s.isEmpty()) {
for(Show movie : mShowAdapter.getList()) {
if(movie.getTitle().toLowerCase().contains(s.toLowerCase())){
mShowAdapter.add(movie);
}
mShowAdapter.notifyDataSetChanged();
}
} else {
mShowAdapter.addItemsToList(searchList, false);
}
return false;
}
});
mSearchView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
#Override
public void onViewDetachedFromWindow(View arg0) {
// search was detached/closed
Log.v(LOG_TAG, "Restoring list: " + searchList + " size: " + searchList.size());
mShowAdapter.addItemsToList(searchList, false);
}
#Override
public void onViewAttachedToWindow(View arg0) {
// search was opened
searchList = mShowAdapter.getList();
}
});
}
private class ShowHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mTextView;
public ShowHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.grid_item_image);
mTextView = (TextView) itemView.findViewById(R.id.grid_item_title);
}
}
private class ShowAdapter extends RecyclerView.Adapter<ShowHolder> {
private List<Show> mShows;
public ShowAdapter(List<Show> shows) {
mShows = shows;
}
public void add(Show show){
mShows.add(show);
notifyDataSetChanged();
}
public void addItemsToList(List<Show> newShows, boolean append){
if(append){
mShows.addAll(newShows);
}else {
mShows = newShows;
}
notifyDataSetChanged();
}
public void removeItemsFromList(int index){
mShows.remove(index);
notifyItemRemoved(index);
}
public List<Show> getList(){
return mShows;
}
#Override
public ShowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(getActivity());
View rootView = inflater.inflate(R.layout.list_item_row, parent, false);
return new ShowHolder(rootView);
}
#Override
public void onBindViewHolder(ShowHolder holder, int position) {
Show currentShow = mShows.get(position);
holder.mTextView.setText(currentShow.getTitle());
Glide.with(getActivity()).load(currentShow.getImage()).into(holder.mImageView);
}
#Override
public int getItemCount() {
return mShows.size();
}
}
#Override
public Loader<List<Show>> onCreateLoader(int i, Bundle bundle) {
//start the loader with the appropriate uri
//for now it only supports movies+popular
//it will support movies+top, tv+popular, tv+top.
Uri baseUri = Uri.parse(BASE_URL);
Uri.Builder uriBuilder = baseUri.buildUpon();
uriBuilder.appendPath("movie");
uriBuilder.appendPath("popular");
uriBuilder.appendQueryParameter("api_key", QueryUtils.API_KEY);
uriBuilder.appendQueryParameter("page", Integer.valueOf(1).toString());
Log.v(LOG_TAG, "onCreateLoader#URL built: " + uriBuilder.toString());
return new ShowLoader(getActivity(), uriBuilder.toString());
}
#Override
public void onLoadFinished(Loader<List<Show>> loader, List<Show> shows) {
// Clear the adapter of previous earthquake data
clearAdapter();
// If there is a valid list of Shows, then add them to the adapter's
// data set. This will trigger the ListView to update.
if (shows != null && !shows.isEmpty()) {
mShowAdapter.addItemsToList(shows, false);
mShowAdapter.notifyDataSetChanged();
}
pb.setVisibility(View.GONE);
}
#Override
public void onLoaderReset(Loader<List<Show>> loader) {
// Loader reset, so we can clear out our existing data.
clearAdapter();
}
private void clearAdapter(){
List<Show> empty = new ArrayList<>();
mShowAdapter.addItemsToList(empty, false);
mShowAdapter.notifyDataSetChanged();
}
Thanks
You can use two lists, one with all the elements (original), and one with just queried elements (this one should use recyclerview adapter). When querying, just select from original list and add them to adapter list, then notify changes. Don't forget to clear adapter list before adding new entries.
Edit: you can try something like this on onQueryTextChange method. Adapt for your own wish.
if(s != null && !s.isEmpty()) {
for(String movie : originalList) {
if(movie.toLowerCase().contains(s.toLowerCase()){
adapter.add(movie);
}
notifyChanges();
}
}
} else { adapter.addAll(originalList); }
I have an autocomplete textview in my app that would let user enter address and the textview uses Places Api to show them different places that start with those letters the user is using. I implemented the Places Api and the user is able to see places but when they select a place I would like to retrieve that place and use it according to my needs(like retrieving the LatLng, and stuff like that) but the place object is String object and I don't know how to retrieve it as Place or convert the String object to Place object. I tried the following so far to no avail.
This is my adapter class.
class GooglePlacesAutocompleteAdapter extends ArrayAdapter implements Filterable {
private ArrayList resultList;
public GooglePlacesAutocompleteAdapter(Context context, int list, int textViewResourceId) {
super(context, list, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public String getItem(int index) {
return resultList.get(index).toString();
}
#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;
}
}
msg.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.search_results_list_item, R.id.tvSearchResultItem));
msg.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String selectedPlace = (String) parent.getItemAtPosition(position);
Place pl = new Place() {
#Override
public String getId() {
return null;
}
#Override
public List<Integer> getPlaceTypes() {
return null;
}
#Override
public CharSequence getAddress() {
return null;
}
#Override
public Locale getLocale() {
return null;
}
#Override
public CharSequence getName() {
return selectedPlace;
}
#Override
public LatLng getLatLng() {
return null;
}
#Override
public LatLngBounds getViewport() {
return null;
}
#Override
public Uri getWebsiteUri() {
return null;
}
#Override
public CharSequence getPhoneNumber() {
return null;
}
#Override
public float getRating() {
return 0;
}
#Override
public int getPriceLevel() {
return 0;
}
#Override
public Place freeze() {
return null;
}
#Override
public boolean isDataValid() {
return true;
}
};
LatLng selectedltlng = getSelectedLatLng(pl);
Log.e("selected", selectedltlng.toString());
//Place selectedPlace = Places.GeoDataApi.getPlaceById(mGoogleApiClient, );
//Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
private LatLng getSelectedLatLng(Place placeStringe) {
LatLng placeltlg = placeStringe.getLatLng();
Log.e("selcete", placeltlg.toString());
return placeltlg;
}
});
But this throws a null pointer exception.
I also tried to cast the string object as Object like this
Object selectedPlace = (Object) parent.getItemAtPosition(position);
Place plac = (Place)selectedPlace;
But this throws cast exception. How can I do that in an efficient way?
I made a city selector a week ago. It use custom extended AutoCompleteTextView widget. May be this helps you. This widget allows user to enter chars (grey color) and then show list of matched cities. User select a city from the list (it became black) and then selected city saved in cityData object and could be retrived by .getCity() call.
Here is the code:
public class CityAutoCompleteEditText extends AutoCompleteTextView implements View.OnFocusChangeListener, TextWatcherAdapter.TextWatcherListener {
// City object (code, name, type, level and so on)
private OKTMOUnit cityData;
// One of the constructors. You need to implement all with init() inside
public CityAutoCompleteEditText(Context context) {
super(context);
init(context, null);
}
// Initial data setter
public void setCity(OKTMOUnit city) {
setText(city.toString());
setTextColor(resource_black);
cityData = city;
}
// Data getter
public OKTMOUnit getCity() {
return cityData;
}
private void init(Context context, AttributeSet attrs) {
......
super.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// On click - set color black and init cityData
cityData = (OKTMOUnit) getAdapter().getItem(position);
setTextColor(resource_black);
}
});
.....
}
#Override
public void onTextChanged(EditText view, String text) {
// Text changed by hand - grey it and clear cityData
cityData = null;
setTextColor(resource_grey);
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (cityData == null) {
setText("");
}
}
}
And adapter:
public class CityAutoCompleteAdapter extends BaseAdapter implements Filterable {
private static final int MAX_RESULTS = 20;
private Context mContext;
private ArrayList<OKTMOUnit> mData;
public CityAutoCompleteAdapter(Context context) {
mData = new ArrayList<>();
mContext = context;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public OKTMOUnit getItem(int index) {
return mData.get(index);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.autocomplete_dropdown_item, parent, false);
}
if (convertView != null) {
((TextView) convertView.findViewById(R.id.autoCompleteCity)).setText(getItem(position).getFullCity());
((TextView) convertView.findViewById(R.id.autoCompleteRegion)).setText(getItem(position).getFullRegion());
}
return convertView;
}
}
ADD: I removed public Filter getFilter() {} code from adapter to simplify it.
try this It is done with Model Class u can get place name,address,lat,long I found very useful http://coderzpassion.com/android-working-google-places-api/
I have a adapter with this code:
public class LoadOrders_adapter extends BaseAdapter {
private JSONArray data;
private Context context;
public LoadOrders_adapter(JSONArray data, Context context) {
this.data = data;
this.context = context;
}
#Override
public int getCount() {
return data.length();
}
#Override
public Object getItem(int position) {
try {
return data.get(position);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.loading_orderlist, parent, false);
ImageView product_images=(ImageView) row.findViewById(R.id.product_images);
TextView Total_quantity = (TextView) row.findViewById(R.id.Total_quantity);
TextView order_status=(TextView) row.findViewById(R.id.order_status);
TextView order_date = (TextView) row.findViewById(R.id.order_date);
TextView order_id = (TextView) row.findViewById(R.id.order_id);
TextView product_Name=(TextView) row.findViewById(R.id.product_Name);
try {
JSONObject temp = data.getJSONObject(position);
Picasso.with(context).load(WebConnection.getInstance().resource_url(temp.getString("imgUrl"))).into(product_images);
Total_quantity.setText(temp.getString("Quantity"));
order_date.setText(temp.getString("Date_Sub"));
order_id.setText("#"+temp.getString("Order_ID"));
order_status.setText(temp.getString("Status"));
product_Name.setText(temp.getString("Name"));
} catch (JSONException e) {
e.printStackTrace();
}
return row;
}
}
And a class called:
public class LoadOrders extends ActionBarActivity implements Top_fragment.Top_fragmentListener {
private JSONArray data = null;
private JSONArray OrderDetails2 = null;
private ListView Normal_Orders_list;
private String previous_activity = "info.sliit.mystyle.Home";
private String title_name = "Your Normal Orders";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_promotional_wear);
Normal_Orders_list = (ListView)findViewById(R.id.Normal_Orders_list);
new BackgroundProcess().execute();
}
class BackgroundProcess extends AsyncTask<Void,Void,Void> {
ProgressDialog progressDialog = new ProgressDialog(LoadOrders.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Loading data...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
data = WebConnection.getInstance().get_request("Loading_order_rest/orderloading/user_id/12","json");
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
progressDialog.dismiss();
BaseAdapter baseAdapter1 = new LoadOrders_adapter(data,LoadOrders.this);
Normal_Orders_list.setAdapter(baseAdapter1);
//Normal_Orders_list.setOnItemClickListener();
}
}
#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_customized_orders,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public String get_previous_activity() {
return previous_activity;
}
#Override
public String getTitle_name() {
return title_name;
}
}
I have an activity called Activity_loading_orders which has a list view called Normal_Orders_list and i have another layout called loading_orderlist which has has a RelativeLayout with some Textviews and a button. As you can see in the code the layout loading_orderlist is loaded as an list item into the Normal_Orders_list activity. What i want to do is to remove list items when the button is clicked see image http://i.imgur.com/TYAqd0t.jpg
My Jason taken from postman
<?xml version="1.0" encoding="utf-8"?>
<xml><data><datum><Order_ID>8</Order_ID><Quantity>52</Quantity><Comment>fs</Comment><Date_Sub>2015-08-27</Date_Sub><Date_Del/><Product_ID/><Customer_ID>12</Customer_ID><Status>Accepted</Status><View>Unread</View><Name>T-shirt</Name><imgUrl>\assets\images\projectpics\normalt\Edited_front.jpg</imgUrl></datum><datum><Order_ID>10</Order_ID><Quantity>45</Quantity><Comment>sf</Comment><Date_Sub>2015-08-27</Date_Sub><Date_Del/><Product_ID/><Customer_ID>12</Customer_ID><Status>Accepted</Status><View>Unread</View><Name>T-shirt</Name><imgUrl>\assets\images\projectpics\normalt\Edited_front.jpg</imgUrl></datum></data></xml>
Consider moving the JSON parsing outside of getView(). What you're going to want to do is:
Have a (preferably) List of <ParsedJsonObject> (from parsing the JSON) instead of a JsonArray
On 'cancel' click: delete item at position from the List
After deleting the item from the list, notify your adapter that it's dataset has changed: mListViewAdapter.notifyDataSetChanged();
Please note: I'm afraid you're going to have to change to a custom ArrayAdapter instead of a BaseAdapter. The reason for this is that you are using a JSONArray as the data set for the adapter. It's not a good idea to start messing with the JSON yourself, but you're going to have to remove the item from the dataset one way or another. I recommend you take a look at libraries such as gson or Genson.
Those libraries can deserialize JSON into Java objects for you. So what'd you'd end up doing:
Fetch JSON data
Deserialize JSON data into Java objects, put these objects into a List<ParsedJsonObject>
Create a new ArrayAdapter<ParsedJsonObject>
Pass along the list of ParsedJsonObjects as the dataset for the ArrayAdapter you just created.
getView() won't have to change a lot, just change where the data comes from. getView() lets you know what position you are in, and considering you passed along a List<ParsedJsonObject>, you can just do list.get(position) to return an object containing all the data.
I hope this helped!
All right, so here's what you need to do:
Create new classes: DataModel.java, Data.java, and Datum.java
Put this in them:
DataModel.java:
public class DataModel {
private Data data;
public Data getData ()
{
return data;
}
public void setData (Data data)
{
this.data = data;
}
}
Data.java:
public class Data {
private Datum[] datum;
public Datum[] getDatum ()
{
return datum;
}
public void setDatum (Datum[] datum)
{
this.datum = datum;
}
}
Datum.java:
public class Datum{
private String Name;
private String View;
private String Status;
private String Quantity;
private String Date_Sub;
private String Comment;
private String Customer_ID;
private String Order_ID;
private String imgUrl;
public String getName ()
{
return Name;
}
public void setName (String Name)
{
this.Name = Name;
}
public String getView ()
{
return View;
}
public void setView (String View)
{
this.View = View;
}
public String getStatus ()
{
return Status;
}
public void setStatus (String Status)
{
this.Status = Status;
}
public String getQuantity ()
{
return Quantity;
}
public void setQuantity (String Quantity)
{
this.Quantity = Quantity;
}
public String getDate_Sub ()
{
return Date_Sub;
}
public void setDate_Sub (String Date_Sub)
{
this.Date_Sub = Date_Sub;
}
public String getComment ()
{
return Comment;
}
public void setComment (String Comment)
{
this.Comment = Comment;
}
public String getCustomer_ID ()
{
return Customer_ID;
}
public void setCustomer_ID (String Customer_ID)
{
this.Customer_ID = Customer_ID;
}
public String getOrder_ID ()
{
return Order_ID;
}
public void setOrder_ID (String Order_ID)
{
this.Order_ID = Order_ID;
}
public String getImgUrl ()
{
return imgUrl ;
}
public void setImgUrl (String imgUrl)
{
this.imgUrl = imgUrl;
}
}
And then in your class do Data d = genson.deserialize(jsonString, DataModel.class);
Inside DataModel is a Data instance and inside that is your array of datum's
I am looking for something like this:
several <ItemTemplate> in one ListView.
But it was in .ASP and above my level.
What I need
Class Vitals: vTime, BP, Heart Rate, Respirations per Minute, etc.
Class Medications: mTime, RxName, RxRoute, RxDose, RxDoseUnit, etc.
Class Procedures: pTime, Intubation, IV insertion, Defibrillation, etc.
Classes Vitals, Medications and Procedures to be based on user input that inject in to a ListView (sorted chronologically). A "Many-to-One" if I may.
I've went through hours of "CustomAdapter & ListView" tutorials, code samples, walkthroughs.
Here is my current code (trashed and scattered) to show that I am actively working towards a solution:
/*
* Created by SwaLayS on 2/19/2015.
*/
public class VitalAdapter extends BaseAdapter {
private ArrayList<VitalItem> vitalData;
private LayoutInflater layoutInflater;
public VitalAdapter(Context acontext, ArrayList<VitalItem> vitalData){
this.vitalData=vitalData;
layoutInflater=LayoutInflater.from(acontext);
}
#Override
public int getCount() {
return vitalData.size();
}
#Override
public Object getItem(int position) {
return vitalData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder;
if (convertView == null){
convertView = layoutInflater.inflate(R.layout.vital_view_children,null);
holder = new ViewHolder();
}
}
public class VitalView extends RelativeLayout {
private TextView vTimeTV;
// private TextView vPTATV;
private TextView vRateTV;
private TextView vOxySatTV;
private TextView vSysBPTV;
private TextView vDiaBPTV;
private TextView vRespRateTV;
private TextView vRespEffortTV;
//private TextView vMethodBPTV;
public static VitalView inflate(ViewGroup parent){
VitalView vitalView = (VitalView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.vital_view,parent,false);
return vitalView;
}
public VitalView(Context c){
this(c,null);
}
public VitalView(Context context, AttributeSet attrs){
this(context, attrs,0);
}
public VitalView(Context context, AttributeSet attrs, int defStyle){
super(context,attrs,defStyle);
LayoutInflater.from(context).inflate(R.layout.vital_view_children, this,true);
setupChildren();
}
private void setupChildren(){
vTimeTV = (TextView)findViewById(R.id.vTime);
// vPTATV = (TextView)findViewById(R.id.vPTA);
vRateTV = (TextView) findViewById(R.id.vBPM);
vOxySatTV = (TextView) findViewById(R.id.vOsat);
vSysBPTV = (TextView) findViewById(R.id.vSystolic);
vDiaBPTV = (TextView)findViewById(R.id.vDiastolic);
vRespRateTV = (TextView) findViewById(R.id.vRespRate);
vRespEffortTV = (TextView)findViewById(R.id.vRespEffort);
// vMethodBPTV = (TextView)findViewById(R.id.vMethodBP
}
public void setVital(VitalItem vital){
//vTimeTV.setText(vital.get);
}
}
public class VitalItem {
private String vTime;
// private String vPTA;
private String vRate;
private String vOxySat;
private String vSysBP;
private String vDiaBP;
private String vRespRate;
private String vRespEffort;
// private String vMethodBP;
public VitalItem(String Time, String Rate, String OxySat, String SysBP, String DiaBp, RespRate, String RespEffort){
super();
vTime=Time;
// vPTA=PTA;
vRate=Rate;
vOxySat = OxySat;
vSysBP = SysBP;
vDiaBP = DiaBP;
vRespRate = RespRate;
vRespEffort=RespEffort;
//vMethodBP=MethodBP;
}
public String getvTime() {
return vTime;
}
public void setvTime(String vTime) {
this.vTime = vTime;
}
// public String getvPTA() {
// return vPTA;
// }
// public void setvPTA(String vPTA) {
// this.vPTA = vPTA;
// }
public String getvRate() {
return vRate;
}
public void setvRate(String vRate) {
this.vRate = vRate;
}
public String getvOxySat() {
return vOxySat;
}
public void setvOxySat(String vOxySat) {
this.vOxySat = vOxySat;
}
public String getvSysBP() {
return vSysBP;
}
public void setvSysBP(String vSysBP) {
this.vSysBP = vSysBP;
}
public String getvDiaBP() {
return vDiaBP;
}
public void setvDiaBP(String vDiaBP) {
this.vDiaBP = vDiaBP;
}
public String getvRespRate() {
return vRespRate;
}
public void setvRespRate(String vRespRate) {
this.vRespRate = vRespRate;
}
public String getvRespEffort() {
return vRespEffort;
}
public void setvRespEffort(String vRespEffort) {
this.vRespEffort = vRespEffort;
}
// public String getvMethodBP() {
// return vMethodBP;
//}
// public void setvMethodBP(String vMethodBP) {
// this.vMethodBP = vMethodBP;
//
}
}
I'd appreciate any and everything;
I'm working on a NEMSIS . org project;
I may even be searching with the wrong search terms for what I need.
All help is appreciated
have you try the getViewTypeCount() method in adapter,
it can define different itemView for your different data types.
for your case you need to define three layout items .
search some demos,it may help you .