Android: ListView Contains All Values in One Line - android

I have problem with displaying values using ListView.
I created adapter extends Base Adapter and Setter & Getter for listview, however it stores
all values in one line.
This is displayed screen
I would like to display like this
This is my adapter class
public class DataShow_List_Adapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private ArrayList<TimeTable_ListItems> timeTable_listItems;
public DataShow_List_Adapter(Context context){
this.layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void SetTimeTable_listItems_adapter(ArrayList<TimeTable_ListItems> timeTable_listItems){
this.timeTable_listItems = timeTable_listItems;
}
#Override
public int getCount() {
return timeTable_listItems.size();
}
#Override
public Object getItem(int position) {
return timeTable_listItems.get(position);
}
#Override
public long getItemId(int position) {
return timeTable_listItems.get(position).getId();
}
#SuppressLint("ViewHolder")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = layoutInflater.inflate(R.layout.timetable_datashow_listview_row,parent,false);
((TextView)convertView.findViewById(R.id.Title_List)).setText(timeTable_listItems.get(position).getTitle());
((TextView)convertView.findViewById(R.id.SubTitle_List)).setText(timeTable_listItems.get(position).getSubTitle());
((TextView)convertView.findViewById(R.id.Start_Time_List)).setText(timeTable_listItems.get(position).getStart_Time());
((TextView)convertView.findViewById(R.id.End_Time_List)).setText(timeTable_listItems.get(position).getEnd_time());
return convertView;
}
}
This is Setter & Getter
public class TimeTable_ListItems {
private long id;
private String title;
private String subTitle;
private String start_Time;
private String end_time;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public String getStart_Time() {
return start_Time;
}
public void setStart_Time(String start_Time) {
this.start_Time = start_Time;
}
public String getEnd_time() {
return end_time;
}
public void setEnd_time(String end_time) {
this.end_time = end_time;
}
}
This is method that returns String from Database
public String getTitle_database_mon(){
sqLiteDatabase = this.getReadableDatabase();
String[] columns = new String[]{COLUMN_TITLE, COLUMN_MON,};
#SuppressLint("Recycle")
Cursor cursor =
sqLiteDatabase.query(TABLE_TIMETABLE,columns,COLUMN_MON + "=" + 1 ,null,null,null,null);
int iTitle = cursor.getColumnIndex(COLUMN_TITLE);
StringBuilder result = new StringBuilder();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
result.append(cursor.getString(iTitle)).
append("\n\n");
}
return result.toString();
}
This is My fragment
public class Monday_DataShow_Fragment extends Fragment {
private View root;
private ListView listView_mon;
private ArrayList<TimeTable_ListItems> timeTable_listItems_array;
private TimeTable_ListItems timeTable_listItems;
private DatabaseTimetable databaseTimetable;
private DataShow_List_Adapter dataShow_list_adapter;
public Monday_DataShow_Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_monday__data_show_, container, false);
findViews();
databaseTimetable = new DatabaseTimetable(getActivity());
timeTable_listItems = new TimeTable_ListItems();
dataShow_list_adapter = new DataShow_List_Adapter(requireActivity());
setListItems();
timeTable_listItems_array.add(timeTable_listItems);
dataShow_list_adapter.SetTimeTable_listItems_adapter(timeTable_listItems_array);
listView_mon.setAdapter(dataShow_list_adapter);
// Inflate the layout for this fragment
return root;
}
private void setListItems(){
timeTable_listItems_array = new ArrayList<>();
timeTable_listItems.setTitle(databaseTimetable.getTitle_database_mon());
dataShow_list_adapter.notifyDataSetChanged();
}
private void findViews(){
listView_mon = root.findViewById(R.id.listview_monday);
}
}
If you have any suggestions I'd like to hear it.

The issue is you have only one title as title String. getTitle_database_mon returns result.toString(). If you want to have multiple rows you need to have multiple objects in your list and unique titles for each. So instead of one TimeTable_ListItems. You need to be using ArrayList<TimeTable_ListItems> instead and have each entry contain a title so it is going to create multiple rows in the list instead of one.

