Custom BaseAdapter doesn't call getView after resume app - android

i'm having some problems with a custom BaseAdapter which is showed in a PullToRefreshListView (whitch is an extension from ListView that you can update by pulling the list).
My problem is that when I minimize and later I resume my app, the ListView is not showing nothing... I had a breakpoint at my last line of code and my method getCount from my adapter return always more than zero, but getView still not being called...
Adapter:
package extrasoftware.triptreat.Adapters;
/**
* Creado pormsolla on 7/01/14.
*/
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Point;
import android.view.Display;
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 java.util.GregorianCalendar;
import extrasoftware.triptreat.Clases.ImageLoader;
import extrasoftware.triptreat.Clases.ImageViewEscalable;
import extrasoftware.triptreat.Clases.Ofertas.Oferta;
import extrasoftware.triptreat.Clases.Ofertas.OfertasLlenar_R;
import extrasoftware.triptreat.Comun.Constantes;
import extrasoftware.triptreat.Comun.Datos;
import extrasoftware.triptreat.Comun.General;
import extrasoftware.triptreat.OfertasActivity;
import extrasoftware.triptreat.OfertasDetalleActivity;
import extrasoftware.triptreat.R;
public class OfertasAdapter extends BaseAdapter {
private Activity activity;
private OfertasLlenar_R oRespuesta;
private OfertasLlenar_R oRespuestaTotal;
private static LayoutInflater inflater = null;
private ImageLoader imageLoader;
public static boolean abrirVentana = true;
//public static boolean okComentario = true;
public OfertasAdapter(Activity a, OfertasLlenar_R d, OfertasLlenar_R d_total) {
activity = a;
oRespuesta = d;
oRespuestaTotal = d_total;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Display display = activity.getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
imageLoader = new ImageLoader(activity.getApplicationContext(), R.drawable.sinimagen, Constantes.ImageLoaderTipo.Lista);
}
public int getCount() {
return oRespuesta.datos.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vista = convertView;
try{
vista = inflater.inflate(R.layout.ofertas_row, parent, false);
final Oferta oferta = oRespuesta.datos.get(position);
final TextView txtTitulo = (TextView)vista.findViewById(R.id.txtTitulo);
final TextView txtNegocio = (TextView)vista.findViewById(R.id.txtNegocio);
final ImageViewEscalable imgOferta = (ImageViewEscalable)vista.findViewById(R.id.imgOferta);
final ImageView imgEstado = (ImageView)vista.findViewById(R.id.imgEstado);
imgOferta.setImageBitmap(null);
String urlImagen = General.ObtenerRutaImagen(Constantes.Ventanas_Origen.Ofertas, oRespuesta.oferta_raiz + "/" + oferta.oferta_imagen, activity);
imageLoader.DisplayImage(urlImagen, imgOferta);
txtNegocio.setText(oferta.negocio_nombre);
txtTitulo.setText(oferta.titulo);
GregorianCalendar calendar = new GregorianCalendar();
final boolean caducada = calendar.getTime().after(oferta.valido_hasta_F);
if(caducada){
imgEstado.setImageResource(R.drawable.caducada);
}
else if(oferta.estado == Constantes.Ofertas_Estados.Aceptada){
imgEstado.setImageResource(R.drawable.aceptada);
}
else if(oferta.estado == Constantes.Ofertas_Estados.Usada){
imgEstado.setImageResource(R.drawable.usada);
}
else{
imgEstado.setVisibility(View.GONE);
}
vista.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
final CharSequence[]
options = {
activity.getResources().getString(R.string.borrar),
activity.getResources().getString(R.string.excluir),
activity.getResources().getString(R.string.cancelar)
};
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals(activity.getResources().getString(R.string.borrar))) {
OfertasActivity.ConfirmarBorrar(v, oferta.oferta_id);
}
else if (options[item].equals(activity.getResources().getString(R.string.excluir))) {
OfertasActivity.ConfirmarExcluir(v, oferta.negocio_id, oferta.negocio_nombre);
}
else if (options[item].equals(activity.getResources().getString(R.string.cancelar))) {
dialog.dismiss();
}
}
});
builder.show();
return true;
}
});
// Click event for single list row
vista.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
if(abrirVentana && !caducada){
abrirVentana = false;
General.MostrarCargando(activity);
Datos.setCodigosFiltrados(activity.getApplicationContext(), oRespuesta);
Intent detalleIntent = new Intent(activity.getApplicationContext(), OfertasDetalleActivity.class);
detalleIntent.putExtra(Constantes.Parametros_Extra.Indice, String.valueOf(General.ObtenerIndiceOfertaEnLista(oRespuesta.datos, oferta.oferta_id)));
activity.startActivity(detalleIntent);
}
}
catch (Exception e){
e.printStackTrace();
}
}
});
}
catch(Exception e){
e.printStackTrace();
}
return vista;
}
public void setDatos(OfertasLlenar_R oRespuestaFiltro){
oRespuesta = oRespuestaFiltro;
this.notifyDataSetChanged();
}
}
Thanks!

