ImageButton in GridView get click position? - android

I'm trying create a GridView with some ImageButtons but I can't make onClick of these ImageButtons. I want get these clicks to open other Activitys/Fragments but I can't get position of ImageButton to do it.
How could I get position of ImageButton to click ?
GridView
Adapter XML
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/llPrincipal">
<ImageButton
android:id="#+id/ibPlano"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="fitXY"
android:background="#00000000"
android:focusable="false"
/>
<TextView
android:id="#+id/tvPlano"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:gravity="center"
/>
</LinearLayout>
PrincipalFrag
public class PrincipalFrag extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener{
private List<Permissoes> permissoesTela = new ArrayList<Permissoes>();
private GridView gridView;
private PrincipalAdapter principalAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.principal_frag, container, false);
gridView = (GridView)view.findViewById(R.id.gridView);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
principalAdapter = new PrincipalAdapter(getView().getContext(), getPermissoesTela());
gridView.setAdapter(principalAdapter);
}
#Override
public void onClick(View v) {
}
private List<Permissoes> getPermissoesTela(){
////agenda, despesa, enviar, alterar estoque bloqueados
Usuario usuario = KontroleConfigs.PESSOA;
//venda
Permissoes venda = new Permissoes();
venda.setVenda(usuario.getPlano().getPermissoes().getVenda());
//agenda
Permissoes agenda = new Permissoes();
agenda.setAgenda(usuario.getPlano().getPermissoes().getAgenda());
//cadastro
Permissoes cadastro = new Permissoes();
cadastro.setCadastro(1);
//despesas
Permissoes despesas = new Permissoes();
despesas.setLancamento_dispesas(usuario.getPlano().getPermissoes().getLancamento_dispesas());
//enviar
Permissoes enviar = new Permissoes();
enviar.setEnviar_relatorio_txt(usuario.getPlano().getPermissoes().getEnviar_relatorio_txt());
//meus dados
Permissoes meusDados = new Permissoes();
meusDados.setMeusDados(1);
//recebimentos pendentes
Permissoes recebimentosPendentes = new Permissoes();
recebimentosPendentes.setRecebimentos_pendentes(usuario.getPlano().getPermissoes().getRecebimentos_pendentes());
//entregas pendentes
Permissoes entregasPendentes = new Permissoes();
entregasPendentes.setEntregas_pendentes(usuario.getPlano().getPermissoes().getEntregas_pendentes());
//alterar estoque
Permissoes alterarEstoque = new Permissoes();
alterarEstoque.setAlterar_estoque(usuario.getPlano().getPermissoes().getAlterar_estoque());
permissoesTela.add(venda);
permissoesTela.add(agenda);
permissoesTela.add(cadastro);
permissoesTela.add(despesas);
permissoesTela.add(enviar);
permissoesTela.add(meusDados);
permissoesTela.add(recebimentosPendentes);
permissoesTela.add(entregasPendentes);
permissoesTela.add(alterarEstoque);
return permissoesTela;
}
#Override
public void onPause() {
super.onPause();
CustomVolleySingleton.getInstance().cancelPendingRequests(CustomVolleySingleton.TAG);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("POSITION BUTTON IN GRID VIEW->", position + "");
}
}
PrincipalAdapter
public class PrincipalAdapter extends BaseAdapter {
private Context context;
private List<Permissoes> lista;
public PrincipalAdapter(Context context, List<Permissoes> lista) {
this.context = context;
this.lista = lista;
}
#Override
public int getCount() {
return lista.size();
}
#Override
public Object getItem(int position) {
return lista.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
Usuario usuario = KontroleConfigs.PESSOA;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.principal_adapter, parent, false);
viewHolder.llPrincipal = (LinearLayout) convertView.findViewById(R.id.llPrincipal);
viewHolder.ibPlano = (ImageButton) convertView.findViewById(R.id.ibPlano);
viewHolder.tvPlano = (TextView) convertView.findViewById(R.id.tvPlano);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder)convertView.getTag();
}
//permissoes
Permissoes p = lista.get(position);
//plano lite
////agenda, despesa, enviar, alterar estoque bloqueados
if(usuario.getPlano().getNome().contains("Bronze Lite")){
if(p.getVenda() != null){
if(p.getVenda() > 0){
viewHolder.ibPlano.setImageResource(R.drawable.vendas);
viewHolder.ibPlano.setEnabled(true);
}else{
viewHolder.ibPlano.setImageResource(R.drawable.vendas_2);
viewHolder.ibPlano.setEnabled(false);
}
viewHolder.tvPlano.setText("Vendas");
}else if(p.getAgenda() != null){
if(p.getAgenda() > 0){
viewHolder.ibPlano.setImageResource(R.drawable.agenda);
viewHolder.ibPlano.setEnabled(true);
}else{
viewHolder.ibPlano.setImageResource(R.drawable.agenda_2);
viewHolder.ibPlano.setEnabled(false);
}
viewHolder.tvPlano.setText("Agendas");
}else if(p.getCadastro() != null){
if(p.getCadastro() > 0){
viewHolder.ibPlano.setImageResource(R.drawable.cadastro);
viewHolder.ibPlano.setEnabled(true);
}else{
viewHolder.ibPlano.setImageResource(R.drawable.cadastro_2);
viewHolder.ibPlano.setEnabled(false);
}
viewHolder.tvPlano.setText("Cadastro");
}else if(p.getLancamento_dispesas() != null){
if(p.getLancamento_dispesas() > 0){
viewHolder.ibPlano.setImageResource(R.drawable.despesas);
viewHolder.ibPlano.setEnabled(true);
}else{
viewHolder.ibPlano.setImageResource(R.drawable.despesas_2);
viewHolder.ibPlano.setEnabled(false);
}
viewHolder.tvPlano.setText("Despesas");
}else if(p.getEnviar_relatorio_txt() != null){
if(p.getEnviar_relatorio_txt() > 0){
viewHolder.ibPlano.setImageResource(R.drawable.enviar);
viewHolder.ibPlano.setEnabled(true);
}else{
viewHolder.ibPlano.setImageResource(R.drawable.enviar_2);
viewHolder.ibPlano.setEnabled(false);
}
viewHolder.tvPlano.setText("Enviar");
}else if(p.getMeusDados() != null){
if(p.getMeusDados() > 0){
viewHolder.ibPlano.setImageResource(R.drawable.meus_dados);
viewHolder.ibPlano.setEnabled(true);
}else{
viewHolder.ibPlano.setImageResource(R.drawable.meus_dados_2);
viewHolder.ibPlano.setEnabled(false);
}
viewHolder.tvPlano.setText("Meus Dados");
}else if(p.getRecebimentos_pendentes() != null){
if(p.getRecebimentos_pendentes() > 0){
viewHolder.ibPlano.setImageResource(R.drawable.recebimentos_pendentes);
viewHolder.ibPlano.setEnabled(true);
}else{
viewHolder.ibPlano.setImageResource(R.drawable.recebimentos_pendentes_2);
viewHolder.ibPlano.setEnabled(true);
}
viewHolder.tvPlano.setText("Recebimentos Pendentes");
}else if(p.getEntregas_pendentes() != null){
if(p.getEntregas_pendentes() > 0){
viewHolder.ibPlano.setImageResource(R.drawable.entregas_pendentes);
viewHolder.ibPlano.setEnabled(true);
}else{
viewHolder.ibPlano.setImageResource(R.drawable.entregas_pendentes_2);
viewHolder.ibPlano.setEnabled(true);
}
viewHolder.tvPlano.setText("Entregas Pendentes");
}else if(p.getAlterar_estoque() != null){
if(p.getAlterar_estoque() > 0){
viewHolder.ibPlano.setImageResource(R.drawable.alterar_estoque);
viewHolder.ibPlano.setEnabled(true);
}else{
viewHolder.ibPlano.setImageResource(R.drawable.alterar_estoque_2);
viewHolder.ibPlano.setEnabled(true);
}
viewHolder.tvPlano.setText("Alterar Estoque");
}
}//final plano lite
return convertView;
}
/** pattern view holder */
private static class ViewHolder{
LinearLayout llPrincipal;
ImageButton ibPlano;
TextView tvPlano;
}
}