Related

Insert and update Database to last shown activity

I have a simple problem (I think), that I cannot solve, even after much research. So for the first time I decided to post. I apologize if this is basic, or I cannot explain well. I'm a beginner.
I am devoloping a project, where I must connect to a database of movies, and get information through json.
At this point, I have my app running a list of playing now movies as other lists.
My goal (and problem) now is: When offline, show the last list displayed on the screen.
For that, I must somehow save that list to a database (I've never worked with db), and delete and update to a new one whenever i change screens on my app, so that the last list is displayed when online.
After that, I must show that last saved list (updated db).
Questions: where to code for insert (update) database?
How to convert that list into a db class? I think I must do that...
How to do the otherwise to insert that in a listview?
I use the same xml for that ListView? Since have the same params I think so...
So, here part of my code for this:
Fragment
public class NowPlayingMoviesFragment extends BaseFragment{
private ListView listMovies;
private Button buttonGetMore;
private List<Movie> movieList;
private int currentPage=1;
private MovieAdapter movieAdapter;
private ListView listOfflineMovies;
public static NowPlayingMoviesFragment newInstance() {
Bundle args = new Bundle();
NowPlayingMoviesFragment fragment = new NowPlayingMoviesFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.now_playing_movies_fragment, container, false);
findViews(v);
executeNowPlayingMoviesRequest();
addListeners();
return v;
}
private void executeNowPlayingMoviesRequest() {
new GetNowPlayingMoviesAsyncTask(getActivity(), String.valueOf(currentPage), getResources().getString(R.string.language)) {
#Override
protected void onResponseSuccess(MoviesResponse moviesResponse) {
DLog.d(tag, "onResponseSuccess " + moviesResponse);
// create the adapter
if (movieAdapter != null) {
List<Movie> movies = moviesResponse.getMovies();
for (int i = 0; i < movies.size(); i++) {
movieList.add(movies.get(i));
}
movieAdapter.notifyDataSetChanged();
**//is it here i save into db??**
} else {
movieList = moviesResponse.getMovies();
movieAdapter = new MovieAdapter(getActivity(), movieList);
listMovies.setAdapter(movieAdapter);
}
}
#Override
protected void onNetworkError () {
DLog.d(tag, "onNetworkError ");
// Here i now that some error occur when processing the request,
// possible my internet connection if turned off
//OfflineMovieDbEntity();
//MoviesItemDbEntity offlineMovies = new MoviesItemDbEntity(getActivity(),Movie.getOriginalTitle());
// MoviesItemDbEntity offlineMovies = offlineMovies.findById(offLineMovies.class,1)
}
}.execute();
}
private void findViews(View v) {
listMovies = (ListView) v.findViewById(R.id.now_playing_movies_list_view);
buttonGetMore = (Button) v.findViewById(R.id.get_more_button_movies_now);
listOfflineMovies = (ListView) v.findViewById(R.id.offline_movies_screen_list_view);
}
private void addListeners() {
buttonGetMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentPage=currentPage+1;
executeNowPlayingMoviesRequest();
}
});
}
}
---------------------------------------------------------------
# Movie Adapter #
public class MovieAdapter extends ArrayAdapter<Movie> {
public MovieAdapter(#NonNull Context context, #NonNull List<Movie> objects) {
super(context, 0, objects);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View v;
final ViewHolder holder;
final Movie item = getItem(position);
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
v = inflater.inflate(R.layout.movie_item, parent, false);
holder = new ViewHolder(v);
v.setTag(holder);
} else {
v = convertView;
holder = (ViewHolder) v.getTag();
}
holder.movieTitle.setText(item.getTitle());
//See movie details onclick
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), MovieDetailsScreen.class);
intent.putExtra("Movie", item);
getContext().startActivity(intent);
}
});
return v;
}
static class ViewHolder {
private TextView movieTitle;
public ViewHolder(View v) {
movieTitle = (TextView) v.findViewById(R.id.movie_item_title);
}
}
}
------------------------------------------------------------------------
#movie entitie#
public class Movie implements Parcelable {
#SerializedName("poster_path")
private String posterPath;
#SerializedName("overview")
private String overview;
#SerializedName("release_date")
private String releaseDate;
#SerializedName("original_title")
private String originalTitle;
#SerializedName("original_language")
private String originalLanguage;
#SerializedName("title")
private String title;
#SerializedName("backdrop_path")
private String backdropPath;
#SerializedName("popularity")
private Double popularity;
#SerializedName("vote_count")
private Integer voteCount;
#SerializedName("vote_average")
private Double voteAverage;
public String getPosterPath() {
return posterPath;
}
public String getOverview() {
return overview;
}
public String getReleaseDate() {
return releaseDate;
}
public String getOriginalTitle() {
return originalTitle;
}
public String getOriginalLanguage() {
return originalLanguage;
}
public String getTitle() {
return title;
}
public String getBackdropPath() {
return backdropPath;
}
public Double getPopularity() {
return popularity;
}
public Integer getVoteCount() {
return voteCount;
}
public Double getVoteAverage() {
return voteAverage;
}
public Movie() {
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.posterPath);
dest.writeString(this.overview);
dest.writeString(this.releaseDate);
dest.writeString(this.originalTitle);
dest.writeString(this.originalLanguage);
dest.writeString(this.title);
dest.writeString(this.backdropPath);
dest.writeValue(this.popularity);
dest.writeValue(this.voteCount);
dest.writeValue(this.voteAverage);
}
protected Movie(Parcel in) {
this.posterPath = in.readString();
this.overview = in.readString();
this.releaseDate = in.readString();
this.originalTitle = in.readString();
this.originalLanguage = in.readString();
this.title = in.readString();
this.backdropPath = in.readString();
this.popularity = (Double) in.readValue(Double.class.getClassLoader());
this.voteCount = (Integer) in.readValue(Integer.class.getClassLoader());
this.voteAverage = (Double) in.readValue(Double.class.getClassLoader());
}
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
#Override
public Movie createFromParcel(Parcel source) {
return new Movie(source);
}
#Override
public Movie[] newArray(int size) {
return new Movie[size];
}
};
}
-----------------------------------------------------------------
#movies response#
public class MoviesResponse {
#SerializedName("page")
private Integer page;
#SerializedName("results")
private List<Movie> movies = new ArrayList<>();
#SerializedName("total_pages")
private Integer totalPages;
public Integer getPage() {
return page;
}
public Integer getTotalPages() {
return totalPages;
}
public List<Movie> getMovies() {
return movies;
}
}
-----------------------------------------------------------
MovieAsyncTask
public abstract class GetNowPlayingMoviesAsyncTask extends ExecuteRequestAsyncTask<MoviesResponse> {
private static final String PATH = "/movie/now_playing";
private static final String LANGUAGE_KEY = "language";
private static final String PAGE_KEY = "page";
private String page;
private String language;
public GetNowPlayingMoviesAsyncTask(Context context, String page, String language) {
super(context);
this.page=page;
this.language=language;
}
#Override
protected String getPath() {
return PATH;
}
#Override
protected void addQueryParams(StringBuilder sb) {
addQueryParam(sb, LANGUAGE_KEY, language);
addQueryParam(sb, PAGE_KEY, page);
}
#Override
protected Class<MoviesResponse> getResponseEntityClass() {
return MoviesResponse.class;
}
}
-----------------------------------------
#Movie Database#
public class MoviesItemDbEntity extends SugarRecord {
public static final String TITLE_COLUMN_NAME = "movie_title_column";
private String title;
public MoviesItemDbEntity() {
}
public MoviesItemDbEntity(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public String setTitle() {
return title;
}
}
---------------------------------------------------------
#Movie Item 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"
android:gravity="center_horizontal">
<TextView
android:id="#+id/movie_item_title"
style="#style/ItemListStyle"
android:text="lalalala"/>
</LinearLayout>
---------------------------------------------------------------
#now playing ListView 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"
android:gravity="center">
<TextView
android:id="#+id/now_playing_movies_title"
style="#style/TitleStyle"
android:text="#string/movies"/>
<Button
android:id="#+id/get_more_button_movies_now"
style="#style/ButtonMoreStyle"/>
<ListView
android:id="#+id/now_playing_movies_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/now_playing_movies_title">
</ListView>
</RelativeLayout>

Cannot Parse JSON using retrofit and use listView

I am try to parse this Json array from this site NewsApi and display it in a listView.When I run the app nothing is displaying.Here is my code.What am doing wrong?.I have tried to debug the problem to no avail.
public class NewsApiClient {
public static String API_BASE_URL = "https://newsapi.org/v1/";
public static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
public static Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create()
);
public static Retrofit retrofit = builder.client(httpClient.build()).build();
NewsApiClient client = retrofit.create(NewsApiClient.class);
}
calling the endpoint?
public interface NewsApiInterface {
//endpoint
#GET("sources")
Call <SourcesResponse> getTechSources(
#Query("language") String language,
#Query("category") String category)
}
I am only using the name,description and category attributes.
public class Source {
#SerializedName("id")
public String id;
#SerializedName("name")
public String name;
#SerializedName("description")
public String description;
#SerializedName("url")
public String url;
#SerializedName("category")
public String category;
#SerializedName("language")
public String language;
#SerializedName("country")
public String country;
}
public class SourcesAdapter extends BaseAdapter {
Context context;
List<Source> sourceList;
public SourcesAdapter( Context context,List<Source> sourceList){
this.context = context;
this.sourceList = sourceList;
}
#Override
public int getCount() {
return sourceList.size();
}
#Override
public Object getItem(int position) {
return sourceList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView = layoutInflater.inflate(R.layout.sources_list,null);
Source currentsource = sourceList.get(position);
TextView sourcesName = (TextView) convertView.findViewById(R.id.sources_name);
TextView sourcesDescription = (TextView) convertView.findViewById(R.id.sources_description);
TextView sourcesCategory = (TextView) convertView.findViewById(R.id.sources_category);
sourcesName.setText(currentsource.name);
sourcesDescription.setText(currentsource.description);
sourcesCategory.setText(currentsource.category);
return convertView;
}
}
public class SourcesFragment extends Fragment {
ListView listView;
public SourcesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//
//instance of the adapter to this listview
View view = inflater.inflate(R.layout.fragment_sources, container, false);
listView = (ListView)view.findViewById(R.id.list_view_sources) ;
getSources();
return view;
}
public void getSources(){
Retrofit retrofit = NewsApiClient.builder.build();
NewsApiInterface newsApiInterface = retrofit.create(NewsApiInterface.class);
Call<SourcesResponse> sourcesCall = newsApiInterface.getTechSources("en", "technology");
sourcesCall.enqueue(new Callback<SourcesResponse>() {
#Override
public void onResponse(Call<SourcesResponse> call, Response<SourcesResponse> response) {
List<Source> sources = response.body().sources;
SourcesAdapter sourcesAdapter = new SourcesAdapter(getContext(),sources);
listView.setAdapter(sourcesAdapter);
}
#Override
public void onFailure(Call<SourcesResponse> call, Throwable t) {
}
});
}
}
public class SourcesResponse {
#SerializedName("status")
public String status;
#SerializedName("sources")
public List<Source> sources;
}
I have created 3 fragments,the sources fragment is one of them.On the sources fragment i only want to display sources with technology.
Thank you in advance!
In your retrofit's onResponse callback method, you are accessing sources list like response.body().sources. Instead of this in the SourcesResponse , add a getter and setter for sources like this
public List<SourcesResponse> getSources() {
return sources;
}
public void setSources(List<SourcesResponse> sources) {
this.sources = sources;
}
Now go to your onResponse callback of retrofit and change
response.body().sources
to
response.body().getSources()