I had just find an error in the activity that uses this adapter... But i don't understand this, and i'm not sure that it was the betters solution...
This method was the problem:
private static void CargarListasOfertas(OfertasLlenar_R oRespuesta){
try{
OfertasLlenar_R oRespuestFiltradas = (OfertasLlenar_R) oRespuesta.clone();
if(m_listaNavegaciones != null && m_listaNavegaciones.size() != 0){
final short paisID = m_listaNavegaciones.get(m_indice_actual).pais_id;
final short ciudadID = m_listaNavegaciones.get(m_indice_actual).ciudad_id;
Predicate<Oferta> ofertasPredicate = new Predicate<Oferta>() {
public boolean apply(Oferta oferta) {
return oferta.pais_id == paisID && oferta.ciudad_id == ciudadID;
}
};
Collection<Oferta> ofertas = General.Filtrar(oRespuestFiltradas.datos, ofertasPredicate);
oRespuestFiltradas.datos = new ArrayList<Oferta>(ofertas);
if(adapterOfertas == null){
adapterOfertas = new OfertasAdapter(activity, oRespuestFiltradas, oRespuesta);
lstOfertas.setAdapter(adapterOfertas);
}
else{
adapterOfertas.setDatos(oRespuestFiltradas);
}
}
else{
oRespuestFiltradas.datos = new ArrayList<Oferta>();
if(adapterOfertas == null){
adapterOfertas = new OfertasAdapter(activity, oRespuestFiltradas, oRespuesta);
lstOfertas.setAdapter(adapterOfertas);
}
else{
adapterOfertas.setDatos(oRespuestFiltradas);
}
oRespuestFiltradas.datos = new ArrayList<Oferta>();
}
final long ONE_MINUTE_IN_MILLIS = 60000;//millisecs
long t = Calendar.getInstance().getTime().getTime();
Date afterAddingTenMins = new Date(t + (10 * ONE_MINUTE_IN_MILLIS));
if(Datos.ventana_origen != Constantes.Ventanas_Origen.OfertasDetalle
|| (OfertasDetalleActivity.getFechaCarga() != null
&& !OfertasDetalleActivity.getFechaCarga().before(afterAddingTenMins))){
m_posicionOfertas = lstOfertas.getRefreshableView().getFirstVisiblePosition();
}
if(m_posicionOfertas != -1){
lstOfertas.getRefreshableView().setSelection(m_posicionOfertas);
}
General.OcultarCargando();
}
catch (Exception e){
e.printStackTrace();
General.OcultarCargando();
}
}
The code that now is working fine is:
private static void CargarListasOfertas(OfertasLlenar_R oRespuesta){
try{
OfertasLlenar_R oRespuestFiltradas = (OfertasLlenar_R) oRespuesta.clone();
if(m_listaNavegaciones != null && m_listaNavegaciones.size() != 0){
final short paisID = m_listaNavegaciones.get(m_indice_actual).pais_id;
final short ciudadID = m_listaNavegaciones.get(m_indice_actual).ciudad_id;
Predicate<Oferta> ofertasPredicate = new Predicate<Oferta>() {
public boolean apply(Oferta oferta) {
return oferta.pais_id == paisID && oferta.ciudad_id == ciudadID;
}
};
Collection<Oferta> ofertas = General.Filtrar(oRespuestFiltradas.datos, ofertasPredicate);
oRespuestFiltradas.datos = new ArrayList<Oferta>(ofertas);
}
else{
oRespuestFiltradas.datos = new ArrayList<Oferta>();
}
adapterOfertas = new OfertasAdapter(activity, oRespuestFiltradas, oRespuesta);
lstOfertas.setAdapter(adapterOfertas);
final long ONE_MINUTE_IN_MILLIS = 60000;//millisecs
long t = Calendar.getInstance().getTime().getTime();
Date afterAddingTenMins = new Date(t + (10 * ONE_MINUTE_IN_MILLIS));
if(Datos.ventana_origen != Constantes.Ventanas_Origen.OfertasDetalle
|| (OfertasDetalleActivity.getFechaCarga() != null
&& !OfertasDetalleActivity.getFechaCarga().before(afterAddingTenMins))){
m_posicionOfertas = lstOfertas.getRefreshableView().getFirstVisiblePosition();
}
if(m_posicionOfertas != -1){
lstOfertas.getRefreshableView().setSelection(m_posicionOfertas);
}
General.OcultarCargando();
}
catch (Exception e){
e.printStackTrace();
General.OcultarCargando();
}
}

Related

listview effecting multiple rows 4th,7th,10th

i have a custom listview and custom adapter. each row has multiple items inside it, when i click on like button it change the color of imageview but it also effect the 4th,7th and 10th row.
after searching on internet i learned that i have to use getTag and setTag but i dont know how to use it.
please help me in understanding the concept of getTag and setTag and solving this error.
here is my code:-
package rj.osmthemes;
import java.util.ArrayList;
import android.content.Context;
import android.os.Build;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import static android.R.attr.data;
import static rj.osmthemes.R.id.downlink;
import static rj.osmthemes.R.id.likebtn;
import static rj.osmthemes.R.id.likecount;
public class ListAdapter extends ArrayAdapter<DataModel> {
customButtonListener customListner;
private ArrayList<DataModel> dataSet;
public String temp1;
public interface customButtonListener {
public void onButtonClickListner(int position,String value);
public void onImageClickListner(int position,String value);
public void onlikeImageClickListner(int position,String value);
public void ondislikeImageClickListner(int position,String value);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
private Context context;
//private ArrayList<String> data = new ArrayList<String>();
public ListAdapter(ArrayList<DataModel> data, Context context) {
super(context, R.layout.list_layout, data);
this.dataSet = data;
this.context = context;
}
private int lastPosition = -1;
// public ListAdapter(Context context, ArrayList<String> dataItem) {
// super(context, R.layout.list_layout, dataItem);
// this.data = dataItem;
// this.context = context;
// }
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
final DataModel dataModel = getItem(position);
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.list_layout, null);
viewHolder = new ViewHolder();
viewHolder.themename = (TextView) convertView.findViewById(R.id.themename);
viewHolder.madeby = (TextView) convertView.findViewById(R.id.madeby);
viewHolder.downcount = (TextView) convertView.findViewById(R.id.downcount);
viewHolder.likecount = (TextView) convertView.findViewById(likecount);
viewHolder.dislikecount = (TextView) convertView.findViewById(R.id.dislikecount);
viewHolder.ss1 = (ImageView) convertView.findViewById(R.id.img1);
viewHolder.ss2 = (ImageView) convertView.findViewById(R.id.img2);
viewHolder.ss3 = (ImageView) convertView.findViewById(R.id.img3);
viewHolder.likebtn = (ImageView) convertView.findViewById(likebtn);
viewHolder.dislikebtn = (ImageView) convertView.findViewById(R.id.dislikebtn);
viewHolder.btndownload = (Button) convertView.findViewById(downlink);
convertView.setTag(viewHolder);
final String temp = getItem(position).toString();
viewHolder.likebtn.setTag(temp);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
lastPosition = position;
//final String temp = getItem(position).toString();
// viewHolder.tempid = Integer.parseInt(dataModel.getId());
final String ss1link,ss2link,ss3link,downlink;
viewHolder.themename.setText(dataModel.getTheme_name());
viewHolder.madeby.setText(dataModel.getMade_by());
viewHolder.downcount.setText(dataModel.getDown_count());
viewHolder.likecount.setText(dataModel.getLike_count());
viewHolder.dislikecount.setText(dataModel.getDislike_count());
ss1link = dataModel.getSs1();
ss2link = dataModel.getSs2();
ss3link = dataModel.getSs3();
downlink = dataModel.getDown_link();
// viewHolder.text.setText(temp);
viewHolder.btndownload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
int downcounttmp = Integer.parseInt(dataModel.getDown_count());
downcounttmp++;
viewHolder.downcount.setText(""+downcounttmp);
String name = downlink + "#" + dataModel.getTheme_name() + "#" + dataModel.getId() + "#" + downcounttmp;
customListner.onButtonClickListner(position,name);
}
}
});
viewHolder.ss1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onImageClickListner(position,ss1link);
}
}
});
viewHolder.ss2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onImageClickListner(position,ss2link);
}
}
});
viewHolder.ss3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onImageClickListner(position,ss3link);
}
}
});
viewHolder.likebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
// Toast.makeText(context, dataModel.getId() + " { " ,Toast.LENGTH_LONG).show();
if(viewHolder.check == 0){
int likecount = Integer.parseInt(dataModel.getLike_count());
likecount++;
viewHolder.likecount.setText(""+likecount);
String name = likecount + "#" + dataModel.getId();
// Toast.makeText(context,position + " " + temp,Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
viewHolder.likebtn.setImageResource(R.drawable.ic_thumb_up_red_24dp);
//viewHolder.likebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_up_red_24dp, getContext().getTheme()));
viewHolder.check = 1;
} else {
viewHolder.likebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_up_red_24dp));
viewHolder.check = 1;
}
customListner.onlikeImageClickListner(position,name);
}
else {
Toast.makeText(context,"You cant use this action",Toast.LENGTH_LONG).show();
}
}
}
});
viewHolder.dislikebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
if(viewHolder.check == 0) {
int dislikecount = Integer.parseInt(dataModel.getDislike_count());
dislikecount++;
viewHolder.dislikecount.setText(""+dislikecount);
String name = dislikecount + "#" + dataModel.getId();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
viewHolder.dislikebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_down_red_24dp, getContext().getTheme()));
viewHolder.check = 1;
} else {
viewHolder.dislikebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_down_red_24dp));
viewHolder.check = 1;
}
customListner.ondislikeImageClickListner(position,name);
}
else {
Toast.makeText(context,"You cant use this action",Toast.LENGTH_LONG).show();
}
}
}
});
Glide
.with(context)
.load(ss1link)
.into(viewHolder.ss1);
Glide
.with(context)
.load(ss2link)
.into(viewHolder.ss2);
Glide
.with(context)
.load(ss3link)
.into(viewHolder.ss3);
return convertView;
}
public class ViewHolder {
TextView themename,madeby,downcount,likecount,dislikecount;
Button btndownload;
ImageView ss1,ss2,ss3,likebtn,dislikebtn;
int check = 0, tempid = 0;
}
}
This is because of object reuse in your list view.
You can manage separate ArrayList or HashMap to maintain your likes.
And based on that you should update in your getView like this,
if([already selected]) {
viewHolder.likebtn.setBackground([your selected drawable]);
} else {
viewHolder.likebtn.setBackground([your non selected drawable]);
}