set onClick for your ImageButton in getView() method like this:
viewHolder.ibPlano.setOnClickListener(new OnClickListener(){
public void onClick(View v){
// you can get position of clicked item here(you have it in getView argument)
}
});

Related

How to update a textview of adapter in an activity

I have a textview in my adapter class and I have to update the textview in activity since I am getting the result in activity. How can i do that?
This is my activity class. I want to update textview tv2 with "some text". I have even tried updating textview in adapter but I wasn't successful in doing that.
public class TextviewActivity extends AppCompatActivity {
ListView lvText;
ArrayList<TextviewPojo> textviewPojos = new ArrayList<>();
TextviewAdapter textviewAdapter;
TextView tv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_textview);
lvText = findViewById(R.id.lvText);
textviewAdapter = new TextviewAdapter(textviewPojos,this);
lvText.setAdapter(textviewAdapter);
textviewPojos.add(new TextviewPojo("first text","second text"));
textviewPojos.add(new TextviewPojo("first text","second text"));
}
}
This is my adapter class.
public class TextviewAdapter extends BaseAdapter {
ArrayList<TextviewPojo> textviewPojos = new ArrayList<>();
Context context;
public TextviewAdapter(ArrayList<TextviewPojo> textviewPojos, Context context) {
this.textviewPojos = textviewPojos;
this.context = context;
}
#Override
public int getCount() {
return textviewPojos.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = LayoutInflater.from(context).inflate(R.layout.item_textview,parent,false);
}
TextView tv1,tv2;
TextviewPojo textviewPojo = textviewPojos.get(position);
tv1 = convertView.findViewById(R.id.tv1);
tv2 = convertView.findViewById(R.id.tv2);
tv1.setText(textviewPojo.getText1());
tv2.setText(textviewPojo.getText2());
return convertView;
}
}
Below is my item layout. - item_textview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv1"
android:textSize="30sp"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="filename1"/>
<TextView
android:id="#+id/tv2"
android:layout_weight="1"
android:textSize="30sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="filename2"/>
</LinearLayout>
Try this code do not need to take reference of tvDocName again in selected file just change this code in selected file
public class DocumentActivity extends AppCompatActivity {
ImageView toolbar_back;
TextView next;
RecyclerView recyclerView;
ArrayList<Survey_vehiclepojo> mylist = new ArrayList();
My_document_adapter adapter;
TextView tvDocName;
View view;
private int position;
String displayName = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_document);
view = getLayoutInflater().inflate(R.layout.activity_document, null);
tvDocName = findViewById(R.id.tvDocName);
// toolbar_back=(ImageView)findViewById(R.id.toolbar_back);
// toolbar_back.setOnClickListener(this);
// next=(TextView)findViewById(R.id.next);
// next.setOnClickListener(this);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
mylist.add(new Survey_vehiclepojo("Pay Slip"));
mylist.add(new Survey_vehiclepojo("Insurance"));
mylist.add(new Survey_vehiclepojo("NA Certificate"));
adapter = new My_document_adapter(DocumentActivity.this, mylist);
recyclerView.setAdapter(adapter);
}
/* #Override
public void onClick(View v) {
switch (v.getId()){
*//*case R.id.toolbar_back:
finish();
break;
case R.id.next:
Intent n=new Intent(DocumentActivity.this,Loan_checklistActivity.class);
startActivity(n);
break;*//*
}
}*/
public void Document(int pos) {
position = pos;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 100);
tvDocName.setText(mylist.get(pos).getPay_slip());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
selectedFile(data);
}
private void selectedFile(Intent data) {
if (data != null) {
Uri uri = data.getData();
String uriString = null;
if (uri != null) {
uriString = uri.toString();
}
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
if (uriString != null) {
if (uriString.startsWith("content://")) {
try (Cursor cursor = DocumentActivity.this.getContentResolver().query(uri, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Toast.makeText(this, "display" + displayName, Toast.LENGTH_SHORT).show();
// Toast.makeText(this, "path is" +path, Toast.LENGTH_SHORT).show();
// My_document_adapter.Filename(displayName, position);
// ViewGroup v = (ViewGroup) getLayoutInflater().inflate(R.layout.activity_document, null);
// tvDocName = v.findViewById(R.id.tvDocName);
tvDocName.setText(displayName);
adapter.notifyDataSetChanged();
}
}
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
Toast.makeText(this, "display start " + displayName, Toast.LENGTH_SHORT).show();
// ViewGroup v = (ViewGroup) getLayoutInflater().inflate(R.layout.activity_document, null);
// tvDocName = v.findViewById(R.id.tvDocName);
tvDocName.setText(displayName);
adapter.notifyDataSetChanged();
}
}
}
}
in your adapter class change this line
View v = LayoutInflater.from(context).inflate(R.layout.item_document, viewGroup, false);
call this where you update you list trough your adpater
public void refresh(ArrayList<TextviewPojos> textviewPojos){
this.textviewPojo=textviewPojos;
notifyDataSetChanged();
}

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