One ListView Receiving Data from Multiple Class

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 .

Endless pagination listview Android with database

I need to implement an endless pagination listview in my code, I've searched online and I saw a lot of examples, but none of them is using database, my app does the following:
it connects to an API and retrieves the data with json and show it in a listview, ok that works fine, but I want that listview to have an infinite scroll, like the facebook one.
I don't want anyone to write the code for me, I'm asking to someone guide me on wich is the better way to achieve that, I'll share some of my code, so you can understand:
try {
//Repositorio is my database
Repositorio mRepositorio = new Repositorio(getActivity());
List listaDeClientes = mRepositorio.getClientes();
System.out.println(listaDeClientes);
TextView total = (TextView) rootView.findViewById(R.id.totalClientes);
total.setText(getTotalClientes(mRepositorio.getTotalRegistros("clientes")));
final ArrayAdapter ad = new ClienteViewAdapter(this.getActivity(), R.layout.fragment_cliente_item, listaDeClientes);
ListView lv = (ListView) rootView.findViewById(R.id.listaClientes);
lv.setVerticalFadingEdgeEnabled(true);
lv.setVerticalScrollBarEnabled(true);
lv.setAdapter(ad);
} catch (Exception e) {
e.printStackTrace();
}
return rootView;
}
ClienteViewAdapter:
public class ClienteViewAdapter extends ArrayAdapter<ClienteModel> {
private final LayoutInflater inflater;
private final int resourceId;
public ClienteViewAdapter(Context context, int resource, List<ClienteModel> objects) {
super(context, resource, objects);
this.inflater = LayoutInflater.from(context);
this.resourceId = resource;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ClienteModel mClienteModel = getItem(position);
view = inflater.inflate(resourceId, parent, false);
TextView tvId = (TextView) view.findViewById(R.id.clienteId);
TextView tvNome = (TextView) view.findViewById(R.id.clienteNome);
TextView tvTipo = (TextView) view.findViewById(R.id.clienteTipo);
tvId.setText(String.valueOf(mClienteModel.getClientes_id()));
tvNome.setText(mClienteModel.getNome());
tvTipo.setText(mClienteModel.getTipo());
return view;
}
}
Model:
public class ClienteModel implements Serializable {
private static final long serialVersionUID = 1L;
private Integer clientes_id;
private Integer id_rm;
private Integer credencial_id;
private String nome;
private String tipo;
private String informacao_adicional;
private String _criado;
private String _modificado;
private String _status;
public Integer getClientes_id() {
return clientes_id;
}
public void setClientes_id(Integer clientes_id) {
this.clientes_id = clientes_id;
}
public Integer getId_rm() {
return id_rm;
}
public void setId_rm(Integer id_rm) {
this.id_rm = id_rm;
}
public Integer getCredencial_id() {
return credencial_id;
}
public void setCredencial_id(Integer credencial_id) {
this.credencial_id = credencial_id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getInformacao_adicional() {
return informacao_adicional;
}
public void setInformacao_adicional(String informacao_adicional) {
this.informacao_adicional = informacao_adicional;
}
public String get_criado() {
return _criado;
}
public void set_criado(String _criado) {
this._criado = _criado;
}
public String get_modificado() {
return _modificado;
}
public void set_modificado(String _modificado) {
this._modificado = _modificado;
}
public String get_status() {
return _status;
}
public void set_status(String _status) {
this._status = _status;
}
public static String[] getColunas() {
return Colunas;
}
public static void setColunas(String[] colunas) {
Colunas = colunas;
}
public static String[] Colunas = new String[]{
Coluna.CLIENTES_ID,
Coluna.ID_RM,
Coluna.CREDENCIAL_ID,
Coluna.NOME,
Coluna.TIPO,
Coluna.INFORMACAO_ADICIONAL,
Coluna._CRIADO,
Coluna._MODIFICADO,
Coluna._STATUS
};

i want to sorting my listview by user Android

i have 2 classes to show some data in list view
but i want make option for users to sort this list view
this is adapter class
public class CustomListViewAdapter extends BaseAdapter {
private Activity activity;
private Book[] data;
private static LayoutInflater inflater=null;
public CustomListViewAdapter(Activity a, Book list[]) {
activity = a;
data=list;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getBookId(int position){
return data[position].getId();
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row, null);
TextView row_id =(TextView)vi.findViewById(R.id.row_id);
TextView name=(TextView)vi.findViewById(R.id.title);
TextView descp = (TextView) vi.findViewById(R.id.artist);
TextView note_type = (TextView) vi.findViewById(R.id.row_note_type);
ImageView image=(ImageView)vi.findViewById(R.id.image);
row_id.setText(String.valueOf(data[position].getId()));
name.setText(data[position].getTitle());
descp.setText(data[position].getContent());
//row_id.setText(data[position].getId());
note_type.setText(data[position].getType());
//image.setImageResource(R.drawable.subway);
if(data[position].getImage().toString().equals("Facebook")){
image.setImageResource(R.drawable.facebook);
}else if(data[position].getImage().toString().equals("skype")){
image.setImageResource(R.drawable.skype);
}else if(data[position].getImage().toString().equals("Subway")){
image.setImageResource(R.drawable.subway);
}else if(data[position].getImage().toString().equals("Book")){
image.setImageResource(R.drawable.book);
}
return vi;
}
}
and this is book class
public class Book {
private int id;
private String title;
private String content; // this is content of table
private String image; // choosing images
private String type; // type of table ( note or task)
private int archived; // Archive table (true or false)
private int check; // make overline when finish (true or false)
private int protect; // protect the table with password (true or false)
private String password; // password of table if it was protected
private String date_added;
public Book() {}
public Book(String title, String content, String image, String type, int archived,
int check, int protect, String password) {
this.title = title;
this.content = content;
this.image = image;
this.type = type;
this.archived = archived;
this.check = check;
this.protect = protect;
this.password = password;
}
// ---- setter
public void setId(int id){
this.id = id;
}
public void setTitle(String title){
this.title = title;
}
public void setContent(String content){
this.content = content;
}
public void setImage(String image){
this.image = image;
}
public void setType(String type){
this.type = type;
}
public void setArchived(int archived){
this.archived = archived;
}
public void setCheck(int check){
this.check = check;
}
public void setProtect(int protect){
this.protect = protect;
}
public void setPassword(String password){
this.password = password;
}
public void setDate_added(String date_added){
this.date_added = date_added;
}
// --- getter ---
public int getId(){
return id;
}
public String getTitle(){
return title;
}
public String getContent(){
return content;
}
public String getImage(){
return image;
}
public String getType(){
return type;
}
public int getArchived(){
return archived;
}
public int getCheck(){
return check;
}
public int getProtect(){
return protect;
}
public String getPassword(){
return password;
}
public String getDate_added() {
return date_added;
}
public String toString(){
return "Book >> id:"+id+" | title:"+title+" | author:";
}
}
and this is method for showing the data in list view but BookTable is class of connect and get data from sqlite
public void list_Books() {
BookTable bt = new BookTable(getActivity());
adapter = new CustomListViewAdapter(getActivity(), bt.getAllBooks());
list.setAdapter(adapter);
list.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View arg1,int pos, long id) {
selected = adapter.getBookId(pos);
row_type = (TextView) arg1.findViewById(R.id.row_note_type);
return false;
}
});
registerForContextMenu(list);
}
i want to know how can i sorting this data by objects of my Book class
please i want speed answer
One approach of sorting is for your object Book to implement Comparable interface:
public class Book implements Comparable<Book>{
private int id;
#Override
public int compareTo(Book another) {
if(this.id >= another.id)
return 1;
return -1;
}
}
If you want to sort after you query the data from database you can just call the Collections sort() method:
Collections.sort(list);
If you dont want to implement Comparable interface, you can just create a Comparator and call the following method of Collections:
Collections.sort(list, new Comparator<Book>() {
#Override
public int compare(Book lhs, Book rhs) {
if(lhs.id >= rhs.id)
return 1;
return -1;
}
});
To reverse the order (as frequently it is requiredfor sorting):
Collections.sort(list, Collections.reverseOrder());
After you sort the list dont forget to notify the adapter to refresh the view:
adapter.notifyDataSetChanged();

Categories

Resources