getView in base adapter is not working - android

I'm trying to create base adapter for Favorites.class so I can display items in it.
The getView method is not being called and the Activity won't show any view.
BaseAdapter:
public class fYtAdapter extends BaseAdapter {
private List<SearchResult> mfVideoList = null;
private LayoutInflater mfLayoutInflater = null;
private Favorites fActivity = null;
public fYtAdapter(Favorites iActivity){
fActivity = iActivity;
mfLayoutInflater = LayoutInflater.from(fActivity);
}
public void setmVideoList(List<SearchResult> mVideoList){
this.mfVideoList = mVideoList;
}
#Override
public int getCount() {
return (mfVideoList == null)? (0):(mfVideoList.size());
}
#Override
public Object getItem(int position) {
return (mfVideoList != null && mfVideoList.size()>position)? (mfVideoList.get(position)):(null);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder mHolder;
if(convertView != null){
mHolder = (ViewHolder)convertView.getTag();
}else{
mHolder = new ViewHolder();
convertView = mfLayoutInflater.inflate(R.layout.view_video_item,null);
mHolder.mVideoThumbnail = (ImageView)convertView.findViewById(R.id.video_thumbnail);
mHolder.mVideoTitle = (TextView)convertView.findViewById(R.id.video_title);
convertView.setTag(mHolder);
}
//Setting the data
final SearchResult result = mfVideoList.get(position);
mHolder.mVideoTitle.setText(result.getSnippet().getTitle());
//Loading the image
Picasso.with(fActivity).load(result.getSnippet().getThumbnails().getMedium().getUrl()).into(mHolder.mVideoThumbnail);
return convertView;
}
private class ViewHolder{
private TextView mVideoTitle = null;
private ImageView mVideoThumbnail = null;
}
}
Favorites.class
public class Favorites extends ActionBarActivity
implements View.OnClickListener, AdapterView.OnItemClickListener, ServerResponseListener{
private LayoutInflater mLayoutInflater = null;
private ProgressDialog mLoadingDialog = null;
private fYtAdapter mYtadapter = null;
String vidID = null, vidTitle = null, vidThumbnail = null;
ListView mFavLsv;
Bundle extras;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites_layout);
getSupportActionBar().setTitle("Favorites");
initializeViews();
extras = getIntent().getExtras();
this.vidID = extras.getString("id");
this.vidTitle = extras.getString("title");
this.vidThumbnail = extras.getString("thumbnail");
}
public void initializeViews(){
mLayoutInflater = LayoutInflater.from(this);
mFavLsv = (ListView)findViewById(R.id.yt_fav_lst);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
//Not needed in this Activity
#Override
public void onClick(View v) {
}
//To start video
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent videoIntent = YouTubeStandalonePlayer.createVideoIntent(this, AppConstants.KEY, vidID);
startActivity(videoIntent);
}
#Override
public void prepareRequest(Object... objects) {
//Parse the response based on type of request
Integer reqCode = (Integer) objects[0];
if(reqCode == null || reqCode == 0)
throw new NullPointerException("Request Code's value is Invalid.");
String dialogMsg = null;
switch(reqCode){
case SEARCH_VIDEO:
dialogMsg = SEARCH_VIDEO_MSG;
break;
}
if(mLoadingDialog != null && !mLoadingDialog.isShowing())
mLoadingDialog = ProgressDialog.show(this, DIALOG_TITLE, dialogMsg, true, true);
}
#Override
public void goBackground(Object... objects) {
}
#Override
public void completedRequest(Object... objects) {
//Dismiss the dialog
if(mLoadingDialog != null && mLoadingDialog.isShowing())
mLoadingDialog.dismiss();
//Parse the response based on type of request
Integer reqCode = (Integer) objects[0];
if(reqCode == null || reqCode == 0)
throw new NullPointerException("Request Code's value is Invalid.");
switch (reqCode){
case SEARCH_VIDEO:
if(mYtadapter == null){
mYtadapter = new fYtAdapter(this);
mYtadapter.setmVideoList((List<SearchResult>)objects[1]);
mFavLsv.setAdapter(mYtadapter);
}else{
mYtadapter.setmVideoList((List<SearchResult>) objects[1]);
mYtadapter.notifyDataSetChanged();
}
break;
}
}
}
I got another base adapter for another Activity and it is working fine.
I can't figure out why this is not working in here.
I need to display the view (with thumbnail(vidThumbnail) and title(vidTitle) in Favorites.class
*It seems that it won't got into "completedRequest" at all.

I faced this same issue. And I got the solution from here.. Link
Solution:
The only reasons getView() is not called are:
1) getCount() returns 0
2) You forget to call setListAdapter on the ListView.
3) If the ListView's visibility (or its container's visibility) is GONE.

