Custom Adapter not populating GridView - android

I have made a custom adapter to populate my gridView. What I am doing is that i am trying to populate the gridview with two different data(that too are custom) which are: Movies and FavouriteMovies. when the dridview is updated using Movies it updates just fine but when it FavouriteMovies it does not. I am storing FavouriteMovies in a sqlite db and then querying it to return a cursor.the data returns perfectly and there is no error. the main problem is with my MoviesAdapter. inside this when i add Movies to adapter it adds to the list inside MoviesAdapter and it works perfectly but when I add FavouriteMovies to the adapter it does not add it inside the favouriteList inside MoviesAdapter and its size is always zero.
please help!!
here is my MoviesAdapter:
package com.akshitjain.popularmovies;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class MoviesAdapter extends BaseAdapter {
private Context mContext;
List<Movies> list = new ArrayList<>();
List<FavouriteMovies> favouriteList = new ArrayList<>();
public MoviesAdapter(Context c) {
this.mContext = c;
}
#Override
public int getCount() {
if (list != null)
return list.size();
else
return favouriteList.size();
}
#Override
public Object getItem(int position) {
if (list != null)
return list.get(position);
else
return favouriteList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.grid_item_movies, parent, false);
}
ImageView moviePoster = (ImageView) convertView.findViewById(R.id.grid_item_movie_image);
if (list != null) {
Movies movies = list.get(position);
String posterPath = movies.posterPath;
final String POSTER_FINAL_URL = Constants.IMAGE_BASE_URL + Constants.POSTER_SIZE_LARGE + posterPath;
Picasso.with(mContext).load(POSTER_FINAL_URL.trim()).into(moviePoster);
} else {
FavouriteMovies favouriteMovies = favouriteList.get(position);
byte[] bb = favouriteMovies.posterImage;
moviePoster.setImageBitmap(BitmapFactory.decodeByteArray(bb, 0, bb.length));
}
return convertView;
}
public void add(Movies movies) {
list.add(movies);
}
public void offlineAdd(FavouriteMovies favouriteMovies) {
favouriteList.add(favouriteMovies);
}
public void clear() {
list.clear();
}
}
and here is where I am adding to the adapter:
#Override
protected void onPostExecute(Movies[] strings) {
if (strings != null) {
mMoviesAdapter.clear();
for (Movies moviesStr : strings) {
mMoviesAdapter.add(moviesStr);
}
}else if(mFavouriteMovies != null){
mMoviesAdapter.clear();
for(FavouriteMovies favouriteMoviesStr : mFavouriteMovies){
mMoviesAdapter.offlineAdd(favouriteMoviesStr);
}
}
Log.v("FetchMoviesTask","Count :" + mMoviesAdapter.getItem(0));
mMoviesAdapter.notifyDataSetChanged();
}
So sorry for my crude language.

You will always have count == 0 if you set your favorite movies.
List<Movies> list = new ArrayList<>();
#Override
public int getCount() {
if (list != null)
return list.size();
else
return favouriteList.size();
}
This will always return a count of 0 since list never is null. You favorite movies get ignored.
Solutions
Since you are only displaying either movies or favorites you should use 2 adapters. If you don't want to do this,
Use a boolean. Just set showFavorites to true, and display those. Or if you keep your null checks,
set the List<Movie> = null; when displaying favorited, then it will also work.