UltimateRecycleView : SetLoadMoreView is Not Working

I am currently working with Android and UltimateRecycleView. I manage to make the ultimaterecycleview working, but when I tried to use the load more functionality, the bottom progress bar is not showing (although the data is loaded). Anyone has experienced this problem? Can you please help me to find out what is wrong?
Here is the code :
--- Adapter ---
public class ListPendingAdapter extends UltimateViewAdapter<ListPendingAdapter.PendingViewHolder> {
private Context context;
private List<Queue> queues;
public ListPendingAdapter(Context context, List<Queue> queues) {
this.context = context;
this.queues = queues;
}
#Override
public PendingViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.pending_list, parent, false);
PendingViewHolder vh = new PendingViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(PendingViewHolder holder, int position) {
TextView nodata = (TextView) ((Activity) context).findViewById(R.id.nodata);
if(queues.size() <= 0){
nodata.setVisibility(View.VISIBLE);
} else {
nodata.setVisibility(View.GONE);
User user = new User(queues.get(position).getQueuer());
if (user.getProfilePicture() == null) {
holder.photo.setImageDrawable(context.getResources().getDrawable(R.drawable.default_photo));
} else {
ImageUtil.setParseFileImageToView(context, user.getProfilePicture(), holder.photo);
}
holder.name.setText(user.getFullname());
holder.totalPerson.setText(Integer.toString(queues.get(position).getTotalPax()));
holder.timeQueue.setText(DateUtil.formatDateIntoTimeString(queues.get(position).getCreatedAt()));
attachButtonClickListener(holder.accept, true, position, holder.parent);
attachButtonClickListener(holder.reject, false, position, holder.parent);
CustomerUtil.attachUsernameListener((Activity) context, holder.name, queues.get(position));
CustomerUtil.attachProfpicListener((Activity) context, holder.photo, queues.get(position));
}
}
#Override
public int getItemCount() {
int size = (queues == null ? 0 : queues.size());
return size;
}
#Override
public PendingViewHolder onCreateViewHolder(ViewGroup viewGroup) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.pending_list, viewGroup, false);
PendingViewHolder vh = new PendingViewHolder(v);
return vh;
}
#Override
public PendingViewHolder getViewHolder(View view) {
return new PendingViewHolder(view);
}
#Override
public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup viewGroup) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.custom_bottom_progressbar, viewGroup, false);
return new RecyclerView.ViewHolder(view) {
};
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
}
#Override
public long generateHeaderId(int position) {
if (getItem(position).get("objectId").toString().length() > 0)
return (getItem(position).get("objectId").toString()).charAt(0);
else return -1;
}
#Override
public int getAdapterItemCount() {
int size = (queues == null ? 0 : queues.size());
return size;
}
public Queue getItem(int position) {
if (customHeaderView != null)
position--;
if (position < queues.size())
return queues.get(position);
else return null;
}
private void attachButtonClickListener(Button button, final boolean isAccept, final int position, final View parent){
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callPendingProcess(isAccept, position, parent);
}
});
}
private void callPendingProcess(final boolean isAccept, final int position, final View parent){
ProcessPending processPending = new ProcessPending(context, this, isAccept, position, parent);
processPending.execute();
}
public List<Queue> getDataset(){
return queues;
}
public static class PendingViewHolder extends UltimateRecyclerviewViewHolder {
public CircleImageView photo;
public TextView name;
public TextView totalPerson;
public TextView timeQueue;
public Button accept;
public Button reject;
public View parent;
public PendingViewHolder(View v) {
super(v);
parent = v;
photo = (CircleImageView) v.findViewById(R.id.photo);
name = (TextView) v.findViewById(R.id.cust_name);
totalPerson = (TextView) v.findViewById(R.id.total_cust);
timeQueue = (TextView) v.findViewById(R.id.time_queue);
accept = (Button) v.findViewById(R.id.accept_btn);
reject = (Button) v.findViewById(R.id.reject_btn);
}
}
}
--- Async Task (where I set the adapter to listview) ---
public class LoadPendingCustomer extends AsyncTask<Void, Void, List<Queue>> {
private Context context;
private Activity activity;
private ProgressBar pb;
private View view;
private View layout;
private int skipCount;
private boolean isLoadMore;
public LoadPendingCustomer(Context context, View layout, int skipCount, boolean isLoadMore) {
this.context = context;
this.activity = (Activity) context;
this.layout = layout;
this.skipCount = skipCount;
this.isLoadMore = isLoadMore;
this.pb = (ProgressBar) layout.findViewById(R.id.pending_progress);
this.view = layout.findViewById(R.id.pending_list_container);
}
#Override
protected void onPreExecute() {
if(!isLoadMore) {
ProgressUtil.showProgress(true, view, pb, context);
}
}
#Override
protected List<Queue> doInBackground(Void... arg0) {
List<Queue> queues = null;
try {
List<String> statuses = new ArrayList<String>();
statuses.add(Queue.STATUS_PENDING_APPROVAL);
queues = QueueDao.getCustomersBasedOnStatus(statuses, skipCount);
} catch (ParseException e) {
Log.w(MainActivity.TAG, "Error while retrieving pending queues", e);
}
return queues;
}
#Override
protected void onPostExecute(List<Queue> results) {
TextView nodata = (TextView) layout.findViewById(R.id.nodata);
if(results == null){
nodata.setVisibility(View.VISIBLE);
} else {
if (results.size() <= 0) {
if(!isLoadMore) {
nodata.setVisibility(View.VISIBLE);
}
} else {
nodata.setVisibility(View.GONE);
UltimateRecyclerView queueList = (UltimateRecyclerView) layout.findViewById(R.id.pendinglist);
if(!isLoadMore || queueList.getAdapter() == null){
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(activity);
ListPendingAdapter listPendingAdapter = new ListPendingAdapter(context, results);
queueList.setLayoutManager(layoutManager);
queueList.setAdapter(listPendingAdapter);
} else {
ListPendingAdapter listPendingAdapter = (ListPendingAdapter) queueList.getAdapter();
listPendingAdapter.getDataset().addAll(results);
listPendingAdapter.notifyDataSetChanged();
}
setLoadMore(queueList);
}
}
if(!isLoadMore) {
ProgressUtil.showProgress(false, view, pb, context);
}
}
private void setLoadMore(final UltimateRecyclerView queueList){
queueList.reenableLoadmore();
queueList.setLoadMoreView(R.layout.custom_bottom_progressbar);
queueList.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
#Override
public void loadMore(int i, int i1) {
LoadPendingCustomer loadPendingCustomer = new LoadPendingCustomer(context, layout, skipCount + 10, true);
loadPendingCustomer.execute();
}
});
}
}
--- fragment xml ---
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"
tools:context=".fragments.QueueFragment">
<!-- TODO: Update blank fragment layout -->
<ProgressBar
android:id="#+id/pending_progress"
style="?android:attr/progressBarStyleLarge"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:visibility="gone" />
<LinearLayout
android:id="#+id/pending_list_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/nodata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/nodata"
android:visibility="gone"/>
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/pending_swipe_refresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.marshalchen.ultimaterecyclerview.UltimateRecyclerView
android:id="#+id/pendinglist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"/>
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
</RelativeLayout>
--- custom_bottom_progressbar.xml ---
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/bottomPB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffff">
<ProgressBar
android:layout_width="30dp"
android:layout_height="30dp"
android:id="#+id/bottom_progress_bar"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/loading"
android:layout_below="#+id/bottom_progress_bar"
android:layout_marginTop="2dp"
android:gravity="center"/>
</RelativeLayout>
Please help me. Thanks in advance...