fix listview data disappear when activity restarted in android

I wrote an android app and it simply displays a list view.
and everything works fine except one.
I installed my app on my tablet and when i run the app, that problem occurs.
==>. that is . . .
When I press power button to turn off screen and press power button again to turn screen on, the whole list view data disappears.
I think this is some problem with activity lifecycle, but I can't deal with this..
Please help me..
Here is my code...
package com.jo.fivemancard;
import android.content.Context;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public ScoreListAdapter scoreListAdapter;
class RoundScore {
public int score1 = 0;
public int score2 = 0;
public int score3 = 0;
public int score4 = 0;
public int score5 = 0;
public RoundScore(){
score1 = score2 = score3 = score4 = score5 = 0;
}
}
class ScoreListAdapter extends BaseAdapter{
public Context context;
class ViewHolder{
TextView textViewScore1;
TextView textViewScore2;
TextView textViewScore3;
TextView textViewScore4;
TextView textViewScore5;
}
public ArrayList<RoundScore> scoreList;
public ScoreListAdapter(Context cont){
context = cont;
scoreList = new ArrayList<RoundScore>();
}
public void appendData(RoundScore rc){
scoreList.add(rc);
notifyDataSetChanged();
}
#Override
public int getCount() {
return scoreList.size();
}
#Override
public Object getItem(int position) {
return scoreList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.listviewitem_score, parent, false);
vh = new ViewHolder();
vh.textViewScore1 = (TextView)rowView.findViewById(R.id.textViewScore1);
vh.textViewScore2 = (TextView)rowView.findViewById(R.id.textViewScore2);
vh.textViewScore3 = (TextView)rowView.findViewById(R.id.textViewScore3);
vh.textViewScore4 = (TextView)rowView.findViewById(R.id.textViewScore4);
vh.textViewScore5 = (TextView)rowView.findViewById(R.id.textViewScore5);
convertView = rowView;
}else {
vh = (ViewHolder) convertView.getTag();
}
RoundScore rc = scoreList.get(position);
vh.textViewScore1.setText("" + rc.score1);
vh.textViewScore2.setText("" + rc.score2);
vh.textViewScore3.setText("" + rc.score3);
vh.textViewScore4.setText("" + rc.score4);
vh.textViewScore5.setText("" + rc.score5);
convertView.setTag(vh);
return convertView;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.buttonNextRound).setOnClickListener(this);
findViewById(R.id.floatActionButtonCalculate).setOnClickListener(this);
scoreListAdapter = new ScoreListAdapter(this);
((ListView)findViewById(R.id.listViewScore)).setAdapter(scoreListAdapter);
((TextView)findViewById(R.id.textViewPlayer1)).setText(GlobalConstant.playername1);
((TextView)findViewById(R.id.textViewPlayer2)).setText(GlobalConstant.playername2);
((TextView)findViewById(R.id.textViewPlayer3)).setText(GlobalConstant.playername3);
((TextView)findViewById(R.id.textViewPlayer4)).setText(GlobalConstant.playername4);
((TextView)findViewById(R.id.textViewPlayer5)).setText(GlobalConstant.playername5);
}
public int getScore(String score){
if(score.trim().equals("")){
return 0;
}
if(score.length() == 0){
return 0;
}
boolean isNumber;
if(score.charAt(0) == '-'){
isNumber = android.text.TextUtils.isDigitsOnly(score.substring(1));
}else{
isNumber = android.text.TextUtils.isDigitsOnly(score);
}
if(isNumber) {
return Integer.parseInt(score.trim());
}
return 0;
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.buttonNextRound){
String score1 = ((EditText)findViewById(R.id.editTextNewScorePlayer1)).getText().toString();
String score2 = ((EditText)findViewById(R.id.editTextNewScorePlayer2)).getText().toString();
String score3 = ((EditText)findViewById(R.id.editTextNewScorePlayer3)).getText().toString();
String score4 = ((EditText)findViewById(R.id.editTextNewScorePlayer4)).getText().toString();
String score5 = ((EditText)findViewById(R.id.editTextNewScorePlayer5)).getText().toString();
if(score1.trim().equals("")){
score1 = "0";
}
RoundScore rc = new RoundScore();
rc.score1 = getScore(score1);
rc.score2 = getScore(score2);
rc.score3 = getScore(score3);
rc.score4 = getScore(score4);
rc.score5 = getScore(score5);
if(rc.score1 == 0 && rc.score2 == 0 && rc.score3 == 0 && rc.score4 == 0 && rc.score5 == 0){
Toast.makeText(this, "Bad Input...", Toast.LENGTH_SHORT).show();
return;
}
scoreListAdapter.appendData(rc);
((ListView)findViewById(R.id.listViewScore)).setSelection(scoreListAdapter.getCount() - 1);
Toast.makeText(this, "Next Round...", Toast.LENGTH_SHORT).show();
((EditText)findViewById(R.id.editTextNewScorePlayer1)).setText("");
((EditText)findViewById(R.id.editTextNewScorePlayer2)).setText("");
((EditText)findViewById(R.id.editTextNewScorePlayer3)).setText("");
((EditText)findViewById(R.id.editTextNewScorePlayer4)).setText("");
((EditText)findViewById(R.id.editTextNewScorePlayer5)).setText("");
}
if(v.getId() == R.id.floatActionButtonCalculate){
RoundScore rs = new RoundScore();
int i;
for(i=0;i<scoreListAdapter.scoreList.size();i++){
rs.score1 += scoreListAdapter.scoreList.get(i).score1;
rs.score2 += scoreListAdapter.scoreList.get(i).score2;
rs.score3 += scoreListAdapter.scoreList.get(i).score3;
rs.score4 += scoreListAdapter.scoreList.get(i).score4;
rs.score5 += scoreListAdapter.scoreList.get(i).score5;
}
if(findViewById(R.id.buttonNextRound).isEnabled()){
String str1 = ((EditText)findViewById(R.id.editTextNewScorePlayer1)).getText().toString().trim();
String str2 = ((EditText)findViewById(R.id.editTextNewScorePlayer2)).getText().toString().trim();
String str3 = ((EditText)findViewById(R.id.editTextNewScorePlayer3)).getText().toString().trim();
String str4 = ((EditText)findViewById(R.id.editTextNewScorePlayer4)).getText().toString().trim();
String str5 = ((EditText)findViewById(R.id.editTextNewScorePlayer5)).getText().toString().trim();
if(!str1.equals("") || !str2.equals("") || !str3.equals("") || !str4.equals("") || !str5.equals("")){
Toast.makeText(this,"It seems you wanna add score info.",Toast.LENGTH_SHORT);
return;
}
findViewById(R.id.buttonNextRound).setEnabled(false);
((EditText)findViewById(R.id.editTextNewScorePlayer1)).setText("" + rs.score1);
((EditText)findViewById(R.id.editTextNewScorePlayer2)).setText("" + rs.score2);
((EditText)findViewById(R.id.editTextNewScorePlayer3)).setText("" + rs.score3);
((EditText)findViewById(R.id.editTextNewScorePlayer4)).setText("" + rs.score4);
((EditText)findViewById(R.id.editTextNewScorePlayer5)).setText("" + rs.score5);
((EditText)findViewById(R.id.editTextNewScorePlayer1)).setEnabled(false);
((EditText)findViewById(R.id.editTextNewScorePlayer2)).setEnabled(false);
((EditText)findViewById(R.id.editTextNewScorePlayer3)).setEnabled(false);
((EditText)findViewById(R.id.editTextNewScorePlayer4)).setEnabled(false);
((EditText)findViewById(R.id.editTextNewScorePlayer5)).setEnabled(false);
}else{
findViewById(R.id.buttonNextRound).setEnabled(true);
((EditText)findViewById(R.id.editTextNewScorePlayer1)).setText("");
((EditText)findViewById(R.id.editTextNewScorePlayer2)).setText("");
((EditText)findViewById(R.id.editTextNewScorePlayer3)).setText("");
((EditText)findViewById(R.id.editTextNewScorePlayer4)).setText("");
((EditText)findViewById(R.id.editTextNewScorePlayer5)).setText("");
((EditText)findViewById(R.id.editTextNewScorePlayer1)).setEnabled(true);
((EditText)findViewById(R.id.editTextNewScorePlayer2)).setEnabled(true);
((EditText)findViewById(R.id.editTextNewScorePlayer3)).setEnabled(true);
((EditText)findViewById(R.id.editTextNewScorePlayer4)).setEnabled(true);
((EditText)findViewById(R.id.editTextNewScorePlayer5)).setEnabled(true);
}
}
}
private Boolean exit = false;
#Override
public void onBackPressed() {
if (exit) {
finish(); // finish activity
} else {
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 1 * 1000);
}
}
}