Initialize your adapter and then set it to your ListView inside your initializeViews() method using mFavLsv.setAdapter(youradapter);

you have to add one more line -
mFavLsv.setAdapter(mYtadapter );
You missed set adapter in listview.

Related

Listview add item one at a time

I have a listview and a button in my main activity and three layout ressource files (right.xml, mid.xml and left.xml [They're relative layout]).
I want to make an arrayList (with strings and drawable (images)) and each time I push the button in main.xml the first content of the arrayList will appear at the bottom of the screen (either left, mid or right --> depend of the order of the arrayList) and when I click again the next item (string or drawable) will appear beneath it, pushing it in an upward motion.
UPDATE
I made a Model and an Adapter
Here is the model
public class ModelC1 {
public String C1Name;
public String C1Text;
public int id;
public boolean isSend;
public ModelC1(String C1Name, String C1Text, int id, boolean isSend){
this.id = id;
this.C1Name = C1Name;
this.C1Text = C1Text;
this.isSend = isSend;
}
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getC1Name() {
return C1Name;
}
public void setC1Name(String C1Name){
this.C1Name = C1Name;
}
public String getC1Text() {
return C1Text;
}
public void setC1Text (String C1Text){
this.C1Text = C1Text ;
}
public boolean isSend() {
return isSend;
}
public void setIsSend(boolean send){
isSend = send;
}
Here is the Adapter
public class AdapterC1 extends BaseAdapter {
private List<ModelC1> listChat;
private LayoutInflater inflater;
private Context context;
public AdapterC1(List<ModelC1> listChat, Context context){
this.listChat = listChat;
this.context = context;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listChat.size();
}
#Override
public Object getItem(int i) {
return listChat.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
View vi = convertView;
if(convertView == null ){
if(listChat.get(i).isSend() == 0)
vi=inflater.inflate(R.layout.list_send,null);
else if ((listChat.get(i).isSend() == 1))
vi=inflater.inflate(R.layout.list_recv,null);
else if ((listChat.get(i).isSend() == 2))
vi=inflater.inflate(R.layout.list_mid,null);
}else{
if(listChat.get(i).isSend() == 0)
vi=inflater.inflate(R.layout.list_send,null);
else if ((listChat.get(i).isSend() == 1))
vi=inflater.inflate(R.layout.list_recv,null);
else if ((listChat.get(i).isSend() == 2))
vi=inflater.inflate(R.layout.list_mid,null);
}
if(listChat.get(i).isSend() !=0 || listChat.get(i).isSend() !=1 || listChat.get(i).isSend() !=2 ){
BubbleTextView bubbleTextView = (BubbleTextView) vi.findViewById(R.id.bubbleChat);
if(bubbleTextView != null)
bubbleTextView.setText(listChat.get(i).C1Text);
TextView nameTextView = (TextView) vi.findViewById(R.id.nameChat);
if(nameTextView != null)
nameTextView.setText(listChat.get(i).C1Name);
}else{
vi=inflater.inflate(R.layout.list_mid,null);
BubbleTextView bubbleTextView = (BubbleTextView) vi.findViewById(R.id.bubbleChat);
bubbleTextView.setText("THE END");
}
return vi;
}
And here is the activity
public class Chat1 extends AppCompatActivity {
private static final String TAG = "Chat1";
private AdapterC1 adapter;
private List<ModelC1> listChat = new ArrayList<>();
private int count = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat1);
RecyclerView chatContent1 = findViewById(R.id.chatContent1);
}
private ModelC1 setUpMessage(){
Log.d(TAG, "setUpMessage: Exec");
return();
}
///OnClick of the button in the activity_chat1.xml
public void nextClicked1(View view) {
Log.d(TAG, "nextClicked: Is Clicked");
///After the limit of the arraylist is reached
final int limit = 40;
if(count == limit){
Log.d(TAG, "nextClicked: Limit Reached");
Intent i = new Intent(Chat1.this, MainActivity.class);
startActivity(i);
}else{
///Call the list
loadList(null);
}
}
///Load the list of arrays?
public void loadList(View view){
ModelC1 chat = setUpMessage();
listChat.add(chat);
///The ID of the recycleview in the activity_chat1.xml
final RecyclerView recyclerview = findViewById(R.id.chatContent1);
///The adapter
final AdapterC1 adapter = new AdapterC1(listChat, this);
///Make the recyclerview always scroll
///the adapter
///recyclerview.setAdapter(adapter);
}
My questions are now how do I make the ArrayList (containing strings and drawables) and how to link the ArrayList to make it appear one by one when I click on the button ?
As for the ArrayList, will soemthing like that works ?
private List<List<String>> textChat1 = new ArrayList<List<String>>();
ArrayList<String> textChat1 = new ArrayList<String>();
textChat1.add("This is message 1");
textChat1.add("This is message 2");
textChat1.add("This is message 2");
addresses.add(textChat1);
How can I add images and how to say which strings inflate which layout (left, mid or right) ?
You can do your job like this: in your Adapter's getView method ,
#Override
public View getView(int position, View convertView, ViewGroup container) {
if (convertView == null) {
if (position == 1) {
convertView = getLayoutInflater().inflate(R.layout.left, container, false);
} else if (position == 2) {
convertView = getLayoutInflater().inflate(R.layout.mid, container, false);
} else {
convertView = getLayoutInflater().inflate(R.layout.right, container, false);
}
}
//your code here
return convertView;
}
This will do your job, but, I suggest you to use Recyclerview because it's more efficient and better in terms of looks as well as memory management.

Android ListView glitching back to top for a few seconds before it works properly

I am trying to make an application with a ListView that include a Country Flag and name. This is so that the user can click on them and be shown images of the country that they wouldve taken before. However for about 3 seconds when the listview loads if i try to scroll it will sort of glitch and send me back to top. This is the code..
public class CountriesListAdapter extends ArrayAdapter {
private int resource;
private LayoutInflater inflater;
private List<CountryModel> countryModels;
private WeakReference<TextView> selectedCountryIdtxt;
private boolean useFilter;
private WeakReference<ProgressBar> progressBarWeakReference;
public int getSelectedCountryId() {
return selectedCountryId;
}
public void setSelectedCountryId(int selectedCountryId) {
this.selectedCountryId = selectedCountryId;
}
private int selectedCountryId;
public CountriesListAdapter(#NonNull WeakReference<Context> context, int resourceId, WeakReference<TextView> textView, #NonNull List<CountryModel> countryModelList, boolean useFilter, WeakReference<ProgressBar> progressBarWeakReference){
super(context.get(), resourceId, countryModelList);
selectedCountryIdtxt = textView;
resource = resourceId; //the id of the template file
inflater = LayoutInflater.from(context.get());
this.countryModels = countryModelList;
selectedCountryId = -1;
this.useFilter = useFilter;
this.progressBarWeakReference = progressBarWeakReference;
}
public int getCount() {
if (countryModels != null)
return countryModels.size();
return 0;
}
public CountryModel getItem(int position) {
if (countryModels != null)
return countryModels.get(position);
return null;
}
public long getItemId(int position) {
if (countryModels != null)
return countryModels.get(position).hashCode();
return 0;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
// this method is automatically called for every object in our list
//basically it's called for every single row before it is generated
// this method is called per row
convertView = (ConstraintLayout) inflater.inflate(resource, null);
//the variable countryModel is fiiled with current object that is being processed
final CountryModel countryModel = countryModels.get(position);
TextView countryName = convertView.findViewById(R.id.countryNamelbl);
final ImageView countryFlag = convertView.findViewById(R.id.countryFlagimg);
final ImageView checked = convertView.findViewById(R.id.countryCheckedimg);
//this is done for every object in the list
assert countryModel != null;
countryName.setText(countryModel.getName());
Picasso.get().load(countryModel.getImage()).fit().into(countryFlag);
if(!useFilter) {
if (selectedCountryId == countryModel.getId()) {
checked.setVisibility(View.VISIBLE);
} else {
checked.setVisibility(View.INVISIBLE);
}
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!useFilter) {
if (checked.getVisibility() == View.VISIBLE) {
checked.setVisibility(View.INVISIBLE);
selectedCountryId = -1;
selectedCountryIdtxt.get().setText(String.valueOf(selectedCountryId));
} else {
if (selectedCountryId == -1) {
checked.setVisibility(View.VISIBLE);
selectedCountryId = countryModel.getId();
} else {
selectedCountryId = countryModel.getId();
notifyDataSetChanged();
}
selectedCountryIdtxt.get().setText(String.valueOf(selectedCountryId));
}
} else {
Intent i = new Intent(getContext(), PicturesActivity.class);
i.putExtra("countryId",countryModel.getId());
i.putExtra("countryName", countryModel.getName());
getContext().startActivity(i);
}
}
});
progressBarWeakReference.get().setVisibility(View.INVISIBLE);
return convertView;
}
public List<CountryModel> getCountryModels() {
return countryModels;
}
public void setCountryModels(List<CountryModel> countryModels) {
this.countryModels = countryModels;
}
}
The problem was actually in another class, i was calling the adapter for every list item instead of just once... oops.
Thanks for the replies though!