Null Pointer Exception at Imageview in Custom List View

I have a custom list view with a TextView and three ImageViews. On click of image view I want to start a new activity and pass the data of specific position to next activity. But I am getting null pointer exception.
I have use this for refernce http://jmsliu.com/2444/click-button-in-listview-and-get-item-position.html
Here is my code. This is main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employees);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("Manage Employees");
nPregress = (ProgressBar) findViewById(R.id.toolbar_progress_bar);
nPregress.setVisibility(View.GONE);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mainList = (ListView) findViewById(R.id.manageemployeeList);
employee1 = new ArrayList<Pojo>();
tii = new ArrayList<String>();
SharedPreferences prefs = getSharedPreferences("MyPref4", MODE_PRIVATE);
Set<String> set1 = prefs.getStringSet("employeename", null);
if (set1 != null ) {
List<String> nameList = new ArrayList<String>(0);
nameList.addAll(set1);
for (int i = 0; i < set1.size(); i++) {
pojo = new Pojo();
pojo.setMgEmpName(nameList.get(i));
employee1.add(pojo);
Log.e("namemmee0", "" + nameList.get(i));
}
mainAdapter = new EmployeesAdapter(EmployeesActivity.this, employee1);
mainList.setAdapter(mainAdapter);
} else {
new NetCheck().execute();
}
new NetCheck().execute();
emp_edit = (ImageView) findViewById(R.id.imgedit);
emp_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
mainList = (ListView) parentRow.getParent();
final int position = mainList.getPositionForView(parentRow);
String emp_name = employee1.get(position).getMgEmpName().toString();
Intent i = new Intent(EmployeesActivity.this, EditEmployee.class);
i.putExtra("empname", emp_name);
startActivity(i);
}
});
}
I am getting exception at this line
emp_edit.setOnClickListener(new View.OnClickListener()
How can i do this? Please help me.
This is my Adapter. I have tried onClickListener in adpter also But i am not gtting proper data in next activity.. I get same value even if i select different list view items
public class EmployeesAdapter extends BaseAdapter {
TextView categoryName;
Pojo pojo;
private Context activity1;
ArrayList<Pojo> data1;
private ArrayList<Pojo> arraylist1 = null;
public static LayoutInflater inflater;
ImageView edit, delete, historyy;
String del_empid;
public EmployeesAdapter(Context ctx, ArrayList<Pojo> employee1) {
// TODO Auto-generated constructor stub
activity1 = ctx;
data1 = employee1;
inflater = (LayoutInflater) activity1
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arraylist1 = new ArrayList<Pojo>();
this.arraylist1.addAll(data1);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data1.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
v = inflater.inflate(R.layout.manage_emp_list, parent, false);
pojo = data1.get(position);
categoryName = (TextView) v.findViewById(R.id.employeeName);
categoryName.setText(pojo.getMgEmpName());
edit = (ImageView) v.findViewById(R.id.imgedit);
delete = (ImageView) v.findViewById(R.id.imgdelete);
historyy = (ImageView) v.findViewById(R.id.imgHistory);
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity1, EditEmployee.class);
intent.putExtra("empname", "" + pojo.getMgEmpName());
intent.putExtra("empmobile", "" + pojo.getMgEmpContact());
intent.putExtra("empemail", "" + pojo.getMgEmpEmail());
intent.putExtra("empappcost", "" + pojo.getMgEmpAppCost());
activity1.startActivity(intent);
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
del_empid = pojo.getMgEmp_id();
new NetCheck().execute();
}
});
historyy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity1, MainActivity.class);
activity1.startActivity(intent);
}
});
return v;
}
manage_emp_list of the custom list view
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/employeeName"
android:textColor="#000000"
android:textSize="18dp"
android:padding="5dp"
android:layout_marginLeft="5dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgdelete"
android:src="#drawable/delete32"
android:layout_marginRight="12dp"
android:layout_marginEnd="12dp"
android:layout_alignBottom="#+id/employeeName"
android:layout_toLeftOf="#+id/imgedit"
android:layout_toStartOf="#+id/imgedit"
android:clickable="true"
android:onClick="delete_empoyee"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgedit"
android:layout_marginRight="15dp"
android:layout_marginEnd="15dp"
android:src="#drawable/edit32"
android:layout_alignTop="#+id/imgdelete"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:clickable="true"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgHistory"
android:src="#drawable/history32"
android:clickable="true"
android:onClick="employee_history"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/imgdelete"
android:layout_toStartOf="#+id/imgdelete"
/>
Try this, There may be position mismatch when store it locally
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity1, EditEmployee.class);
intent.putExtra("empname", "" + data1.get(position).getMgEmpName());
intent.putExtra("empmobile", "" + data1.get(position).getMgEmpContact());
intent.putExtra("empemail", "" + data1.get(position).getMgEmpEmail());
intent.putExtra("empappcost", "" + data1.get(position).getMgEmpAppCost());
activity1.startActivity(intent);
}
});
Your getView() method should look like this in your adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pojo = data1.get(position);
ViewHolder holder;
if (pojo != null) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.manage_emp_list, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.categoryName.setText(pojo.getMgEmpName());
//holder.edit.setOnClickListener()...
//holder.delete.setOnclickListener()...
}
return convertView;
}
And add a static class in to your Adapter:
static class ViewHolder {
TextView categoryName;
ImageView edit;
ImageView delete;
ImageView historyy;
public ViewHolder(View view) {
categoryName = (TextView) v.findViewById(R.id.employeeName);
edit = (ImageView) v.findViewById(R.id.imgedit);
delete = (ImageView) v.findViewById(R.id.imgdelete);
historyy = (ImageView) v.findViewById(R.id.imgHistory);
}
}