issue in pass arraylist to autocompletetextview

I want to display 3 textviews in autocomplete textview drop down so I'm using arryalist but when I pass arraylist to AutoCompleteTextview,nothing display in dropdown.
I print the arryalist.tostring() in logcat.and the output is
[com.novityrecharge.Beans.AutocompletetextviewGeSe#41097f28]
How to solve this
Autcocompleteadapter2.java
package com.novityrecharge.adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;
import com.novityrecharge.Beans.AutocompletetextviewGeSe;
import com.novityrecharge.R;
import java.util.ArrayList;
import java.util.List;
/**
* Created by varshils on 3/26/2016.
*/
public class AutoCompleteAdapter2 extends ArrayAdapter<AutocompletetextviewGeSe> {
private Activity context;
ArrayList<AutocompletetextviewGeSe> data;
int layoutResourceId;
public AutoCompleteAdapter2(Activity context, int resource,ArrayList<AutocompletetextviewGeSe> data)
{
super(context, resource, data);
this.context = context;
this.data = data;
this.layoutResourceId = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
return getDropDownView(position, convertView, parent);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{ // This view starts when we click the spinner.
View row = convertView;
listHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new listHolder();
holder.firm = (TextView)row.findViewById(R.id.a_firm);
holder.mob = (TextView)row.findViewById(R.id.a_mobno);
holder.mcode = (TextView)row.findViewById(R.id.a_mcode);
row.setTag(holder);
}
else
{
holder = (listHolder)row.getTag();
}
AutocompletetextviewGeSe item = data.get(position);
holder.firm.setText(item.getAfirm());
holder.mob.setText(item.getAmob());
holder.mcode.setText(item.getAmcode());
return row;
}
static class listHolder
{
TextView firm,mob,mcode;
}
}
Topuptransfer.java
package com.novityrecharge;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v4.view.GravityCompat;
import android.support.v7.app.ActionBar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import com.novityrecharge.Beans.AutocompletetextviewGeSe;
import com.novityrecharge.Beans.ResponseString;
import com.novityrecharge.CrashingReport.ExceptionHandler;
import com.novityrecharge.Interfaces.callback;
import com.novityrecharge.adapter.AutoCompleteAdapter;
import com.novityrecharge.adapter.AutoCompleteAdapter2;
import com.novityrecharge.async.AsyncTaskCommon;
import com.novityrecharge.async.AsynctaskgetBalance;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by varshils on 1/13/2016.
*/
public class TopupTransfer extends BaseActivity{
AutoCompleteTextView memberView;
ArrayList <AutocompletetextviewGeSe> name1= null;
Button btnSubmit;
String membercode2,amount;
TextInputLayout smspin_textInputLayout;
EditText amnt,smspin;;
HashMap<String,String> memberDetail;
AutoCompleteAdapter2 adapter;
DatabaseHelper db;
int amont;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.topuptransfer);
if(!(Thread.getDefaultUncaughtExceptionHandler() instanceof ExceptionHandler))
{
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
}
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#4CB5F5")));
db = new DatabaseHelper(TopupTransfer.this);
memberView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
name1 = new ArrayList<AutocompletetextviewGeSe>();
memberDetail = new HashMap<String,String>();
amnt = (EditText) findViewById(R.id.topup_amnt);
btnSubmit = (Button) findViewById(R.id.button);
smspin = (EditText) findViewById(R.id.smspin);
smspin_textInputLayout = (TextInputLayout) findViewById(R.id.topuptransfer_smspin);
if(ResponseString.getRequiredSmsPin().equals("TRUE"))
{
smspin_textInputLayout.setVisibility(View.VISIBLE);
smspin.setVisibility(View.VISIBLE);
}
else
{
smspin_textInputLayout.setVisibility(View.GONE);
smspin.setVisibility(View.GONE);
}
memberView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String text = s.toString();
Log.d("text", "" + text);
int len = text.length();
if (memberView != null)
{
if( len >= 3) {
Log.d("text", "" + text);
try {
name1 = GetList2(text);
Log.d("ADPTER LIST", name1.toString());
adapter = new AutoCompleteAdapter2(TopupTransfer.this,R.layout.autocompletetextview_layout,name1);
memberView.setAdapter(adapter);
}catch(Exception e){
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(TopupTransfer.this));
}
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(amnt.getText().toString().length() != 0)
{
amont = Integer.parseInt(amnt.getText().toString());
}
if(ResponseString.getRequiredSmsPin().equals("TRUE"))
{
String sms = smspin.getText().toString();
String rs = ResponseString.getSmspwd();
if (sms.length() == 0) {
toastValidationMessage(TopupTransfer.this, getResources().getString(R.string.plsentersmspin));
return;
}
else if (!sms.equals(rs)) {
toastValidationMessage(TopupTransfer.this, getResources().getString(R.string.pinentercorrect));
return;
}
}else if (memberView.getText().toString().length() == 0) {
toastValidationMessage(TopupTransfer.this, getResources().getString(R.string.plsenterfirm));
memberView.requestFocus();
return;
}else if (amnt.getText().toString().length() == 0) {
toastValidationMessage(TopupTransfer.this, getResources().getString(R.string.plsenteramnt));
amnt.requestFocus();
return;
}else if(amont <= 0)
{
toastValidationMessage(TopupTransfer.this, getResources().getString(R.string.plsentercrectamnt));
return;
}
String Dpattern = memberView.getText().toString();
membercode2 = BaseActivity.detailMember.get(Dpattern);
amount = amnt.getText().toString();
Log.d("topup membercode",membercode2);
try {
if (membercode2 == null) {
//Toast.makeText(TopupTransfer.this, "Firm name is not Valid", Toast.LENGTH_SHORT).show();
toastValidationMessage(TopupTransfer.this, "Firm name is not Valid");
memberView.requestFocus();
} else {
boolean con = isInternetConnected();
if (con) {
AsynctaskgetBalance asy = new AsynctaskgetBalance(TopupTransfer.this,new callback(){
public void run(String result){
if (ResponseString.getStcode().equals("0")) {
AlertDialog.Builder builder = new AlertDialog.Builder(TopupTransfer.this);
builder.setTitle(R.string.app_name);
builder.setMessage(BaseActivity.sMsg);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
BaseActivity.sMsg = "";
finish();
Intent m = new Intent(TopupTransfer.this,TopupTransfer.class);
overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
startActivity(m);
}
});
setOnlyBalance();
builder.show();
} else {
toastValidationMessage(TopupTransfer.this,sMsg);
}
}
} , membercode2,amount,"","BALANCE","DISCOUNT");
asy.execute("TopupTransfer");
} else {
toastValidationMessage(TopupTransfer.this,getResources().getString(R.string.checkinternet));
}
}
}catch (Exception e)
{
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(TopupTransfer.this));
}
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
case R.id.action_signout:
logout(TopupTransfer.this);
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
if (fullLayout != null && fullLayout.isDrawerOpen(GravityCompat.START)) {
fullLayout.closeDrawer(GravityCompat.START);
} else {
Intent intent = new Intent(TopupTransfer.this, HomePage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
}
#Override
protected void onPause() {
super.onPause();
if ((BaseActivity.pleaseWaitDialog != null) && BaseActivity.pleaseWaitDialog.isShowing()) {
BaseActivity.pleaseWaitDialog.dismiss();
BaseActivity.pleaseWaitDialog = null;
}
}
}
GetList2()
ArrayList<AutocompletetextviewGeSe> GetList2(String text) {
AutocompletetextviewGeSe autogese;
ArrayList<AutocompletetextviewGeSe> arrayListtemp = new ArrayList<AutocompletetextviewGeSe>();;
Cursor cursor = db.getTimeRecordList(text, "ChildUserInfo");
if (cursor != null){
if (cursor.moveToFirst()) {
do {
autogese = new AutocompletetextviewGeSe();
autogese.setAfirm(cursor.getString(cursor.getColumnIndex("FirmName")));
autogese.setAmob(cursor.getString(cursor.getColumnIndex("MobileNumber")));
autogese.setAmcode(cursor.getString(cursor.getColumnIndex("MemberCode")));
arrayListtemp = new ArrayList<AutocompletetextviewGeSe>();
arrayListtemp.add(autogese);
} while (cursor.moveToNext());
}
}
Log.d("arraylist",arrayListtemp.toString());
return arrayListtemp;
}