Android:Receive Array of Objects and display in listView

Hello to all android folks over there!!
I want to get list of objects from web service and want to display them in list view.Now i am able to fetch those values and collected them in arraylist.But i am facing problem to display them in list view.below is my code.
Using everyones suggestion ,i solved my problem.Thats the spirit of android buddies.I am pasting my answer in UPDATED block.Hope it will be helpful in future.
UPDATED
public class TabFragment2 extends android.support.v4.app.Fragment {
ListView FacultyList;
View rootView;
LinearLayout courseEmptyLayout;
FacultyListAdapter facultyListAdapter;
String feedbackresult,programtype,programname;
Boolean FeedBackResponse;
String FacultiesList[];
public ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
SharedPreferences pref;
FacultyListAdapter adapter;
SessionSetting session;
public TabFragment2(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getActivity().getSharedPreferences("prefbook", getActivity().MODE_PRIVATE);
programtype = pref.getString("programtype", "NOTHINGpref");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_studenttab2, container, false);
session = new SessionSetting(getActivity());
new FacultySyncerBg().execute("");
courseEmptyLayout = (LinearLayout) rootView.findViewById(R.id.feedback_empty_layout);
FacultyList = (ListView) rootView.findViewById(R.id.feedback_list);
facultyListAdapter = new FacultyListAdapter(getActivity());
FacultyList.setEmptyView(rootView.findViewById(R.id.feedback_list));
FacultyList.setAdapter(facultyListAdapter);
return rootView;
}
public class FacultyListAdapter extends BaseAdapter {
private final Context context;
public FacultyListAdapter(Context context) {
this.context = context;
if (!facultylist.isEmpty())
courseEmptyLayout.setVisibility(LinearLayout.GONE);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder TabviewHolder;
if (convertView == null) {
TabviewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_feedback,
parent, false);
TabviewHolder.FacultyName = (TextView) convertView.findViewById(R.id.FacultyName);//facultyname
TabviewHolder.rating = (RatingBar) convertView.findViewById(R.id.rating);//rating starts
TabviewHolder.Submit = (Button) convertView.findViewById(R.id.btnSubmit);
// Save the holder with the view
convertView.setTag(TabviewHolder);
} else {
TabviewHolder = (ViewHolder) convertView.getTag();
}
final Faculty mFac = facultylist.get(position);//*****************************NOTICE
TabviewHolder.FacultyName.setText(mFac.getEmployeename());
// TabviewHolder.ModuleName.setText(mFac.getSubject());
TabviewHolder.rating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
feedbackresult =String.valueOf(rating);
}
});
return convertView;
}
#Override
public int getCount() {
return facultylist.size();
}
#Override
public Object getItem(int position) {return facultylist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
static class ViewHolder {
TextView FacultyName;
RatingBar rating;
Button Submit;
}
private class FacultySyncerBg extends AsyncTask<String, Integer, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(getActivity(), "Faculty Feedback!","Fetching Faculty List", true);
}
#Override
protected Void doInBackground(String... params) {
//CALLING WEBSERVICE
Faculty(programtype);
return null;
}
#Override
protected void onPostExecute(Void result) {
/*if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else
{
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
progressDialog.dismiss();*/
if (!facultylist.isEmpty()) {
// FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null)
{
if (FacultyList.getAdapter().getCount() == 0)
{
FacultyList.setAdapter(facultyListAdapter);
}
else
{
facultyListAdapter.notifyDataSetChanged();
}
}
else
{
FacultyList.setAdapter(facultyListAdapter);
}
}else
{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
// FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isResumed()) {
new FacultySyncerBg().execute("");
}
}//end*
//**************************WEBSERVICE CODE***********************************
public void Faculty(String programtype)
{
String URL ="http://detelearning.cloudapp.net/det_skill_webservice/service.php?wsdl";
String METHOD_NAMEFACULTY = "getUserInfo";
String NAMESPACEFAC="http://localhost", SOAPACTIONFAC="http://detelearning.cloudapp.net/det_skill_webservice/service.php/getUserInfo";
String faculty[]=new String[4];//changeit
String webprogramtype="flag";
String programname="DESHPANDE SUSANDHI ELECTRICIAN FELLOWSHIP";
// Create request
SoapObject request = new SoapObject(NAMESPACEFAC, METHOD_NAMEFACULTY);
request.addProperty("fellowshipname", programname);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
//my code Calling Soap Action
androidHttpTransport.call(SOAPACTIONFAC, envelope);
// ArrayList<Faculty> facultylist = new ArrayList<Faculty>();
java.util.Vector<SoapObject> rs = (java.util.Vector<SoapObject>) envelope.getResponse();
if (rs != null)
{
for (SoapObject cs : rs)
{
Faculty rp = new Faculty();
rp.setEmployeename(cs.getProperty(0).toString());//program name
rp.setEmployeeid(cs.getProperty(1).toString());//employee name
facultylist.add(rp);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
if (lstView.getAdapter() != null) {
if (lstView.getAdapter().getCount() == 0) {
lstView.setAdapter(finalAdapter);
} else {
finalAdapter.notifyDataSetChanged();
}
} else {
lstView.setAdapter(finalAdapter);
}
and setVisibiltity(View.VISIBLE)for listview
Put this code here
#Override
protected void onPostExecute(Void result) {
if (!facultylist.isEmpty()) {
FacultyList.setVisibiltity(View.VISIBLE) ;
courseEmptyLayout.setVisibility(LinearLayout.GONE);
if (FacultyList.getAdapter() != null) {
if (FacultyList.getAdapter().getCount() == 0) {
FacultyList.setAdapter(facultyListAdapter);
} else {
facultyListAdapter.notifyDataSetChanged();
}
} else {
FacultyList.setAdapter(facultyListAdapter);
}
}else{
courseEmptyLayout.setVisibility(LinearLayout.VISIBLE);
FacultyList.setVisibiltity(View.GONE) ;
}
progressDialog.dismiss();
}
you can try this:
this is the adapter class code.
public class CustomTaskHistory extends ArrayAdapter<String> {
private Activity context;
ArrayList<String> listTasks = new ArrayList<String>();
String fetchRefID;
StringBuilder responseOutput;
ProgressDialog progress;
String resultOutput;
public String getFetchRefID() {
return fetchRefID;
}
public void setFetchRefID(String fetchRefID) {
this.fetchRefID = fetchRefID;
}
public CustomTaskHistory(Activity context, ArrayList<String> listTasks) {
super(context, R.layout.content_main, listTasks);
this.context = context;
this.listTasks = listTasks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_task_history, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
LinearLayout linearLayout = (LinearLayout) listViewItem.findViewById(R.id.firstLayout);
//System.out.println("client_id" + _clientID);
//TextView textViewDesc = (TextView) listViewItem.findViewById(R.id.textViewDesc);
//ImageView image = (ImageView) listViewItem.findViewById(R.id.imageView);
if (position % 2 != 0) {
linearLayout.setBackgroundResource(R.color.sky_blue);
} else {
linearLayout.setBackgroundResource(R.color.white);
}
textViewName.setText(listTasks.get(position));
return listViewItem;
}
}
and now in the parent class you must have already added a list view in your xml file so now display code for it is below:
CustomTaskHistory customList = new CustomTaskHistory(TaskHistory.this, task_history_name);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(customList);
you can also perform any action on clicking cells of listview.If needed code for it is below add just below the above code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent nextScreen2 = new Intent(getApplicationContext(), SubscribeProgrammes.class);
nextScreen2.putExtra("CLIENT_ID", _clientID);
nextScreen2.putExtra("REFERENCE_ID", reference_IDs.get(i));
startActivity(nextScreen2);
Toast.makeText(getApplicationContext(), "You Clicked " + task_list.get(i), Toast.LENGTH_SHORT).show();
}
});