Button's click in listiview not working properly

In my listview i set two buttons and one edittext but it is not working properly,the view of my buttons and edittext in listview is look like this
Button1 Edittext Button2
in my edittext i set 1,and Button1 is for decrement or minus and Button2 for increment or plus,but the issue is in every listitem it is not working properly,if i have three items in my listview,and if i increment in first item the operation is performing in third item,,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.list_view_addtocart, container, false);
totvalues=(TextView)rootView.findViewById(R.id.totaldisp);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
edtcopupon=(EditText)rootView.findViewById(R.id.edt_coupon);
btn_applycoupon=(Button)rootView.findViewById(R.id.aplycoupoon);
btn_applycoupon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
list=(ListView)rootView.findViewById(R.id.list_addtocart);
plcordr=(Button)rootView.findViewById(R.id.plcordr);
plcordr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Placeorder tf = new Placeorder();
Bundle bundle = new Bundle();
tf.setArguments(bundle);
android.app.FragmentManager fm = getActivity().getFragmentManager();
android.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container_body, tf);
ft.setTransition(android.support.v4.app.FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
});
ArrayList<ContactListItems> contactList = new ArrayList<ContactListItems>();
contactList.clear();
String query = "SELECT * FROM PHONE_CONTACTS ";
Cursor c1 = SqlHandler.selectQuery(query);
if (c1 != null & c1.getCount() != 0) {
if (c1.moveToNext()) {
do {
contactListItems = new ContactListItems();
contactListItems.setSlno(c1.getString(c1
.getColumnIndex("slno")));
contactListItems.setName(c1.getString(c1
.getColumnIndex("name")));
contactListItems.setPhone(c1.getString(c1
.getColumnIndex("phone")));
contactListItems.setSizes(c1.getString(c1
.getColumnIndex("sizes")));
contactListItems.setQtys(c1.getString(c1
.getColumnIndex("qtys")));
contactList.add(contactListItems);
} while (c1.moveToNext());
}
}
c1.close();
contactListAdapter = new ContactListAdapter(getActivity(), contactList);
list.setAdapter(contactListAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
}
});
return rootView;
}
public class ContactListAdapter extends BaseAdapter {
Context context;
ViewHolder holder;
ArrayList<ContactListItems> contactList;
String dollars = "\u0024";
public ContactListAdapter(Context context, ArrayList<ContactListItems> list) {
this.context = context;
contactList = list;
}
#Override
public int getCount() {
return contactList.size();
}
#Override
public Object getItem(int position) {
return contactList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(getActivity()).inflate(R.layout.list_item_addtocart, null);
holder.propic = (ImageView) convertView.findViewById(R.id.propicaccept);
holder.tvSlNo = (TextView) convertView.findViewById(R.id.txt_size);
holder.tvName = (TextView) convertView.findViewById(R.id.proprice_addtocart);
holder.tvPhone = (TextView) convertView.findViewById(R.id.proname_addtocart);
holder.tvsizes = (TextView) convertView.findViewById(R.id.txt_sizes);
holder._decrease = (Button)convertView.findViewById(R.id.minuss_addtocart);
holder.mBTIncrement = (Button)convertView.findViewById(R.id.plus_addtocart);
holder._value = (EditText)convertView.findViewById(R.id.edt_procount_addtocart);
holder.mBTIncrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//increment();
int mValue = Integer.parseInt(holder._value.getText().toString());
mValue++;
quntity++;
tots = pric * quntity;
System.out.println("INCRESE VALUES" + tots);
totvalues.setText(String.valueOf(tots));
holder._value.setText("" + mValue);
}
});
holder._decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//decrement();
int mValue = Integer.parseInt(holder._value.getText().toString());
mValue--;
quntity--;
tots = pric * quntity;
System.out.println("INCRESE VALUES" + tots);
totvalues.setText(String.valueOf(tots));
if (mValue < 0) {
System.out.println("not valid");
holder._decrease.setEnabled(false);
} else {
holder._value.setText("" + mValue);
}
}
});
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.tvName.setText(dollars+contactListItems.getName());
holder.tvPhone.setText(contactListItems.getPhone());
holder.tvsizes.setText(contactListItems.getSizes());
holder._value.setText(contactListItems.getQtys());
quntity=Float.parseFloat(contactListItems.getQtys());
pric=Float.parseFloat(contactListItems.getName());
tots=pric*quntity;
totvalues.setText(String.valueOf(tots));
System.out.println("QTYSSS>>" + quntity);
System.out.println("PRICCC>>" + pric);
// float aditya=+tots;
System.out.println("TOTTTT>>" + tots);
//aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.ic_launcher);
return convertView;
}
class ViewHolder{
ImageView propic;
TextView tvSlNo;
TextView tvName;
TextView tvPhone;
Button mBTIncrement;
TextView tvsizes;
Button _decrease;
public EditText _value;
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/rectback"
>
<ImageView
android:layout_width="70dp"
android:layout_height="100dp"
android:id="#+id/img_addtocart"
android:src="#drawable/productfirst"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/relfirsrt"
android:layout_toRightOf="#+id/img_addtocart"
android:layout_above="#+id/relativeLayout"
android:layout_alignParentTop="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/proname_addtocart"
android:textAppearance="?android:attr/textAppearanceMedium"
android:maxLength="13"
android:textColor="#android:color/black"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txt_size"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txt_sizes"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/img_addtocart"
android:layout_toRightOf="#+id/img_addtocart"
android:layout_toEndOf="#+id/img_addtocart"
android:id="#+id/relativeLayout">
<Button
android:layout_width="40dp"
android:layout_height="29dp"
android:id="#+id/minuss_addtocart"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#drawable/minusbox"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/edt_procount_addtocart"
android:layout_toStartOf="#+id/edt_procount_addtocart" />
<EditText
android:layout_width="40dp"
android:layout_height="29dp"
android:id="#+id/edt_procount_addtocart"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#drawable/inputbox"
android:inputType="number"
android:gravity="center"
android:text="0"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/plus_addtocart"
android:layout_toStartOf="#+id/plus_addtocart" />
<Button
android:layout_width="40dp"
android:layout_height="29dp"
android:id="#+id/plus_addtocart"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#drawable/addbox"
android:layout_alignParentTop="true"
android:focusable="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/proprice_addtocart"
android:gravity="center_vertical"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</RelativeLayout>
Write your onClick listener and tag assigning code outside the if-else block.
if (convertView == null) {
}
else {
}
holder.position = position;
holder.mBTIncrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//increment();
int mValue = Integer.parseInt(holder._value.getText().toString());
mValue++;
quntity++;
tots = pric * quntity;
System.out.println("INCRESE VALUES" + tots);
totvalues.setText(String.valueOf(tots));
holder._value.setText("" + mValue);
}
});
holder._decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//decrement();
int mValue = Integer.parseInt(holder._value.getText().toString());
mValue--;
quntity--;
tots = pric * quntity;
System.out.println("INCRESE VALUES" + tots);
totvalues.setText(String.valueOf(tots));
if (mValue < 0) {
System.out.println("not valid");
holder._decrease.setEnabled(false);
} else {
holder._value.setText("" + mValue);
}
}
});
You need to base your logic on the position of the click, because the adapter may refresh itself after the click and change the position;
public class ContactListAdapter extends BaseAdapter {
Context context;
ViewHolder holder;
ArrayList<ContactListItems> contactList;
ArrayList<Integer> values;
String dollars = "\u0024";
public ContactListAdapter(Context context, ArrayList<ContactListItems> list) {
this.context = context;
contactList = list;
values = new ArrayList<>();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new ViewHolder();
values.add(contactListItems.getQtys());
convertView = LayoutInflater.from(getActivity()).inflate(R.layout.list_item_addtocart, null);
holder.propic = (ImageView) convertView.findViewById(R.id.propicaccept);
holder.tvSlNo = (TextView) convertView.findViewById(R.id.txt_size);
holder.tvName = (TextView) convertView.findViewById(R.id.proprice_addtocart);
holder.tvPhone = (TextView) convertView.findViewById(R.id.proname_addtocart);
holder.tvsizes = (TextView) convertView.findViewById(R.id.txt_sizes);
holder._decrease = (Button)convertView.findViewById(R.id.minuss_addtocart);
holder.mBTIncrement = (Button)convertView.findViewById(R.id.plus_addtocart);
holder._value = (EditText)convertView.findViewById(R.id.edt_procount_addtocart);
holder.mBTIncrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = holder.position;
int mValue = Integer.parseInt(holder._value.getText().toString());
mValue++;
quntity++;
tots = pric * quntity;
System.out.println("INCRESE VALUES" + tots);
totvalues.setText(String.valueOf(tots));
values.set(position, mValue);
}
});
holder._decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = holder.position;
int mValue = Integer.parseInt(holder._value.getText().toString());
mValue--;
quntity--;
tots = pric * quntity;
System.out.println("INCRESE VALUES" + tots);
totvalues.setText(String.valueOf(tots));
values.set(position, mValue);
}
});
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.position = position;
holder.tvName.setText(dollars+contactListItems.getName());
holder.tvPhone.setText(contactListItems.getPhone());
holder.tvsizes.setText(contactListItems.getSizes());
int value = values.get(position);
if (value < 0) {
holder._decrease.setEnabled(false);
} else {
holder._value.setText("" + mValue);
}
quntity=Float.parseFloat(contactListItems.getQtys());
pric=Float.parseFloat(contactListItems.getName());
tots=pric*quntity;
totvalues.setText(String.valueOf(tots));
System.out.println("QTYSSS>>" + quntity);
System.out.println("PRICCC>>" + pric);
// float aditya=+tots;
System.out.println("TOTTTT>>" + tots);
//aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.ic_launcher);
return convertView;
}
class ViewHolder{
int position;
ImageView propic;
TextView tvSlNo;
TextView tvName;
TextView tvPhone;
Button mBTIncrement;
TextView tvsizes;
Button _decrease;
public EditText _value;
}
}
Try implementing adapter like below
private Context context;
private List<ContactListItems> items;
/**
* #param context
* #param groupList
*/
public TestListAdapter(Context context, List<ContactListItems> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.li_plus_minus, parent, false);
holder = new ViewHolder();
holder.plus = (Button) convertView.findViewById(R.id.plus);
holder.minus = (Button) convertView.findViewById(R.id.minus);
holder.et = (EditText) convertView.findViewById(R.id.editText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ContactListItems item = items.get(position);
holder.et.setText(String.valueOf(item.value));
holder.plus.setOnClickListener(new ClickListener(item));
holder.minus.setOnClickListener(new ClickListener(item));
return convertView;
}
class ClickListener implements View.OnClickListener {
private ContactListItems item;
public ClickListener(ContactListItems item) {
this.item = item;
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.minus) {
item.value--;
} else if (v.getId() == R.id.plus) {
item.value++;
}
notifyDataSetChanged();
}
}
class ViewHolder {
Button plus, minus;
EditText et;
}
Hope this helps
Add this line in your Customise view parent layout.
android:descendantFocusability="blocksDescendants"

Categories

Resources