wrong item is being selected in listview when selecting checkbox

**
When i select the items which are at the bottom of the listview,they wont get selected,
rather only first four items in the list is being selected.its because the items are out of view.
what to do to get these items in view ??sometimes the item gets randomly selected.
Please help me.
thank you
Here is my code**
Main activity
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
public class ExceptionAppActivity extends Activity implements OnClickListener, OnItemSelectedListener {
private final int REQUEST_CODE = 20;
String flagg;
String empNm = Constants.Common.STR_BLNK;
String empCode = Constants.Common.STR_BLNK;
SessionManager session = null;
final Context context = this;
static Typeface custom_font = null;
TextView lblExcId, lblExcEmpNm, lblExcFrmDt, lblExcFrmDtVal, lblExcToDtVal, lblExcTyp, lblExcStat, lblExcEmpCmt;
Button btnExcRej, btnExcApp, btnExcSrch, btnExcExit;
CheckBox cb, chkBox;
ListView excSrchListView;
ArrayList<Excp> Results;
CustomListViewAdapter cla;
ExceptionAppDao eCon = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.exception_app_activity);
/* get Resources from Xml file */
btnExcApp = (Button) findViewById(R.id.btnExcApp);
btnExcRej = (Button) findViewById(R.id.btnExcRej);
btnExcSrch = (Button) findViewById(R.id.btnExcSrch);
btnExcExit = (Button) findViewById(R.id.btnExcExit);
lblExcEmpNm = (TextView) findViewById(R.id.lblExcEmpNm);
lblExcFrmDt = (TextView) findViewById(R.id.lblExcFrmDt);
lblExcFrmDtVal = (TextView) findViewById(R.id.lblExcFrmDtVal);
lblExcToDtVal = (TextView) findViewById(R.id.lblExcToDtVal);
lblExcTyp = (TextView) findViewById(R.id.lblExcTyp);
lblExcStat = (TextView) findViewById(R.id.lblExcStat);
lblExcEmpCmt = (TextView) findViewById(R.id.lblExcEmpCmt);
lblExcId = (TextView) findViewById(R.id.lblExcId);
chkBox = (CheckBox) findViewById(R.id.chkBx);
excSrchListView = (ListView) findViewById(R.id.excSrchListView);
// Session Manager
session = new SessionManager(getApplicationContext());
custom_font = Typeface.createFromAsset(getAssets(), "fonts/DejaVuSans.ttf");
// Connection object for Login
eCon = new ExceptionAppDao(context);
// get User Details from Session
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap = session.getUserDetails();
empNm = hashMap.get(SessionManager.KEY_EMP_NM);
empCode = hashMap.get(SessionManager.KEY_EMP_CODE);
btnExcApp.setTypeface(custom_font);
btnExcRej.setTypeface(custom_font);
btnExcSrch.setTypeface(custom_font);
btnExcExit.setTypeface(custom_font);
new SyncData(empCode).execute();
if (getIntent().getBooleanExtra("EXIT", false)) {
}
// on click any button
addButtonListener();
}
/**
* on click any button
*/
private void addButtonListener() {
btnExcApp.setOnClickListener(this);
btnExcRej.setOnClickListener(this);
btnExcSrch.setOnClickListener(this);
btnExcExit.setOnClickListener(this);
}
public class SyncData extends AsyncTask<String, String, ArrayList<Excp>> {
private final ProgressDialog dialog = new ProgressDialog(context);
List<ExcpMstVo> rtnExcVo = new ArrayList<ExcpMstVo>();
ExcpMstVo rtnExcMstVo = new ExcpMstVo();
ArrayList<Excp> resultLst = new ArrayList<Excp>();
ExceptionService_Service excpServObj = new ExceptionService_Service();
String syncFlg = Constants.Common.STR_BLNK;
private View rootView;
String flag = "";
int x;
boolean success = false;
boolean successSyncFlag = false;
int countApp = 0;
public SyncData(String str) {
syncFlg = str;
}
public SyncData(View rootView) {
// TODO Auto-generated constructor stub
this.rootView = rootView;
}
#Override
protected ArrayList<Excp> doInBackground(String... params) {
ExceptionSearchCriteria vo = new ExceptionSearchCriteria();
ExcpMstVo excpMstVo = new ExcpMstVo();
try {
if (syncFlg.equals(empCode)) {
vo = setAppData(vo);
rtnExcVo = excpServObj.getExceptionPort().searchExceptionApproval(vo);
if (!(rtnExcVo.isEmpty())) {
System.out.println("rtnExcVo" + rtnExcVo.size());
Excp exc = null;
for (ExcpMstVo excMstVo : rtnExcVo) {
exc = new Excp();
exc.setExcId(excMstVo.getExcpId());
exc.setEmpCode(excMstVo.getEmpCode());
exc.setEmpNm(excMstVo.getEmpnm());
exc.setFromDt(excMstVo.getFromDt());
exc.setToDt(excMstVo.getToDt());
exc.setExcType(excMstVo.getExcpType());
exc.setExcStatus(excMstVo.getStatus());
exc.setEmpComments(excMstVo.getEmpComments());
exc.setExcFor(excMstVo.getExcpFor());
exc.setExcReason(excMstVo.getExcpReason());
resultLst.add(exc);
Results = resultLst;
success = true;
}
}
} else if (btnExcApp.equals(rootView.getRootView().findViewById(rootView.getId()))) {
for (x = excSrchListView.getChildCount() - 1; x >= 0; x--) {
cb = (CheckBox) excSrchListView.getChildAt(x).findViewById(R.id.chkBx);
if (cb.isChecked()) {
excpMstVo = setEmpData();
rtnExcMstVo = excpServObj.getExceptionPort().changeExceptionStatus(excpMstVo);
System.out.println("rtnExcMstVo:::::" + rtnExcMstVo.getExcpId());
System.out.println("rtnExcMstVoStatuss:::::" + rtnExcMstVo.getStatus());
countApp++;
success = false;
}
}
/*if (countApp == 0) {
} else*/ if (countApp > 0) {
new SyncData(rootView).execute();
//flagg = false;
}
System.out.println("rtnExcMstVo:::::" + rtnExcMstVo.getExcpId());
System.out.println("rtnExcMstVoStatuss:::::" + rtnExcMstVo.getStatus());
}
// get dump from device
CopyDbFromDevice cd = new CopyDbFromDevice();
cd.copyDbToSdcard(context);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("success::::" + success);
successSyncFlag = success;
System.out.println("successSyncFlag::::::::" + successSyncFlag);
return resultLst;
}
private ExcpMstVo setEmpData() {
ExcpMstVo excpMstVo = new ExcpMstVo();
excpMstVo.setExcpId(Results.get(x).getExcId());
excpMstVo.setFromDt(Results.get(x).getFromDt());
excpMstVo.setStatus(Constants.Status.STAT_APPRV);
excpMstVo.setMngrComments("");
excpMstVo.setApprovedBy(empCode);
excpMstVo.setLoggedInUser(empCode);
return excpMstVo;
}
private ExceptionSearchCriteria setAppData(ExceptionSearchCriteria vo) {
vo.setApprover(empCode);
vo.setStatus(Constants.Status.PENDING_APPROVAL);
return vo;
}
protected void onPostExecute(ArrayList<Excp> searchResults) {
System.out.println("successSyncFlag1::::::::" + successSyncFlag);
if (successSyncFlag == true) {
System.out.println("entering ON POST IF");
cla = new CustomListViewAdapter(ExceptionAppActivity.this, resultLst);
excSrchListView.setAdapter(cla);
}
else {
System.out.println("ENTERING ONPOST ELSE PART ");
System.out.println("successSyncFlag2:;;;;;; " + successSyncFlag);
System.out.println("success2:::::::::::: " + success);
System.out.println("NEW METHOD STARTED:::::;");
if (countApp == 0) {
System.out.println("ENTERING COUNT APP 0 ");
String flag = "checkItemApp";
dialogBox(flag);
} else {
new SyncData(empCode).execute();
String flag = "excApp";
dialogBox(flag);
System.out.println("NEW METHOD STARTED1:::::::::");
}
}
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
#Override
public void onClick(View v) {
int countRej = 0;
int id = v.getId();
Intent intent = null;
if (id == R.id.btnExcApp) {
new SyncData(v).execute();
} else if (id == R.id.btnExcRej) {
int itemPos = 0;
for (int y = excSrchListView.getChildCount() - 1; y >= 0; y--) {
cb = (CheckBox) excSrchListView.getChildAt(y).findViewById(R.id.chkBx);
if (cb.isChecked()) {
itemPos = y;
cla.notifyDataSetChanged();
countRej++;
}
}
// Check if any Exception is selected for Rejection and proceed
// accordingly
if (countRej == 1) {
CustomListViewAdapter cla = (CustomListViewAdapter) excSrchListView.getAdapter();
Object o = cla.getItem(itemPos);
Excp selectedExcp = (Excp) o;
intent = new Intent(getBaseContext(), ExcAppDtlsActivity.class);
intent.putExtra("selectedExcp", selectedExcp);
intent.putExtra("readOnly", false);
startActivityForResult(intent, REQUEST_CODE);
} else if (countRej == 0) {
// show dialogue of Select at least 1
String flag = "checkItemRej";
dialogBox(flag);
} else if (countRej > 1) {
String flag = "checkOnlyOne";
dialogBox(flag);
for (int y = excSrchListView.getChildCount() - 1; y >= 0; y--) {
cb = (CheckBox) excSrchListView.getChildAt(y).findViewById(R.id.chkBx);
if (cb.isChecked()) {
itemPos = y;
cb.setChecked(false);
cla.notifyDataSetChanged();
}
}
}
} else if (id == R.id.btnExcSrch) {
intent = new Intent(this, FurtherSearchActivity.class);
intent.putExtra("readOnly", false);
startActivity(intent);
} else if (id == R.id.btnExcExit) {
finish();
}
}
/**
* create alert dialog
*
* #param flag
*/
private void dialogBox(String flag) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
/*if (flag == "excApp") {
alertDialogBuilder.setTitle("Exception Approved successfully !");
} else*/ if (flag == "checkOnlyOne") {
alertDialogBuilder.setTitle("Please select only one item to reject !");
} else if (flag == "checkItemRej") {
alertDialogBuilder.setTitle("Select Exception to Reject !");
}
/*else if (flag == "checkItemApp") {
alertDialogBuilder.setTitle("Select Exception to Approve !");
} */
else if (flag == "excRej") {
alertDialogBuilder.setTitle("Exception Rejected successfully !");
}
/*else {
alertDialogBuilder.setTitle("Flag - " + flag);
}*/
Dialogbox dbx = new Dialogbox(context);
dbx.createDialogAlert(flag, alertDialogBuilder);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
#Override
protected void
onActivityResult(int requestCode, int resultCode, Intent data) {
// REQUEST_CODE is defined above
/*
* if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) { //
* Extract name value from result extras flagg =
* data.getExtras().getString("flagg"); if ((flagg.equals("Approve")) ||
* (flagg.equals("Reject"))) { for (int x = 0; x <
* excSrchListView.getChildCount(); x++) { cb = (CheckBox)
* excSrchListView.getChildAt(x).findViewById( R.id.chkBx); if
* (cb.isChecked()) { // If Approval is successful remove from list
* Results.remove(x); cb.setChecked(false); cla.notifyDataSetChanged();
* if (flagg.equals("Approve")) { dialogBox("excApp"); } else {
* dialogBox("excRej"); } } }
*
* } }
*/
}
}
CUSTOM LIST ADAPTER
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TableLayout;
import android.widget.TextView;
import com.eanda.smarttime_mobi.R;
import com.eanda.smarttime_mobi.model.Excp;
public class CustomListViewAdapter extends BaseAdapter {
private static ArrayList<Excp> searchArrayList;
HashMap<Integer, Boolean> checked;
private LayoutInflater mInflater;
Typeface custom_font = null;
public CustomListViewAdapter(Context context, ArrayList<Excp> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
checked = new HashMap<Integer, Boolean>(getCount());
custom_font = Typeface.createFromAsset(context.getAssets(), "fonts/DejaVuSans.ttf");
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
// created custom view
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.myTable = (TableLayout) convertView.findViewById(R.id.myTable);
holder.txtExcId = (TextView) convertView.findViewById(R.id.lblExcId);
holder.txtEmpNm = (TextView) convertView.findViewById(R.id.lblExcEmpNm);
holder.txtFrmDt = (TextView) convertView.findViewById(R.id.lblExcFrmDtVal);
holder.txtToDt = (TextView) convertView.findViewById(R.id.lblExcToDtVal);
holder.txtExcTyp = (TextView) convertView.findViewById(R.id.lblExcTyp);
holder.txtExcStat = (TextView) convertView.findViewById(R.id.lblExcStat);
holder.txtEmpCmt = (TextView) convertView.findViewById(R.id.lblExcEmpCmt);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.chkBx);
convertView.setTag(holder);
convertView.setTag(R.id.chkBx, holder.checkBox);
} else {
holder = (ViewHolder) convertView.getTag();
}
System.out.println("exception_name" + searchArrayList.get(position).getEmpNm());
holder.txtExcId.setText(Integer.toString(searchArrayList.get(position).getExcId()));
holder.txtEmpNm.setText(searchArrayList.get(position).getEmpNm());
holder.txtFrmDt.setText(searchArrayList.get(position).getFromDt());
holder.txtToDt.setText(searchArrayList.get(position).getToDt());
holder.txtExcTyp.setText(searchArrayList.get(position).getExcType());
holder.txtExcStat.setText(searchArrayList.get(position).getExcStatus());
holder.txtEmpCmt.setText(searchArrayList.get(position).getEmpComments());
holder.checkBox.setTag(position);
holder.checkBox.setChecked(searchArrayList.get(position).isChecked());
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.chkBx);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
System.out.println("selected");
int checkBoxId = (Integer) buttonView.getTag();
holder.checkBox.setChecked(buttonView.isChecked() ? true : false);
searchArrayList.get(checkBoxId).setChecked(buttonView.isChecked() ? true : false);
System.out.println("checkBoxId " + checkBoxId);
}
});
holder.checkBox.setTag(position);
holder.txtExcId.setTypeface(custom_font);
holder.txtEmpNm.setTypeface(custom_font);
holder.txtFrmDt.setTypeface(custom_font);
holder.txtToDt.setTypeface(custom_font);
holder.txtExcTyp.setTypeface(custom_font);
holder.txtExcStat.setTypeface(custom_font);
holder.txtEmpCmt.setTypeface(custom_font);
return convertView;
}
static class ViewHolder {
TableLayout myTable;
TextView txtExcId;
TextView txtEmpNm;
TextView txtFrmDt;
TextView txtToDt;
TextView txtExcTyp;
TextView txtExcStat;
TextView txtEmpCmt;
CheckBox checkBox;
}
}
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.chkBx);
You already have check box reference stored in the holder, I wonder why you are initializing it again.
holder.checkBox.setChecked(buttonView.isChecked() ? true : false);
Checked state will be changed when the user clicks the checkbox, so no need to change the checked state again.
Try the following code
----
----
holder.checkBox.setTag(position);
holder.checkBox.setChecked(searchArrayList.get(position).isChecked());
holder.checkBox..setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
System.out.println("selected");
int checkBoxId = (Integer) buttonView.getTag();
searchArrayList.get(checkBoxId).setChecked(buttonView.isChecked() ? true : false);
System.out.println("checkBoxId " + checkBoxId);
}
});
holder.checkBox.setTag(position);
-----
----