android listview with custom adapter multiselection issue

I want to make a listview item selected and the text "select" to be made to "selected", but when i click an item mutiple items get selected if I select an item at position 0 , items get selected at at a pattern, that is 0,7,14,21 and if i change the view to landscape: it will be 0 ,5,10,15, etc.
my main activity is:
public class two extends Activity implements OnQueryTextListener,OnItemClickListener {
GroupAdapter grpAdapter;
public static ArrayList<GroupsModel> arrayOfList;
public static ListView listView;
public static String base_url = "myurl";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.two);
arrayOfList = new ArrayList<GroupsModel>();
listView = (ListView) findViewById(R.id.group_listview);
listView.setOnItemClickListener(this);
listView.setTextFilterEnabled(true);
new ProgressTask(two.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
#SuppressWarnings("unused")
private two activity;
public ProgressTask(two two) {
this.activity = two;
context = two;
dialog = new ProgressDialog(context);
}
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
grpAdapter = new GroupAdapter(two.this, R.layout.two_row,arrayOfList);
listView.setAdapter(grpAdapter);
}
protected Boolean doInBackground(final String... args) {
//arrayOfList = new ArrayList<GroupsModel>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
//params.add(new BasicNameValuePair("",""));
JSONParser jp = new JSONParser();
JSONArray groups_obj = jp.makeHttpRequest(base_url + "groups/all", "GET", params);
for (int i = 0; i < groups_obj.length(); i++) {
GroupsModel group = new GroupsModel();
try {
JSONObject grp = groups_obj.getJSONObject(i);
group.setGroupId(grp.getInt("id"));
group.setGroupname(grp.getString("name"));
arrayOfList.add(group);
}
catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService( Context.SEARCH_SERVICE );
SearchView searchView = (SearchView) menu.findItem(R.id.menu_item_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setSubmitButtonEnabled(false);
searchView.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onQueryTextChange(String newText)
{
// this is your adapter that will be filtered
if (TextUtils.isEmpty(newText))
{
listView.clearTextFilter();
}
grpAdapter.getFilter().filter(newText.toString());
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
// TODO Auto-generated method stub
view.setBackgroundColor(Color.CYAN);
}}
My adapter is:
public class GroupAdapter extends ArrayAdapter<GroupsModel> implements Filterable{
private Context activity;
private ArrayList<GroupsModel> items ;
private List<GroupsModel> arrayList;
private ArrayFilter mFilter;
private int resource;
public GroupAdapter(Activity act, int resource, ArrayList<GroupsModel> arrayList) {
super(act, resource, arrayList);
this.activity = act;
this.resource = resource;
this.items = new ArrayList<GroupsModel>();
this.items.addAll(arrayList);
this.arrayList = new ArrayList<GroupsModel>();
this.arrayList.addAll(arrayList);
}
public View getView(final int position, View convertView,final ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = ((Activity) activity).getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(resource,parent, false);
holder = new ViewHolder();
holder.group_name = (TextView) convertView.findViewById(R.id.group_name);
holder.select = (TextView) convertView.findViewById(R.id.select);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try{
GroupsModel groups = items.get(position);
holder.group_name.setText(groups.getGroupName());
}catch(Exception e){
e.printStackTrace();
}
holder.select.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
holder.select.setText("my new text");
}
});
return convertView;
}
public class ViewHolder {
public TextView group_name,select;
}
#Override
public int getCount() {
// Total count includes list items and ads.
return items.size();
}
#Override
public GroupsModel getItem(int position)
{
// TODO Auto-generated method stub
return items.get(position);
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return position;
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ArrayFilter();
}
return mFilter;
}
private class ArrayFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (arrayList == null) {
synchronized (this) {
arrayList = new ArrayList<GroupsModel>(items);
}
}
if (prefix == null || prefix.length() == 0) {
ArrayList<GroupsModel> list;
synchronized (this) {
list = new ArrayList<GroupsModel>(arrayList);
}
results.values = list;
results.count = list.size();
} else {
String prefixString = prefix.toString().toLowerCase();
ArrayList<GroupsModel> values;
synchronized (this) {
values = new ArrayList<GroupsModel>(arrayList);
}
final int count = values.size();
final ArrayList<GroupsModel> newValues = new ArrayList<GroupsModel>();
for (int i = 0; i < count; i++) {
final String value = values.get(i).getGroupName();
final String valueText = value.toLowerCase();
// First match against the whole, non-splitted value
if (valueText.startsWith(prefixString)) {
newValues.add(values.get(i));
} else {
final String[] words = valueText.split(" ");
final int wordCount = words.length;
// Start at index 0, in case valueText starts with space(s)
for (int k = 0; k < wordCount; k++) {
if (words[k].startsWith(prefixString)) {
newValues.add(values.get(i));
break;
}
}
}
}
results.values = newValues;
results.count = newValues.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
items = (ArrayList<GroupsModel>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}}
I cant figure this out. Please help
You need to maintain the selected item in adapter and use it to change the text :
Adapter Code
private int selectedIndex;
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
LayoutInflater inflater = ((Activity) activity).getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(resource,parent, false);
holder = new ViewHolder();
holder.group_name = (TextView) convertView.findViewById(R.id.group_name);
holder.select = (TextView) convertView.findViewById(R.id.select);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(selectedIndex!= -1 && position == selectedIndex)
{
convert_view.setBackgroundColor(Color.CYAN);
holder.select.setText("selected");
}
else
{
convert_vie.wsetBackgroundColor(default_color);
holder.select.setText("Select");
}
//Your other code .....
return convertView ;
}
public void setSelectedIndex(position)
{
selectedIndex = position;
}
Now set the selectedIndex variable when a list item clicked.
public class MainActivity extends Activity implements OnItemClickListener
{
// Implemented onItemClickListener
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
adapter.setSelectedIndex(position);
}
}
You can add a member "checked" in GroupsModel, and initial it assign false;
In activity
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
final boolean isChecked = listView.getItem(position).isChecked();
listView.get(position).setChecked(!isChecked);
}
In getView() in adapter:
public View getView(...) {
...
if(getItem(position).isChecked()) {
// You must set root view in holder
holder.getBackground().setBackgroundColor(Color.CYAN);
}
...
}
Your problem is that Android is reusing your views, so when you scroll, the first view disappears and appears at the bottom with the same state.
What you need to do is everytime you check an item, you need to store de id/position of the item checked (maybe ArrayList<Integer>), this way everytime your getView method is getting called you will look at this class/structure you have created and see it the row needs to be checked or not.
Note: If the row is not checked you will have to call to myCheck->setChecked(false); in order to assure that the row is in a coherent state.
You must use a array or option object to record which position is selected.
And detect the array or option object in getView() in adapter.
So, your need move the code: "view.setBackgroundColor(Color.CYAN)" to getView() method.
You have been bitten by what they say "recycling" issues.
When re-using your views, this kind of problems happens.
There are several methods(for example saving checked positions in an arraylist, ...) to deal with it, but in my opinion the simplest and straight forward solution is using tags.
setTag() and getTag()
Here is a tutorial using it.
Hope it helps.