use following adapter:-
boolean[] CheckedItem_Adap;
ImageLoader imgload;
int headercount = 0, childCount;
LinkedList<HashMap<String, String>> allData;
LinkedList<HashMap<String, String>> temp_Header;
LinkedList<HashMap<String, String>> temp_child = new LinkedList<HashMap<String, String>>();
ArrayList<String> header;
ArrayList<String> childCount1;
private int[] mSectionIndices;
private String[] mSectionLetters;
private LayoutInflater inflater;
private Activity context;
public Adapter_UserTimeLine_StickyGrid(Activity context1, LinkedList<HashMap<String, String>> list, boolean[] checkedItems, ArrayList<String> childCountArray, ArrayList<String> headerarray, LinkedList<HashMap<String, String>> temp_Headers_LinkList) {
this.CheckedItem_Adap = checkedItems;
allData = list;
inflater = LayoutInflater.from(context1);
imgload = new ImageLoader(context1);
childCount1 = childCountArray;
header = headerarray;
temp_Header = temp_Headers_LinkList;
context = context1;
}
#Override
public int getCount() {
return allData.size();
}
#Override
public Object getItem(int position) {
return allData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder = new ViewHolder();
if (convertView == null) {
convertView = inflater.inflate(R.layout.sticky_listitems, parent, false);
}
holder.ivPostPic_Sticky = (ImageView) convertView.findViewById(R.id.ivPostPic_Sticky);
holder.ivSelectedToDelete_Sticky = (ImageView) convertView.findViewById(R.id.ivSelectedToDelete_Sticky);
holder.rlPostSticky_ManageSticky = (RelativeLayout) convertView.findViewById(R.id.rlPostSticky_ManageSticky);
if (CheckedItem_Adap[position] == true) {
holder.ivSelectedToDelete_Sticky.setVisibility(View.VISIBLE);
} else if (CheckedItem_Adap[position] == false) {
holder.ivSelectedToDelete_Sticky.setVisibility(View.GONE);
}
if (allData.get(position).get("media_type").equals("text")) {
holder.ivPostPic_Sticky.setImageResource(R.drawable.line_small);
} else {
imgload.DisplayImage(Constants.Imge_baseUrl + allData.get(position).get("video_thumb"),
holder.ivPostPic_Sticky);
}
holder.rlPostSticky_ManageSticky.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (UserTimeLine_Activity.isDeleteSelected) {
if (CheckedItem_Adap[position] == false) {
UserTimeLine_Activity.Selected_PostIds.add(allData.get(position).get("post_id"));
holder.ivSelectedToDelete_Sticky.setVisibility(View.VISIBLE);
CheckedItem_Adap[position] = true;
} else {
UserTimeLine_Activity.Selected_PostIds.remove(allData.get(position).get("post_id"));
holder.ivSelectedToDelete_Sticky.setVisibility(View.GONE);
CheckedItem_Adap[position] = false;
}
for (int i = 0; i < UserTimeLine_Activity.Selected_PostIds.size(); i++) {
Log.e("postid", i + "-" + UserTimeLine_Activity.Selected_PostIds.get(i) + "");
}
if (UserTimeLine_Activity.Selected_PostIds.get(0).equals(UserTimeLine_Activity.Selected_PostIds.get(0))) { }
} else {
String media_type = allData.get(position).get("media_type");
String post_id = allData.get(position).get("post_id");
Intent in = new Intent(context, PostDetails_UserOwn_TimeLIne_Activity.class);
in.putExtra("media_type", media_type);
in.putExtra("post_id", post_id);
in.putExtra("position", String.valueOf(position));
in.putExtra("post_User_Name", allData.get(position).get("post_User_Name"));
context.startActivity(in);
}
}
});
return convertView;
}
#Override
public int getCountForHeader(int i) {
int c = Integer.valueOf(childCount1.get(i));
return c;
}
#Override
public int getNumHeaders() {
return temp_Header.size();
}
#Override
public View getHeaderView(int position, View convertView, ViewGroup parent) {
HeaderViewHolder holder = new HeaderViewHolder();
if (convertView == null) {
convertView = inflater.inflate(R.layout.headersticky_managepost, parent, false);
}
temp_Header.get(position).get("post_datetime");
TextView tvDate_Sticky = (TextView) convertView.findViewById(R.id.tvDate_Sticky);
for (int i = 0; i < temp_Header.size(); i++) {
}
String Date = temp_Header.get(position).get("post_datetime");
String FormatedDate = parseDateToddMMyyyy(Date);
tvDate_Sticky.setText(FormatedDate);
return convertView;
}
public String parseDateToddMMyyyy(String time) {
String inputPattern = "yyyy-MM-dd";
String outputPattern = "MMM-dd-yyyy";
SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
Date date = null;
String str = null;
try {
date = inputFormat.parse(time);
str = outputFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return str;
}
class HeaderViewHolder {
TextView tvDate_Sticky;
}
class ViewHolder {
ImageView ivPostPic_Sticky, ivSelectedToDelete_Sticky;
RelativeLayout rlPostSticky_ManageSticky;
}
}

Related

How to get the ID of an image from a string array