How to get online friend list in gmail?

I am trying to get online friend list in gmail,
i am login and also can chat with friend email id.but not getting list.
Thanks
import android.app.ListActivity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.indianic.frdinfo.FriendInfo;
import com.indianic.frdinfo.STATUS;
import com.indianic.interfac.IAppManager;
import com.indianic.service.IMService;
public class FriendList extends ListActivity
{
private static final int ADD_NEW_FRIEND_ID = Menu.FIRST;
private static final int EXIT_APP_ID = Menu.FIRST + 1;
private IAppManager imService = null;
private FriendListAdapter friendAdapter;
private class FriendListAdapter extends BaseAdapter
{
class ViewHolder {
TextView text;
ImageView icon;
}
private LayoutInflater mInflater;
private Bitmap mOnlineIcon;
private Bitmap mOfflineIcon;
private FriendInfo[] friends = null;
public FriendListAdapter(Context context) {
super();
mInflater = LayoutInflater.from(context);
mOnlineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.greenstar);
mOfflineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.redstar);
}
public void setFriendList(FriendInfo[] friends)
{
this.friends = friends;
}
public int getCount() {
return friends.length;
}
public FriendInfo getItem(int position) {
return friends[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unneccessary calls
// to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is no need
// to reinflate it. We only inflate a new View when the convertView supplied
// by ListView is null.
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.friend_list_screen, null);
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
}
else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// Bind the data efficiently with the holder.
holder.text.setText(friends[position].userName);
holder.icon.setImageBitmap(friends[position].status == STATUS.ONLINE ? mOnlineIcon : mOfflineIcon);
return convertView;
}
}
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Broadcast receiver ", "received a message");
Bundle extra = intent.getExtras();
if (extra != null)
{
String action = intent.getAction();
if (action.equals(IMService.FRIEND_LIST_UPDATED))
{
// taking friend List from broadcast
//String rawFriendList = extra.getString(FriendInfo.FRIEND_LIST);
//FriendList.this.parseFriendInfo(rawFriendList);
FriendList.this.updateData(FriendController.getFriendsInfo(),
FriendController.getUnapprovedFriendsInfo());
}
}
}
};
public MessageReceiver messageReceiver = new MessageReceiver();
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((IMService.IMBinder)service).getService();
FriendInfo[] friends = FriendController.getFriendsInfo(); //imService.getLastRawFriendList();
if (friends != null) {
FriendList.this.updateData(friends, null); // parseFriendInfo(friendList);
}
setTitle(imService.getUsername() + "'s friend list");
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(FriendList.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_screen);
friendAdapter = new FriendListAdapter(this);
}
public void updateData(FriendInfo[] friends, FriendInfo[] unApprovedFriends)
{
if (friends != null) {
friendAdapter.setFriendList(friends);
setListAdapter(friendAdapter);
}
if (unApprovedFriends != null)
{
NotificationManager NM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (unApprovedFriends.length > 0)
{
String tmp = new String();
for (int j = 0; j < unApprovedFriends.length; j++) {
tmp = tmp.concat(unApprovedFriends[j].userName).concat(",");
}
Notification notification = new Notification(R.drawable.stat_sample,
getText(R.string.new_friend_request_exist),
System.currentTimeMillis());
//Intent i = new Intent(this, UnApprovedFriendList.class);
// i.putExtra(FriendInfo.FRIEND_LIST, tmp);
// PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
// i, 0);
// notification.setLatestEventInfo(this, getText(R.string.new_friend_request_exist),
// "You have new friend request(s)",
// contentIntent);
NM.notify(R.string.new_friend_request_exist, notification);
}
else
{
// if any request exists, then cancel it
NM.cancel(R.string.new_friend_request_exist);
}
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, Messaging.class);
FriendInfo friend = friendAdapter.getItem(position);
if (friend.status == STATUS.ONLINE)
{
i.putExtra(FriendInfo.USERNAME, friend.userName);
i.putExtra(FriendInfo.PORT, friend.port);
i.putExtra(FriendInfo.IP, friend.ip);
startActivity(i);
}
else
{
Toast.makeText(FriendList.this, R.string.user_offline, Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPause()
{
unregisterReceiver(messageReceiver);
unbindService(mConnection);
super.onPause();
}
#Override
protected void onResume()
{
super.onResume();
bindService(new Intent(FriendList.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
//i.addAction(IMService.TAKE_MESSAGE);
i.addAction(IMService.FRIEND_LIST_UPDATED);
registerReceiver(messageReceiver, i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, ADD_NEW_FRIEND_ID, 0, R.string.add_new_friend);
menu.add(0, EXIT_APP_ID, 0, R.string.exit_application);
return result;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item)
{
switch(item.getItemId())
{
case ADD_NEW_FRIEND_ID:
{
// Intent i = new Intent(FriendList.this, AddFriend.class);
// startActivity(i);
return true;
}
case EXIT_APP_ID:
{
imService.exit();
finish();
return true;
}
}
return super.onMenuItemSelected(featureId, item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
Roster roster = XMPPConnection.getRoster();
Collection<RosterEntry> entries= roster.getEntries();
ProviderManager.getInstance().addIQProvider("vCard", "vcard-temp",
new VCardProvider());
VCard card = null;
for (RosterEntry entry : entries) {
card = new VCard();
Presence presencek= roster.getPresence(entry.getUser());
try {
card.load(Main.conn, entry.getUser());
} catch (Exception e) {
e.printStackTrace();
}
String jid = entry.getUser();
String name = card.getField("FN");
String status = presencek.getType().name();
Log.d("Prescence", "" + presencek.getType().name());// //num one log
byte[] imgs = card.getAvatar();
if (imgs != null) {
int len = imgs.length;
Bitmap img = BitmapFactory.decodeByteArray(imgs, 0, len);
}
use Smack(XMPP) protocol.
A quick tutorial available here.
Good tutorial for XMPP implementation in android.

Categories

Resources