StaggeredGridView refresh correctly only top

I use https://github.com/bulletnoid/StaggeredGridView this library for make a pinterest style layout and use pulltorefresh on this layout. Also ı have a slide menu for choose different category and according to category which is user choose, refresh and refill the staggred again.
Pulltorefresh is work fine.
if user top of the layout and choose a category on slide menu it's work correctly. But if user bottom of the layout and choose a category on slide menu it's work not correctly .
the scenario, top of layout and select category on slidemenu and refill staggered layout. it's work correctly
the scenario, bottom of layout and select category on slidemenu and refill staggered layout. it's not work correctly
-->listviewAdapter
public void onItemClick(AdapterView<?> parent, View view, int position,
long arg3) {
// TODO Auto-generated method stub
switch (parent.getId()) {
case R.id.listView_sliding_menu:
smenu.toggle();
slidingMenuControl = true;
String categoryId = ((TextView) view.findViewById(R.id.categoryID))
.getText().toString();
parameters[0] = categoryId;
Toast.makeText(getApplicationContext(), categoryId,
Toast.LENGTH_LONG).show();
new PARSEJSONCATEGORYCONTENT().execute(parameters);
break;
default:
break;
}
}
-->parser
private class PARSEJSONCATEGORYCONTENT extends
AsyncTask<String[], Void, ArrayList<Utils>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
processDialoge();
}
protected ArrayList<Utils> doInBackground(String[]... params) {
String catId = params[0][0];
String startCount = params[0][5];
String count = params[0][6];
String urlCatContent = "http://212.58.8.109/webservice/api/content/cat/";
jArray = jsonParser.getJSONFromUrltoCategoryContent(urlCatContent,
Token, tokenValue, catId, startCount, count);
if (utilsArray == null) {
utilsArray = new ArrayList<Utils>();
} else if (slidingMenuControl == true) {
utilsArray.clear();
} else if (contentItemSelection != null) {
utilsArray.clear();
}
try {
// looping through All Contacts
for (int i = 0; i < jArray.length(); i++) {
JSONObject k = jArray.getJSONObject(i);
utils = new Utils();
// Storing each json item in variable
utils.imageUrl = k.getString("ipad_URL");
utils.imageWidth = k.getInt("ipad_width");
utils.imageHeight = k.getInt("ipad_height");
utils.categoryHeader = k.getString("contentHeader");
utils.contentDesc = k.getString("contentDesc");
utils.categoryContentId = k.getInt("id");
utils.contentTxt = k.getString("contentTxt");
Log.d("ipad_URL", utils.imageUrl);
utilsArray.add(utils);
}
String arrayLenght = Integer.toString(utilsArray.size());
Log.d("arrayLenght", arrayLenght);
} catch (JSONException e) {
e.printStackTrace();
}
return utilsArray;
}
protected void onPostExecute(ArrayList<Utils> utilsArray) {
staggeredAdapter.getMoreItemm(utilsArray);
// staggeredAdapter.setRefreshListener(false);
super.onPostExecute(utilsArray);
slidingMenuControl = false;
dialog.cancel();
}
}
-->BaseAdapter.java
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#SuppressLint("NewApi")
public class StaggeredAdapter extends BaseAdapter implements OnClickListener {
Typeface tf;
boolean refreshListener = false;
Utils utils;
private Context mContext;
private Application mAppContext;
private ArrayList<Utils> mUtilsArraylist = new ArrayList<Utils>();
public StaggeredAdapter(Context context, Application application) {
mContext = context;
mAppContext = application;
tf = Typeface.createFromAsset(mContext.getAssets(),
"font/Klavika-Medium.otf");
notifyDataSetChanged();
}
public void getMoreItemm(ArrayList<Utils> arrayList) {
mUtilsArraylist.clear();
mUtilsArraylist.addAll(arrayList);
this.notifyDataSetChanged();
}
public int getCount() {
return mUtilsArraylist == null ? 0 : mUtilsArraylist.size();
}
#Override
public Object getItem(int position) {
return mUtilsArraylist.get(position);
}
#Override
public long getItemId(int position) {
return mUtilsArraylist.indexOf(getItem(position));
}
#SuppressLint("NewApi")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
utils = mUtilsArraylist.get(position);
if (convertView == null) {
Holder holder = new Holder();
view = View.inflate(mContext, R.layout.staggered_item, null);
holder.imgUrl_content = (STGVImageView) view
.findViewById(R.id.imgUrl_content);
holder.tv_info = (TextView) view.findViewById(R.id.contentHeader);
holder.tv_info.setTypeface(tf);
holder.tv_info2 = (TextView) view.findViewById(R.id.contentDesc);
holder.tv_info2.setTypeface(tf);
view.setTag(holder);
} else {
return convertView;
}
final Holder holder = (Holder) view.getTag();
holder.imgUrl_content.mHeight = utils.imageHeight;
holder.imgUrl_content.mWidth = utils.imageWidth;
holder.imgUrl_content.setOnClickListener(this);
ImageLoader imgLoader = new ImageLoader(mAppContext);
imgLoader.DisplayImage(utils.imageUrl, holder.imgUrl_content);
holder.tv_info.setText(utils.categoryHeader);
holder.tv_info.setOnClickListener(this);
holder.tv_info2.setText(utils.contentDesc);
holder.tv_info2.setOnClickListener(this);
return view;
}
class Holder {
public STGVImageView imgUrl_content;
public TextView tv_info;
public TextView tv_info2;
}
public boolean isRefreshListener() {
return refreshListener;
}
public void setRefreshListener(boolean refreshListener) {
this.refreshListener = refreshListener;
}
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
switch (view.getId()) {
case R.id.imgUrl_content:
sendDataItemContentActivity();
break;
case R.id.contentHeader:
sendDataItemContentActivity();
break;
case R.id.contentDesc:
sendDataItemContentActivity();
break;
default:
break;
}
}
public void sendDataItemContentActivity() {
Intent intent = new Intent(mContext, ItemContent.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("contentTxt", utils.contentTxt);
intent.putExtra("contentHeader", utils.categoryHeader);
intent.putExtra("contentİmageUrl", utils.imageUrl);
intent.putExtra("contentCategoryName", utils.categoryName);
Bundle animBundle = ActivityOptions.makeCustomAnimation(mContext,
R.anim.anim, R.anim.anim2).toBundle();
mContext.startActivity(intent, animBundle);
}
}
I guess i had a same problem with using the same pinterest style library with you. i solve my problem by put this
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
mAdapter = new SearchSTGVAdapter(getActivity(), adsList, (Fragment)this);
ptrstgv.setAdapter(mAdapter);
}
which previously I put it in the onCreate method
For your information, I am implement this pinterest style in a view pager not a sliding menu

Categories

Resources