I created a custom adapter for my GridView that will display an image of a book (View image) and its name (View text);
, I declared the list of names of the books in the string file:
[strings.xml]
<string-array name="bookLabels">
<item>android security</item>
<item>penetration_testing</item>
<item>red_team</item>
<item>Linux Firewalls</item>
<item>the_art_of_exploitation</item>
<item>web_application_hacker</item>
<item>Linux Basicsfor Hackers</item>
<item>Black Hat Python</item>
</string-array>
So I want to do the same thing with the images,instead of declaring them in the code like that :
private Integer[] bookImages =
{
R.drawable.android_security,
R.drawable.penetration_testing,
R.drawable.red_team,
R.drawable.lf,
R.drawable.the_art_of_exploitation,
R.drawable.web_application_hacker,
R.drawable.lbh,
R.drawable.bhp
};
I declared the names of the images in a string array named "bookImages",
<string-array name="bookImages">
<item>#drawable/android_security</item>
<item>#drawable/penetration_testing</item>
<item>#drawable/red_team</item>
<item>#drawable/lf</item>
<item>#drawable/the_art_of_exploitation</item>
<item>#drawable/web_application_hacker </item>
<item>#drawable/lbh </item>
<item>#drawable/bhp </item>
</string-array>
and then I recovered the location of all the images declared in to "bookimagesfromstring"array :
Resources resi = context.getResources();
bookImagesFromString = resi.getStringArray(R.array.bookImages);
System.out.println("bookImages Images test 1: " +
Arrays.toString(bookImagesFromString))
this is the source code of [main activity]
public class main extends AppCompatActivity {
String[] labels;
String[ ] pages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Resources res = getResources();
labels = res.getStringArray(R.array.bookLabels);
pages = res.getStringArray(R.array.web_pages);
GridView gridView = findViewById(R.id.gridView1);
BookGrid myAdapter = new BookGrid(getApplicationContext(), labels);
gridView.setAdapter(myAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(
getApplicationContext(),
((TextView) v.findViewById(R.id.gridtextView))
.getText(), Toast.LENGTH_SHORT).show();
// Intent webPageIntent = new Intent(getApplicationContext(),
DisplayWebPage.class);
// webPageIntent.putExtra("WEB_PAGE", pages[ position ] );
// startActivity( webPageIntent );
}
});
}
}
And the [ BookGrid Class ]
public class BookGrid extends BaseAdapter {
private Context context;
private LayoutInflater inflater;
private String[] imageName;
private String[] bookImagesFromString;
private Integer[] bookImages =
{
R.drawable.android_security,
R.drawable.penetration_testing,
R.drawable.red_team,
R.drawable.lf,
R.drawable.the_art_of_exploitation,
R.drawable.web_application_hacker,
R.drawable.lbh,
R.drawable.bhp
};
public BookGrid(Context context, String[] imageName) {
this.context = context;
this.imageName = imageName;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return bookImages.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
/*
Resources rest = context.getResources();
String[] labels = rest.getStringArray(R.array.bookLabels);
System.out.println("bookImagess Tex: " + Arrays.toString(labels));
*/
Resources resi = context.getResources();
bookImagesFromString = resi.getStringArray(R.array.bookImages);
System.out.println("bookImages Images test 1: " + Arrays.toString(bookImagesFromString));
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_grid_image, parent, false);
TextView txtv = convertView.findViewById(R.id.gridtextView);
ImageView imgv = convertView.findViewById(R.id.gridImageView);
//To Avoid ArrayIndexOutOfBoundsException
//boolean inBounds = (position >= 0) && (position <= imageName.length);
txtv.setText(imageName[position]);
//imgv.setImageResource(bookImagesFromString[position]);
imgv.setImageResource(bookImages[position]);
} else {
}
return convertView;
}
the result for the "bookImagesFromString" array was as follows :
([res/drawable-v24/android_security.png, res/drawable-v24/penetration_testing.png, res/drawable-v24/red_team.png, res/drawable/lf.jpg, res/drawable-v24/the_art_of_exploitation.png, res/drawable-v24/web_application_hacker.png, res/drawable/lbh.png, res/drawable-v24/bhp.png])
So the question is how to convert the "bookImagesFromString" array to an array that contains the ID of each image ? -And after using it in this code part:
imgv.setImageResource(bookImagesID[position]);
Thanks.
Try string array like this:
<string-array name="bookImages">
<item>android_security</item>
<item>penetration_testing</item>
<item>red_team</item>
<item>lf</item>
<item>the_art_of_exploitation</item>
<item>web_application_hacker</item>
<item>lbh</item>
<item>bhp</item>
</string-array>
and adapter like this:
public class BookGrid extends BaseAdapter {
private Context context;
private LayoutInflater inflater;
private String[] imageName;
private Integer[] bookImages;
public BookGrid(Context context, String[] imageName) {
this.context = context;
this.imageName = imageName;
this.inflater = LayoutInflater.from(context);
Resources resi = context.getResources();
String[] bookImagesFromString = resi.getStringArray(R.array.bookImages);
bookImages = new Integer[bookImagesFromString.length];
for (int i = 0; i < bookImagesFromString.length; i++) {
bookImages[i] = (resi.getIdentifier(bookImagesFromString[i], "drawable", context.getPackageName()));
}
}
#Override
public int getCount() {
return imageName.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
/*
Resources rest = context.getResources();
String[] labels = rest.getStringArray(R.array.bookLabels);
System.out.println("bookImagess Tex: " + Arrays.toString(labels));
*/
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_grid_image, parent, false);
}
TextView txtv = convertView.findViewById(R.id.gridtextView);
ImageView imgv = convertView.findViewById(R.id.gridImageView);
txtv.setText(imageName[position]);
imgv.setImageResource(bookImages[position]);
return convertView;
}
}
Hope that helps!
for the name of the images as I_A_Mok said I took just:
<string-array name="bookImages">
<item>android_security</item>
<item>penetration_testing</item>
<item>red_team</item>
<item>lf</item>
<item>the_art_of_exploitation</item>
<item>web_application_hacker </item>
<item>lbh </item>
<item>bhp </item>
</string-array>
So I had two solutions :
A method with Context:
public static Integer[] getIds(Context context, String[] str) {
Integer[] bookID = new Integer[str.length];
for (int i = 0; i < str.length; i++) {
bookID[i] = context.getResources().getIdentifier(str[i], "drawable", context.getPackageName());
}
return bookID;
}
Or without Context (this approach is faster than the first Retrieving Resources in Android) :
public static Integer[] getIds(String[] str) {
Integer[] bookID = new Integer[str.length];
try {
for (int i = 0; i < str.length; i++) {
Class res = R.drawable.class;
Field field = res.getField(str[i]);
int drawableId = field.getInt(null);
bookID[i] = drawableId;
}
} catch (Exception e) {
Log.e("MyTag", "Failure to get drawable id.", e);
e.printStackTrace();
}
return bookID;
}
and here is the complete code
package com.example.gridview.BookGridWebView;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.gridview.R;
import java.lang.reflect.Field;
import java.util.Arrays;
public class BookGrid extends BaseAdapter {
private Context context;
private LayoutInflater inflater;
private String[] imageName;
private String[] bookImagesFromStringArray;
private Integer[] bookImages =
{
R.drawable.android_security,
R.drawable.penetration_testing,
R.drawable.red_team,
R.drawable.lf,
R.drawable.the_art_of_exploitation,
R.drawable.web_application_hacker,
R.drawable.lbh,
R.drawable.bhp
};
public BookGrid(Context context, String[] imageName) {
this.context = context;
this.imageName = imageName;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return bookImages.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
bookImagesFromStringArray =
context.getResources().getStringArray(R.array.bookImageName);
//the table contains the IDs of each Image
Integer[] bookIDs = getIds(context,bookImagesFromStringArray);
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_grid_image, parent, false);
TextView txtv = convertView.findViewById(R.id.gridtextView);
ImageView imgv = convertView.findViewById(R.id.gridImageView);
txtv.setText(imageName[position]);
// imgv.setImageResource(bookImages[position]);
imgv.setImageResource(bookIDs[position]);
} else {
}
return convertView;
}
public static Integer[] getIds(Context context, String[] str) {
Integer[] bookID = new Integer[str.length];
for (int i = 0; i < str.length; i++) {
bookID[i] = context.getResources().getIdentifier(str[i], "drawable", context.getPackageName());
}
return bookID;
}
public static Integer[] getIds(String[] str) {
Integer[] bookID = new Integer[str.length];
try {
for (int i = 0; i < str.length; i++) {
Class res = R.drawable.class;
Field field = res.getField(str[i]);
int drawableId = field.getInt(null);
bookID[i] = drawableId;
}
} catch (Exception e) {
Log.e("MyTag", "Failure to get drawable id.", e);
e.printStackTrace();
}
return bookID;
}
}
Thanks.

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;
}
}

Custom Adapter not Changing Layout According to Condition

I am working on a chat app and I am very new to using ListViews and ArrayAdapters, as well as Custom Adapters. I am having a problem that causes all my items in my list to be of one layout, even they are supposed to change according to a booleans(true would be an outgoing chat bubble, and false would be an incoming chat bubble).
Here is my code for the retreival of the chat(It isn't the whole file, just a snippet):
Variable declarations:
final ArrayList<chatBubble> objects = new ArrayList<>();
final CustomAdapter customAdapter = new CustomAdapter(this, objects);
listView.setAdapter(customAdapter);
Code to get messages and add to list:
mDatabase.child("chat").child("publicDump").child("dumpedMessages").child("message" + i).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String message = dataSnapshot.getValue(String.class);
if (message != null) {
final String extract = message.substring(message.lastIndexOf("<") + 1, message.indexOf(">"));
mDatabase.child("users").child("c").child("emailToUsername").child(mAuth.getCurrentUser().getEmail().replace(".", ",")).child("username").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String username = dataSnapshot.getValue(String.class);
if (username != null) {
if (username.equals(extract)) {
Log.i("Extract", extract);
int semicnt = 0;
int num = 0;
//Log.i("Loop", "Yes");
for (int i = 0; i < message.length(); i++) {
//Log.i("Loop", "y");
if (String.valueOf(message.charAt(i)).equals(":")) {
semicnt++;
//Log.i("cnt", String.valueOf(semicnt));
if (semicnt == 3) {
num = i;
i = message.length() - 1;
String time = message.substring(0, (Math.min(message.length(), num)));
String finalM = message.replace(time + ": ", "").replace("<" + extract + "> ", "");
chatBubble chat = new chatBubble(finalM, "From: " + extract + " At: " + time, true);
objects.add(chat);
}
}
}
} else {
int semicnt = 0;
int num = 0;
// Log.i("Loop", "Yes");
for (int i = 0; i < message.length(); i++) {
//Log.i("Loop", "y");
if (String.valueOf(message.charAt(i)).equals(":")) {
semicnt++;
//Log.i("cnt", String.valueOf(semicnt));
if (semicnt == 3) {
num = i;
i = message.length() - 1;
String time = message.substring(0, (Math.min(message.length(), num)));
String finalM = message.replace(time + ": ", "").replace("<" + extract + "> ", "");
chatBubble chat = new chatBubble(finalM, "From: " + extract + " At: " + time, false);
objects.add(chat);
}
}
}
}
customAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here is my code for my chatBubble:
package com.tejasmehta.codeychat;
public class chatBubble {
private String msg;
private String date;
private boolean myMessage;
public chatBubble(String msg, String date, boolean myMessage) {
this.msg = msg;
this.date = date;
this.myMessage = myMessage;
}
public String Msg() {
return msg;
}
public String Date() {
return date;
}
public boolean myMessage() {
return myMessage;
}
}
And here is my code for my customAdapter(which shows that if the boolean, myMessage, is true, it will load a different layout, and a different one for false):
public class CustomAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<chatBubble> objects;
private class ViewHolder {
TextView msg;
TextView date;
}
public CustomAdapter(Context context, ArrayList<chatBubble> objects) {
inflater = LayoutInflater.from(context);
this.objects = objects;
}
public int getCount() {
return objects.size();
}
public chatBubble getItem(int position) {
return objects.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int layoutResource; // determined by view type
chatBubble ChatBubble = getItem(position);
if (ChatBubble.myMessage()) {
layoutResource = R.layout.right_bubble;
} else {
layoutResource = R.layout.left_bubble;
}
if(convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(layoutResource, null);
holder.msg = convertView.findViewById(R.id.txt_msg);
holder.date = convertView.findViewById(R.id.date);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.msg.setText(objects.get(position).Msg());
holder.date.setText(objects.get(position).Date());
return convertView;
}
}
Thank You for all of your help!
the problem is your getview
The view is being recycled so convertview already has a layout. so its not being reinflated to the correct layout.
you need to use getViewType() and getViewTypeCount() to tell the listview you want to use different layouts
http://android.amberfog.com/?p=296
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return getItem(position).myMessage()?0:1;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int layoutResource; // determined by view type
chatBubble ChatBubble = getItem(position);
if (ChatBubble.myMessage()) {
layoutResource = R.layout.right_bubble;
} else {
layoutResource = R.layout.left_bubble;
}
if(convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(layoutResource, null);
holder.msg = convertView.findViewById(R.id.txt_msg);
holder.date = convertView.findViewById(R.id.date);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.msg.setText(objects.get(position).Msg());
holder.date.setText(objects.get(position).Date());
return convertView;
}

ListView with different layouts with two different objects

I want to populate a ListView with different layouts for odd and even rows. It should look like this:
I use two objects "OddListItem" and "EvenListItem" to store/access the data. I do not know how to pass both objects to my custom listview adapter and get the correct view.
My object classes:
public class OddListItem {
private String time_start;
private String time_end;
private String location;
public OddListItem(String time_start, String time_end, String location) {
super();
this.time_start = time_start;
this.time_end = time_end;
this.location = location;
}
// getters and setters
void setTimeStart(String time_start) {
this.time_start = time_start;
}
void setTimeEnd(String time_end) {
this.time_end = time_end;
}
void setLocation(String location) {
this.location = location;
}
public String getTimeStart() {
return time_start;
}
public String getTimeEnd() {
return time_end;
}
public String getLocation() {
return location;
}
}
public class EvenListItem {
private String image;
private String location;
public EvenListItem (String image, String location) {
super();
this.image = image;
this.location = location;
}
// getters and setters
void setImage(String image) {
this.image = image;
}
void setLocation(String location) {
this.location = location;
}
public String getImage() {
return image;
}
public String getLocation() {
return location;
}
}
MyCustomAdapter:
public class MyCustomAdapter extends BaseAdapter {
// Tag for Logging
private static final String TAG = "MyCustomAdapter";
int type;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private ArrayList<OddListItem> mData = new ArrayList<OddListItem>();
private LayoutInflater mInflater;
//private TreeSet mSeparatorsSet = new TreeSet();
private Context context;
public MyCustomAdapter(Context context) {
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
}
public void addItem(final OddListItem item) {
mData.add(item);
//The notification is not necessary since the items are not added dynamically
//notifyDataSetChanged();
}
public void addSeparatorItem(final OddListItem item) {
mData.add(item);
//The notification is not necessary since the items are not added dynamically
//notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
/*if ((position%2) == 0){
type = TYPE_ITEM;
} else {
type = TYPE_SEPARATOR;
}
return type;*/
return position%2;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public OddListItem getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
Log.d(TAG, "getView " + position + " " + convertView + " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
//inflate the new layout
convertView = mInflater.inflate(R.layout.detail_list_row_odd, parent, false);
holder.tv_time_from = (TextView) convertView.findViewById(R.id.tv_time_from);
holder.tv_time_to = (TextView) convertView.findViewById(R.id.tv_time_to);
holder.tv_current_location_odd = (TextView) convertView.findViewById(R.id.tv_current_location_odd);
//fill the layout with values
/*holder.tv_time_from.setText("12:34");
holder.tv_time_to.setText("12:37");
holder.tv_current_location_odd.setText("Aktueller Standort");*/
holder.tv_time_from.setText(mData.get(position).getTimeStart());
holder.tv_time_to.setText(mData.get(position).getTimeEnd());
holder.tv_current_location_odd.setText(mData.get(position).getLocation());
break;
case TYPE_SEPARATOR:
//inflate the new layout
convertView = mInflater.inflate(R.layout.detail_list_row_even, parent, false);
holder.tv_current_location_even = (TextView) convertView.findViewById(R.id.tv_current_location_even);
holder.img_transport = (ImageView) convertView.findViewById(R.id.img_transport);
//fill the layout with values
holder.tv_current_location_even.setText("Hauptbahnhof");
holder.img_transport.setImageDrawable(context.getResources().getDrawable(R.drawable.rollator));
break;
default:
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
private static class ViewHolder {
public TextView tv_time_from;
public TextView tv_time_to;
public TextView tv_current_location_odd;
public TextView tv_current_location_even;
public ImageView img_transport;
}
}
Here I generate the data and call the adapter:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_connection);
generateData();
//fill ListView with custom content from MyCustomAdapter class
mAdapter = new MyCustomAdapter(getApplicationContext());
for (int i = 1; i < odd_items.size(); i++) {
mAdapter.addItem(odd_items.get(i));
if (i % 1 == 0) {
mAdapter.addSeparatorItem(odd_items.get(i));
}
}
setListAdapter(mAdapter);
//set duration text
tv_duration = (TextView)findViewById(R.id.tv_duration);
tv_duration.setText("Dauer: 22 Minuten");
}
private void generateData() {
odd_items = new ArrayList<OddListItem>();
odd_items.add(new OddListItem("12:34", "", "Aktueller Standort"));
odd_items.add(new OddListItem("12:37", "12:37", "TUM"));
odd_items.add(new OddListItem("12:42", "12:42", "Hauptbahnhof Nord"));
odd_items.add(new OddListItem("12:48", "12:48", "Hauptbahnhof"));
even_items = new ArrayList<EvenListItem>();
even_items.add(new EvenListItem("R.drawable.rollator", "3 Minuten Fußweg"));
even_items.add(new EvenListItem("R.drawable.bus", "Richtung Hauptbahnhof Nord"));
even_items.add(new EvenListItem("R.drawable.rollator", "6 Minuten Fußweg"));
mData = new Data(odd_items, even_items);
}
Any help would be great. Maybe there is also a better approach then please let me know.
I would create a Single list of Items
public class Items {
private String time_start;
private String time_end;
private String location;
private int image;
private String locationeven;
private int oddoreven;
public String getTime_start() {
return time_start;
}
public void setTime_start(String time_start) {
this.time_start = time_start;
}
public String getTime_end() {
return time_end;
}
public void setTime_end(String time_end) {
this.time_end = time_end;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getLocationeven() {
return locationeven;
}
public void setLocationeven(String locationeven) {
this.locationeven = locationeven;
}
public int getOddoreven() {
return oddoreven;
}
public void setOddoreven(int oddoreven) {
this.oddoreven = oddoreven;
}
}
In onCreate of Activity call
generateData() ;
Then
ArrayList<Items> oddorevenlist = new ArrayList<Items>();
private void generateData() {
Items item1 = new Items();
item1.setTime_start("12:34");
item1.setTime_end("");
item1.setLocation("Aktueller Standort");
item1.setOddoreven(0);
oddorevenlist.add(item1);
Items item2 = new Items();
item2.setImage(R.drawable.ic_launcher);
item2.setLocationeven("3 Minuten Fußweg");
item2.setOddoreven(1);
oddorevenlist.add(item2);
Items item3 = new Items();
item3.setTime_start("12:37");
item3.setTime_end("12:37");
item3.setLocation("Tum");
item3.setOddoreven(0);
oddorevenlist.add(item3);
Items item4 = new Items();
item4.setImage(R.drawable.ic_launcher);
item4.setLocationeven("Richtung Hauptbahnhof Nord");
item4.setOddoreven(1);
oddorevenlist.add(item4);
Items item5 = new Items();
item5.setTime_start("12:42");
item5.setTime_end("12:42");
item5.setLocation("Hauptbahnhof Nord");
item5.setOddoreven(0);
oddorevenlist.add(item5);
Items item6 = new Items();
item6.setImage(R.drawable.ic_launcher);
item6.setLocationeven("R6 Minuten Fußweg");
item6.setOddoreven(1);
oddorevenlist.add(item6);
Items item7 = new Items();
item7.setTime_start("12:48");
item7.setTime_end("12:48");
item7.setLocation("HHauptbahnhof");
item7.setOddoreven(0);
oddorevenlist.add(item7);
MyCustomAdapter mAdapter = new MyCustomAdapter(this,oddorevenlist);
setListAdapter(mAdapter);
}
Adapter code
public class MyCustomAdapter extends BaseAdapter {
// Tag for Logging
private static final String TAG = "MyCustomAdapter";
int type;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private ArrayList<Items> oddorevenlist ;
private LayoutInflater mInflater;
private Context context;
public MyCustomAdapter(Context context, ArrayList<Items> oddorevenlist) {
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
this.oddorevenlist = oddorevenlist;
}
#Override
public int getItemViewType(int position) {
if (oddorevenlist.get(position).getOddoreven()==0){
type = TYPE_ITEM;
} else if (oddorevenlist.get(position).getOddoreven()==1) {
type = TYPE_SEPARATOR;
}
return type;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return oddorevenlist.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
Log.d(TAG, "getView " + position + " " + convertView + " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
//inflate the new layout
convertView = mInflater.inflate(R.layout.row_odd, parent, false);
holder.tv_time_from = (TextView) convertView.findViewById(R.id.tv_time_from);
holder.tv_time_to = (TextView) convertView.findViewById(R.id.tv_time_to);
holder.tv_current_location_odd = (TextView) convertView.findViewById(R.id.tv_current_location_odd);
holder.tv_time_from.setText(oddorevenlist.get(position).getTime_start());
holder.tv_time_to.setText(oddorevenlist.get(position).getTime_end());
holder.tv_current_location_odd.setText(oddorevenlist.get(position).getLocation());
break;
case TYPE_SEPARATOR:
//inflate the new layout
convertView = mInflater.inflate(R.layout.row_even, parent, false);
holder.tv_current_location_even = (TextView) convertView.findViewById(R.id.tv_current_location_even);
holder.img_transport = (ImageView) convertView.findViewById(R.id.img_transport);
//fill the layout with values
holder.tv_current_location_even.setText(oddorevenlist.get(position).getLocationeven());
holder.img_transport.setImageResource(R.drawable.ic_launcher);
break;
default:
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
private static class ViewHolder {
public TextView tv_time_from;
public TextView tv_time_to;
public TextView tv_current_location_odd;
public TextView tv_current_location_even;
public ImageView img_transport;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
}
Snap

How to add data to custom BaseAdapter for listView - Android

I have a custom BaseAdapter class that creates views for comments, usernames, and numbers. This BaseAdapter receives this information from An AsyncTask. The AsyncTask runs when the user reaches the bottom of the listView. The problem is the BaseAdapter wont add new data. When I try to add new data it deletes the current data in the list and then adds the new data. I want it to keep all the data and just add data to the bottom of the listView. All of these classes are in the same Activity. Here is my current code.
class CreateCommentLists extends BaseAdapter{
Context ctx_invitation;
String[] listComments;
String[] listNumbers;
String[] listUsernames;
public CreateCommentLists(String[] comments, String[] usernames, String[] numbers, DashboardActivity context)
{
super();
ctx_invitation = context;
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
#Override
public int getCount() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
public void add(String[] comments, String[] usernames,
String[] numbers) {
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
public int getCount1() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
public Object getItem1(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
public long getItemId1(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView1(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
final CreateCommentLists mycmlist = new CreateCommentLists(comments, usernames, numbers, DashboardActivity.this);
lstComments = (ListView)findViewById(android.R.id.list);
lstComments.setAdapter(mycmlist);
final ProgressDialog progDailog = new ProgressDialog(DashboardActivity.this);
class loadComments extends AsyncTask<JSONObject, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progDailog.setIndeterminate(false);
progDailog.setCancelable(true);
progDailog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
progDailog.show();
progDailog.setContentView(R.layout.progress_circle);
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
protected JSONObject doInBackground(JSONObject... params) {
JSONObject json2 = CollectComments.collectComments(usernameforcomments, offsetNumber);
return json2;
}
#Override
protected void onPostExecute(JSONObject json2) {
try {
if (json2.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res2 = json2.getString(KEY_SUCCESS);
if(Integer.parseInt(res2) == 1){
JSONArray commentArray = json2.getJSONArray(KEY_COMMENT);
String comments[] = new String[commentArray.length()];
for ( int i=0; i<commentArray.length(); i++ ) {
comments[i] = commentArray.getString(i);
}
JSONArray numberArray = json2.getJSONArray(KEY_NUMBER);
String numbers[] = new String[numberArray.length()];
for ( int i=0; i<numberArray.length(); i++ ) {
numbers[i] = numberArray.getString(i);
}
JSONArray usernameArray = json2.getJSONArray(KEY_USERNAME);
String usernames[] = new String[usernameArray.length()];
for ( int i=0; i<usernameArray.length(); i++ ) {
usernames[i] = usernameArray.getString(i);
}
mycmlist.add(comments,usernames,numbers);
mycmlist.notifyDataSetChanged();
}//end if key is == 1
else{
// Error in registration
registerErrorMsg.setText(json2.getString(KEY_ERROR_MSG));
}//end else
}//end if
} //end try
catch (JSONException e) {
e.printStackTrace();
}//end catch
progDailog.dismiss();
}
}
mainListView = (ListView) findViewById(android.R.id.list);
class EndlessScrollListener implements OnScrollListener {
private int i = 0;
private int visibleThreshold = 5;
private int previousTotal = 0;
private boolean loading = true;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
new loadComments().execute();
mainListView.smoothScrollToPosition(0);
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
mainListView.setOnScrollListener(new EndlessScrollListener());
You try this :
public class Comment {
String username;
String content;
String number;
}
Class Adapter:
public class CommentAdapter extends BaseAdapter {
private List<Comment> listComment;
private Context context;
public CommentAdapter(List<Comment> listComment, Context context) {
super();
this.listComment = listComment;
this.context = context;
}
#Override
public int getCount() {
return listComment.size();
}
#Override
public Comment getItem(int position) {
return listComment.get(position);
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = mInflater.inflate(R.layout.comment_item, null);
}
final TextView textViewUsername = (TextView) v
.findViewById(R.id.comment_Username);
final TextView textViewNumber = (TextView) v
.findViewById(R.id.comment_number);
final TextView textViewContent = (TextView) v
.findViewById(R.id.comment_Content);
final String username = listComment.get(position).getUsername();
final String number= listComment.get(position).getNumber();
String content = listComment.get(position).getContent();
textViewUsername.setText(username);
textViewNumber.setText(number);
textViewContent.setText(content);
return v;
}
}
When you need to add new comment to list. just create new Comment and add to listComment(listComment.add(newComment)), after that, call adapter.notifyDataSetChanged();
package com.example.baseadapter;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity implements OnItemClickListener {
public static final String[] title = new String[] {
"image 1", "image 2", "image 3", "image 4"
};
public static final Integer[] images = {
R.drawable.aa, R.drawable.bb, R.drawable.cc, R.drawable.cc, R.drawable.dd
};
ListView listview;
List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < title.length; i++) {
RowItem item = new RowItem(images[i], title[i]);
rowItems.add(item);
}
listview = (ListView)findViewById(R.id.listview);
customBaseAdapter cba = new customBaseAdapter(this, rowItems);
listview.setAdapter(cba);
listview.setOnItemClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "item selected", Toast.LENGTH_LONG).show();
}
public class customBaseAdapter extends BaseAdapter {
Context context;
List<RowItem> rowItem;
public customBaseAdapter(Context context, List<RowItem> listItem) {
this.context = context;
rowItem = listItem;
Log.d("const", "const");
}
#Override
public int getCount() {
Log.d("count", "count");
return rowItem.size();
}
#Override
public Object getItem(int arg0) {
Log.d("item", "item");
return rowItem.get(arg0);
}
#Override
public long getItemId(int position) {
Log.d("const", "item id");
return rowItem.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("const", "getview");
LayoutInflater inflater = (LayoutInflater)context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
RowItem rowitem = (RowItem)getItem(position);
TextView textForTitle;
ImageView imgForImage;
convertView = inflater.inflate(R.layout.inflate, null);
textForTitle = (TextView)convertView.findViewById(R.id.textview);
imgForImage = (ImageView)convertView.findViewById(R.id.imageview);
textForTitle.setText(rowitem.getTitle());
imgForImage.setImageResource(rowitem.getImageId());
return convertView;
}
}
public class RowItem {
int imageId;
String title;
public RowItem(int imageId, String title) {
this.imageId = imageId;
this.title = title;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getTitle() {
return title;
}
public void setStringTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return title;
}
}
}

Categories

Resources