adding textview dynamically without results - android

I'd like to show an activity as a dialog but this dialog will show a layout which is filled in dynamically from a database but I am getting no results.
package chintan.khetiya.sqlite.cursor;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class lista extends Activity {
private ListView lista;
DatabaseHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listado);
//SE HACE TODO EL PROCESO EJECUTANDO UNA FUNCION
Refresh();
lista.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position,long id) {
final int selected_row = position;
final String cliente = DameCliente(selected_row);
final int limite = DameConteo();
int i;
AlertDialog.Builder myDialog
= new AlertDialog.Builder(lista.this);
My problem is here
LinearLayout linear = (LinearLayout) findViewById(R.id.generar_text);
TextView text = new TextView(lista.this);
text.setText("hola");
Of course this is a test. I'll do a loop to create many more textviews but I need to build the first one and then loop more.
LayoutInflater inflater = getLayoutInflater();
myDialog.setView(inflater.inflate(R.layout.dialog, null));
myDialog.setTitle(cliente);
myDialog.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
}
});
myDialog.setNeutralButton("Eliminar Pedido", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
final int eliminar = selected_row + 1;
AlertDialog.Builder dialogoDentro = new AlertDialog.Builder(lista.this);
dialogoDentro.setTitle("Alerta !");
dialogoDentro.setMessage("Eliminar el Pedido ?");
dialogoDentro.setNeutralButton("Eliminar", new DialogInterface.OnClickListener( {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
db.Delete_Pedido(eliminar);
lista.this.Refresh();
}
});
dialogoDentro.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
}
});
dialogoDentro.show();
}
});
myDialog.show();
}
});
}
public void Refresh(){
int limite = DameConteo();// numero de columnas insertadas como productos
int numero_pedidos = NumeroPedidos();
//Toast.makeText(getApplicationContext(), "Valor Columna: " + ValorColumna(columna) + " -- Columna: " + columna + " -- Precio : " + ValorPrecio(columna), Toast.LENGTH_SHORT).show();
ArrayList<lista_entrada> datos = new ArrayList<lista_entrada>();
for (int a = 1; a <= numero_pedidos;a ++){
String pedidor = InfoPedidos(a).getString(1);
float iva = (float) 1.16;
int articulos = 0;
float subtotal = 0;
float total = 0;
for (int b=0; b<limite; b++){
String columna = DameColumna(b).toString();
articulos = articulos + ValorColumna(columna,a);
subtotal = subtotal + (ValorColumna(columna,a)*(ValorPrecio(columna)));
total = total + (float) (((ValorColumna(columna,a)*(ValorPrecio(columna)))) * iva);
}
datos.add(new lista_entrada(pedidor,"Pedido: " + articulos + " artículos", "Subtotal: $" + String.format("%.2f", subtotal), "Total: $" + String.format("%.2f", total)));
//}
}
lista = (ListView) findViewById(R.id.ListView_listado);
lista.setAdapter(new lista_adaptador(this, R.layout.entrada, datos){
#Override
public void onEntrada(Object entrada, View view) {
if (entrada != null) {
TextView nombre = (TextView) view.findViewById(R.id.nombre);
if (nombre != null)
nombre.setText(((lista_entrada) entrada).getNombre());
TextView articulos = (TextView) view.findViewById(R.id.articulos);
if (articulos != null)
articulos.setText(((lista_entrada) entrada).getArticulos());
TextView subtotal = (TextView) view.findViewById(R.id.subtotal);
if (subtotal != null)
subtotal.setText(((lista_entrada) entrada).getSubtotal());
TextView total = (TextView) view.findViewById(R.id.total);
if (total != null)
total.setText(((lista_entrada) entrada).getTotal());
}
}
});
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
Refresh();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Clientes:
finish();
startActivity(new Intent(this, Main_Screen.class));
return true;
case R.id.Productos:
finish();
startActivity(new Intent(this, Product_Screen.class));
return true;
case R.id.Nuevo_Pedido:
finish();
startActivity(new Intent(this, home_screen.class));
return true;
case R.id.listado_pedidos:
finish();
startActivity(new Intent(this, lista.class));
return true;
case R.id.salir:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public String DameCliente(int contact_name){
//product_data.clear();
db = new DatabaseHandler(this);
ArrayList<Pedido> pedido_array_from_db = db.Get_Pedido();
String cte_name = pedido_array_from_db.get(contact_name).get_contact_name();
return cte_name;
}
public int DameConteo(){
db = new DatabaseHandler(this);
int conteo = db.Get_Total_Products();
return conteo;
}
public int NumeroPedidos(){
db = new DatabaseHandler(this);
int numero = db.Get_Total_Pedido();
return numero;
}
public Cursor InfoPedidos(int id){
db = new DatabaseHandler(this);
Cursor cursor = db.Get_Pedido(id);
return cursor;
}
public String DameColumna(int columna_id){
db = new DatabaseHandler(this);
ArrayList<Columna> columna_array_from_db = db.Get_Columna();
String columna = columna_array_from_db.get(columna_id).get_columnaName();
return columna;
}
public int ValorColumna(String columna, int a){
String valor_a = String.valueOf(a);
db = new DatabaseHandler(this);
int valor = db.get_valor_columna(columna,valor_a);
return valor;
}
public float ValorPrecio(String columna){
db = new DatabaseHandler(this);
float valor = db.get_valor_precio(columna);
return valor;
}
}

Try this.
Change
LinearLayout linear = (LinearLayout) findViewById(R.id.generar_text);
TextView text = new TextView(lista.this);
text.setText("hola");
LayoutInflater inflater = getLayoutInflater();
myDialog.setView(inflater.inflate(R.layout.dialog, null));
to
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.dialog, null);
LinearLayout linear = (LinearLayout) view.findViewById(R.id.generar_text);
TextView text = new TextView(this);
text.setText("hola");
linear.addView(text);
myDialog.setView(view);

If you want to dynamically add Views to a ViewGroup (for example LinearLayout) the easiest thing you can do is to define the View (for example TextView) in a separate layout xml file.
for example
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:id="#id/label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lines="1"
android:textIsSelectable="true"
android:textAppearance="?android:attr/textAppearanceSmall"
/>
stored as /res/layout/mytextview.xml
Now in code where you want to put the Views dynamically instead of finding one by findViewById you inflate each time a new instance of the view for example:
LayoutInflater inflater = getLayoutInflater();
LinearLayout rootView = (LinearLayout) view.findViewById(R.id.rootView);
for( int i=0; i < 5; ++i )
{
TextView mytextview = (TextView) inflater.inflate(R.layout.textview, null);
mytextview.setText("hola");
rootView.addView(mytextview);
}
Note: if you do it this way you can set all the styling and stuff in the XML for the View you want to add dynamically multiple times. This can save you from a lot of writing since defining the look of a View in code involves a lot more "writing" than it is required in XML.

change this:
LinearLayout linear = (LinearLayout) findViewById(R.id.generar_text);
TextView text = new TextView(lista.this);
text.setText("hola");
to:
AlertDialog dialog=myDialog.create();
LinearLayout linear = (LinearLayout) dialog.findViewById(R.id.generar_text);
TextView text = new TextView(lista.this);
text.setText("hola");
dialog.show();

Related

RecyclerView datas last row display with multiple time

I don't understand why my recyclerview is only showing the last row of my database although I initialised it with 150 datas.
I searched a lot in the internet and even here on SO, but not one of the solutions is working. Can you help me to figure out why my recyclerView is only showing the last row of the database? Thanks in advance to all of you.
May be you can help me. Here is my code:
package com.example.frontaddress.matedesignc;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Customer_Activity extends AppCompatActivity {
private List<String> StateListArray =new ArrayList<String>();
private List<String> StateList =new ArrayList<String>();
private List<String> CityListArray ;
private List<String> CityList ;
private Spinner dropdown_state;
private Spinner dropdown_city;
private DBHandler DB = new DBHandler(this);
private static final String BUSINESSNAME = "bussiness_name";
private static final String MOBILE = "mobile";
private static final String ADDRESS = "address";
private static final String ID = "id";
private Toolbar toolbar;
private Customer_list_Adapter adapter;
private RecyclerView recyclerView_Customer;
//ProgressDialog pDialog = new ProgressDialog(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer_list);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
GetStateList(); }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_sub, menu);
return true; }
public void CustomerDetails(String state,String city) throws IOException {
try {
List<customer_search_information> data = null;
data = new ArrayList<>();
customer_search_information current = new customer_search_information();
Cursor RST_CSTInfo = DB.getRows("customer", "id,bussiness_name,mobile,address", " state='" + state + "' AND city='" + city + "'");
while (!RST_CSTInfo.isAfterLast()) {
current.bussiness_name = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(BUSINESSNAME));
current.state = state;
current.city = city;
current.address = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(ADDRESS));
String Mob = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(MOBILE));
current.mobile_no = Mob;
current.e_mail = "mail.isigntech#gmail.com";
current.id = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(ID));
// displayExceptionMessage(current.id+current.bussiness_name+current.state+current.city+current.address+current.mobile+current.email);
data.add(current);
RST_CSTInfo.moveToNext();
}
recyclerView_Customer = (RecyclerView) findViewById(R.id.drawerListCustomer);
recyclerView_Customer.setHasFixedSize(true);
recyclerView_Customer.setHasFixedSize(true);
recyclerView_Customer.setLayoutManager(new LinearLayoutManager(this));
adapter = new Customer_list_Adapter(this, data);
recyclerView_Customer.setAdapter(adapter);
}catch (Exception e){ displayExceptionMessage(e.toString());}
}
private void GetStateList()
{ Cursor Customer= DB.getRows("customer","state", " 1 GROUP BY state");
while(!Customer.isAfterLast()){
String state=Customer.getString(Customer.getColumnIndex("state"));
StateList.add(state);
StateListArray.add(state);
Customer.moveToNext();
}
dropdown_state = (Spinner)findViewById(R.id.SpnSrch_State);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Customer_Activity.this, android.R.layout.simple_spinner_dropdown_item, StateListArray);
dropdown_state.setAdapter(adapter);
dropdown_state.setPrompt("Choose State ");
dropdown_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int item = dropdown_state.getSelectedItemPosition();
String state =StateListArray.get(item);
dropdown_city=(Spinner) findViewById(R.id.SpnSrch_State);
Cursor RstCity= DB.getRows("customer","city", "state='"+state+"' GROUP BY city");
CityListArray =new ArrayList<String>();
CityList =new ArrayList<String>();
while(!RstCity.isAfterLast()){
String city=RstCity.getString(RstCity.getColumnIndex("city"));
CityList.add(city);
CityListArray.add(city);
RstCity.moveToNext();
}
dropdown_city = (Spinner)findViewById(R.id.SpnSrch_City);
ArrayAdapter<String> cityadapter = new ArrayAdapter<String>(Customer_Activity.this, android.R.layout.simple_spinner_dropdown_item, CityListArray);
dropdown_city.setAdapter(cityadapter);
dropdown_city.setPrompt("Choose City ");
dropdown_city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int item = dropdown_state.getSelectedItemPosition();
String state =StateListArray.get(item);
item = dropdown_city.getSelectedItemPosition();
String city =CityListArray.get(item);
try {
CustomerDetails(state,city);
} catch (Exception e) {
displayExceptionMessage(e.toString());
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
displayExceptionMessage("Please Select State.");
}
});
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
displayExceptionMessage("Please Select City.");
}
});
}
public void displayExceptionMessage(String msg) {
//TextView Txterror=(TextView) findViewById(R.id.txterror);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == android.R.id.home) {
// NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItementer code hereSelected(item);
}
}
Here is my custom list adapter code:
package com.example.frontaddress.matedesignc;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
/**
* Created by frontaddress on 10/08/17.
*/
public class Customer_list_Adapter extends RecyclerView.Adapter<Customer_list_Adapter.CustomerViewHolder> {
private LayoutInflater inflater;
private Context contexts;
List<customer_search_information> Cst_data = Collections.emptyList();
public Customer_list_Adapter(Context context, List<customer_search_information> data) {
inflater = LayoutInflater.from(context);
this.Cst_data = data;
// Toast.makeText(contexts, data.size(), Toast.LENGTH_LONG).show();
this.contexts = context;
}
#Override
public CustomerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.content_search_staff, parent, false);
CustomerViewHolder holder = new CustomerViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(CustomerViewHolder holder, int position) {
try {
customer_search_information current = Cst_data.get(position);
Integer Pos=position;
holder.TxtBisinessName.setText(current.bussiness_name);
holder.TxtAddress.setText(current.address);
holder.Statecity.setText(current.state + "-" + current.city);
holder.Txt_Mobile.setText(current.mobile_no.toString());
holder.TxtEmail.setText(current.e_mail);
}catch (Exception e)
{
Toast.makeText(contexts,e.toString(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return Cst_data.size();
}
class CustomerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView TxtBisinessName;
TextView TxtAddress;
TextView Txt_Mobile;
TextView Statecity;
TextView TxtEmail;
ImageView ImgPhoneCall,ImgMailTo;
public CustomerViewHolder(View itemView) {
super(itemView);
TxtBisinessName = (TextView) itemView.findViewById(R.id.Txtbusiness_name);
Txt_Mobile = (TextView) itemView.findViewById(R.id.TxtMobile);
Statecity = (TextView) itemView.findViewById(R.id.Txtstatecity);
TxtAddress = (TextView) itemView.findViewById(R.id.Txtaddress);
TxtEmail=(TextView) itemView.findViewById(R.id.TxtEmail);
ImgPhoneCall = (ImageView) itemView.findViewById(R.id.ImgCallPhone);
ImgMailTo= (ImageView) itemView.findViewById(R.id.Imgmail);
ImgPhoneCall.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
customer_search_information current = Cst_data.get(getPosition());
String MOBILE = current.mobile_no;
try {
if (ActivityCompat.checkSelfPermission(contexts,Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(contexts, "Call Permission Not Granted ", Toast.LENGTH_LONG).show();
return;
}
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:+91" + MOBILE));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
contexts.startActivity(callIntent);
}
catch (Exception e){
Toast.makeText(contexts,e.toString(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
});
/* TxtProfile.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
customer_search_information current = data.get(getPosition());
String SID = current.id;
Intent intent = new Intent(contexts, StudentProfileActivity.class);
intent.putExtra("id", SID);
contexts.startActivity(intent);
}
});*/
ImgMailTo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// TODO Auto-generated method stub
customer_search_information current = Cst_data.get(getPosition());
String EMAIL = current.e_mail;
String BName = current.bussiness_name;
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, EMAIL);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "");
emailIntent.setType("text/plain");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Hi,"+BName);
final PackageManager pm = contexts.getPackageManager();
final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
ResolveInfo best = null;
for (final ResolveInfo info : matches)
if (info.activityInfo.packageName.endsWith(".gm") || info.activityInfo.name.toLowerCase().contains("gmail"))
best = info;
if (best != null)
emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name);
contexts.startActivity(emailIntent);
}
catch (Exception e){ }
}
});
}
#Override
public void onClick(View v) {
int ID=v.getId();
customer_search_information current=Cst_data.get(getPosition());
String SID=current.id;
// Toast.makeText(contexts,"Item Clicked Profile: "+ v.getId(), Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(contexts, StudentProfileActivity.class);
// intent.putExtra("id", SID);
// contexts.startActivity(intent);
}
}
}
I think the problem is here , instead of
while(!RST_CSTInfo.isAfterLast()){
...
..
RST_CSTInfo.moveToNext();
}
try this ....
do(RST_CSTInfo.movetofirst()){
// your logic
}while(cursor.movetonext())

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 solve a ResourcesNotFoundException in Android

This is my code , I have a problem ,error message about ResourcesNotFoundException this is a piece of code to view employees it has 2 buttons one to do delete and the other to do update.
I don't know the reason of this exception.
package com.example.task_9;
import java.util.ArrayList;
import com.example.task_9.my_dataBase.employees_con;
import com.example.task_9.my_dataBase.my_database;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class manage extends Activity {
ListView listview;
TextView totalrecords,tv;
//my_database db;
public ArrayList<employees> emp_list ;
employees_con con;
//Button logout;
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
setContentView(R.layout.manage);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("Employees Record:");
totalrecords = (TextView) findViewById(R.id.textView2);
listview = (ListView) findViewById(R.id.listView1);
// logout=(Button) findViewById(R.id.button1);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
emp_list = new ArrayList<employees>();
emp_list.clear();
con = new employees_con(this);
// db = new my_database(getApplicationContext());
// db.getWritableDatabase();
ArrayList<employees> e_list =con.getAllData() ;
for (int i = 0; i < e_list.size(); i++) {
Log.d("for_getall ", "ok ");
int e_id = e_list.get(i).getId();
Log.d("fun_getall ", "ok ");
// System.out.println("tidno>>>>>" + tidno);
String e_name = e_list.get(i).getUser_name();
String e_password = e_list.get(i).getPassword();
int e_age = e_list.get(i).getAge();
int e_status = e_list.get(i).getStatus();
Log.d("fun_getall ", "ok ");
employees emp_model = new employees();
emp_model.setId(e_id);
emp_model.setUser_name(e_name);
emp_model.setPassword(e_password);
emp_model.setAge(e_age);
emp_model.setStatus(e_status);
Log.d("addlist ", "ok ");
emp_list.add(emp_model);
}
Log.d("out for ", "ok ");
totalrecords.setText("Total Records :-" + emp_list.size());
listview.setAdapter(new ListAdapter(this));
con.close();
}
private class ListAdapter extends BaseAdapter {
//ArrayList<employees> data=new ArrayList<employees>();
Context contxt;
TextView id;
TextView user_name;
TextView password;
TextView age;
TextView status;
ImageView img;
employees obj;
LayoutInflater inflater;
public ListAdapter(Context context) {
// TODO Auto-generated constructor stub
contxt=context;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return emp_list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
// TODO Auto-generated method stub
/*if (v == null) {
v = inflater.inflate(R.layout.view, null);}*/
if (v == null)
{
LayoutInflater vi = (LayoutInflater)contxt.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.view, null); // album_list.xml this layout of the custom listview
Log.d("view if", "ok ");
}
id=(TextView) v.findViewById(R.id.textView6);
user_name=(TextView) v.findViewById(R.id.textView7);
password=(TextView) v.findViewById(R.id.textView8);
age=(TextView) v.findViewById(R.id.textView9);
status=(TextView) v.findViewById(R.id.textView10);
img =(ImageView) v.findViewById(R.id.imageView1);
Log.d("out if", "ok ");
obj = emp_list.get(position);
user_name.setText(obj.getUser_name());
id.setText(obj.getId());
password.setText(obj.getPassword());
age.setText(obj.getAge());
status.setText(obj.getStatus());
Log.d("view else ", "ok ");
final int temp = position;
(v.findViewById(R.id.button1))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
int emp_id=emp_list.get(temp).getId();
String emp_name = emp_list.get(temp).getUser_name();
String emp_password = emp_list.get(temp).getPassword();
int emp_age=emp_list.get(temp).getAge();
int emp_status=emp_list.get(temp).getStatus();
Intent intent = new Intent(manage.this,update.class);
Bundle bundle = new Bundle();
bundle.putInt("id", emp_id);
bundle.putString("name", emp_name);
bundle.putString("password", emp_password);
bundle.putInt("age", emp_age);
bundle.putInt("status", emp_status);
intent.putExtras(bundle);
startActivity(intent);
}
});
(v.findViewById(R.id.button2))
.setOnClickListener(new OnClickListener() {
employees_con con=new employees_con(contxt);
public void onClick(View arg0) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(manage.this);
alertbox.setCancelable(true);
alertbox.setMessage("Are you sure you want to delete ?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
con.DeleteEmp(emp_list.get(temp).getUser_name().toString());
con.close();
manage.this.onResume();
Toast.makeText(
getApplicationContext(),
"Record Deleted...",
Toast.LENGTH_SHORT).show();
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
Toast.makeText(
getApplicationContext(),
"No Clicked...",
Toast.LENGTH_SHORT).show();
}
});
alertbox.show();
}
});
return v;
}
}
}
}
Change
id.setText(obj.getId());
with
id.setText(String.valueOf(obj.getId()));
if you pass an int as argument for a TextView android will look for a String with id the int you provide. If it does not found throws an exception
One important this is that you should use Activity.onCreate() method in place of Activity.onStart().

How to Handle the checkbox ischecked and unchecked event in android

i am new in android.i make a simple maths apps.
i use the check box for select right option but problem is here the answer option is not only one but also two,three means multi select so i use the check box
chkOption.setOnCheckedChangeListener(this);
event and try to handle this.and store the select value in one Arraylist.but when i select option the value is add in arrayList but when i do uncheck(Diselect) then also the event is occur and the value add in arraylist.
my code is below
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
CheckBox chk=(CheckBox) buttonView;
if(chk.isChecked())
{
forMetchCheckBox.add(String.valueOf(chk.getText()));
}
}
forMetchCheckbow is my String ArrayList .So i can what to do?
How to Handle this problem.
if any user deselect the option then the checkbox select value is remove from ArrayList.it`s possible?
It seems you are having more than one checkbox and you are setting global listener for every checkbox. So, in that case you need to identify the event for specific checkbox also.
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
int id = buttonView.getId();
if(id == R.id.chk)
{
if(chk.isChecked()){
forMetchCheckBox.add(String.valueOf(chk.getText()));
}
else{
forMetchCheckBox.remove(String.valueOf(chk.getText()));
}
}
else if(id == R.id.chk1){
....
}
}
and so on, that will make your listener work perfect.
What's wrong is your if condition. It should be:
if( isChecked )
and not
if( chk.isChecked() )
chk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
chetimeslot = (String)chk.getTag();
checkbox_timeslot.add(chetimeslot);
}
else{
chetimeslot = (String)chk.getTag();
checkbox_timeslot.remove(chetimeslot);
}
});
To Select Maximum 5 Checkbox at one Time or Count selected and unselected checkbox in Custom listview with CheckBox
package com.test;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class ListViewCheckboxesActivity extends ListActivity {
AlertDialog alertdialog = null;
int i1, i2, i3 = 0;
Country rowcheck;
MyCustomAdapter dataAdapter = null;
ListView listView = null;
int k = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fmain);
// Generate list View from ArrayList
displayListView();
checkButtonClick();
}
private void displayListView() {
// Array list of countries Equipments
ArrayList<Country> rowcheckList = new ArrayList<Country>();
Country rowcheck = new Country("", "Hex Bolts", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Hex Cap Screw", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Round Head Bolt", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Slotted Head Hex Bolt", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Socket Cap Screw", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Sockets", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Square Head Bolt", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Carriage Bolt", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Plow Bolt", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Struts Clamp", false);
rowcheckList.add(rowcheck);
listView = getListView();
dataAdapter = new MyCustomAdapter(this, R.layout.rowcheck_info,
rowcheckList);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Country rowcheck = (Country) parent.getItemAtPosition(position);
}
});
}
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> rowcheckList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> rowcheckList) {
super(context, textViewResourceId, rowcheckList);
this.rowcheckList = new ArrayList<Country>();
this.rowcheckList.addAll(rowcheckList);
}
private class ViewHolder {
TextView code;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.rowcheck_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
holder.name.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
CheckBox cb = (CheckBox) v ;
Country rowcheck = (Country) cb.getTag();
//To check maximum 5 Selection
if(k>5)
{
if(!cb.isChecked())
{
rowcheck.selected=true;
System.out.println(k--);
}
else
{
System.out.println("if block in-----");
cb.setChecked(false);
Toast.makeText(getApplicationContext(), "Maximum Selection", Toast.LENGTH_LONG).show();
}
}
else
{
System.out.println("else block in-----");
if(!cb.isChecked())
{
rowcheck.selected=true;
System.out.println(k--);
}
else if(cb.isChecked())
{
rowcheck.selected=false;
System.out.println(k++);
}
}
Toast.makeText(getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show()
rowcheck.setSelected(cb.isChecked());
}
});
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Country rowcheck = rowcheckList.get(position);
// holder.code.setText(" (" + rowcheck.getCode() + ")");
holder.code.setText(rowcheck.getName());
// holder.name.setText(rowcheck.getName());
holder.name.setChecked(rowcheck.isSelected());
holder.name.setTag(rowcheck);
return convertView;
}
}
private void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...\n");
ArrayList<Country> rowcheckList = dataAdapter.rowcheckList;
System.out.println("Size" + rowcheckList.size());
int j = 0;
ArrayList<String> stt = new ArrayList<String>();
for (int i = 0; i < rowcheckList.size(); i++) {
Country rowcheck = rowcheckList.get(i);
// System.out.println(rowcheck.getName());
if (rowcheck.isSelected()) {
stt.add(rowcheck.getName());
// Country.st=new ArrayList<String>();
String s = rowcheck.getName();
System.out.println("String--" + rowcheck.getName());
Country.st.add(s);
j = j++;
System.out.println(j++);
responseText.append("\n" + rowcheck.getName());
}
}
for (int i = 0; i < stt.size(); i++) {
System.out.println("Names----" + stt.get(i).toString());
}
if (j >= 1 && j <= 5) {
Intent i = new Intent(ListViewCheckboxesActivity.this,
PickedItemListView.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
} else {
Toast.makeText(ListViewCheckboxesActivity.this,
"Maximum 5 Selection Allowed", Toast.LENGTH_LONG)
.show();
}
Toast.makeText(ListViewCheckboxesActivity.this, responseText,
Toast.LENGTH_LONG).show();
}
});
}
//Logout ALert Box
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
LayoutInflater inflater = LayoutInflater
.from(ListViewCheckboxesActivity.this);
View dialogview = inflater.inflate(R.layout.logout_popup, null);
final Button ok = (Button) dialogview.findViewById(R.id.ok);
final Button cancel = (Button) dialogview.findViewById(R.id.cancel);
AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(
(ListViewCheckboxesActivity.this));
dialogbuilder.setView(dialogview);
dialogbuilder.setInverseBackgroundForced(true);
alertdialog = dialogbuilder.create();
alertdialog.show();
ok.setOnClickListener(new OnClickListener() {
public void onClick(View paramView) {
alertdialog.dismiss();
final Intent intent = new Intent(
ListViewCheckboxesActivity.this,
LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View paramView) {
alertdialog.cancel();
}
});
}
return super.onKeyDown(keyCode, event);
}
}
checkBox_sound.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
var boolSoundOn = (isChecked) ? true : false;
}
});
It works Perfect...

how can i get the editText data from the Alertdailog.builder?

package com.nil.in;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class SettingsMod extends Activity {
/** Called when the activity is first created. */
private ListView listview;
private String lv_arr[] = { "change password", "change contact details" };
String old_password = "rajesh";
// EditText input;
// TextView name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homesettings);
listview = (ListView) findViewById(R.id.View1_homesettings);
listview.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, lv_arr));
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
// get the position where the user clicked on the ListView
if (position == 0) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(
SettingsMod.this);
alertbox.setMessage("Password change!");
alertbox.setView(LayoutInflater.from(SettingsMod.this)
.inflate(R.layout.passwordchange, null));
alertbox.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
System.out.println("Save clicked");
// getting the editText data from the Dailog
Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater
.inflate(
R.layout.passwordchange,
(ViewGroup) findViewById(R.id.LinearLayout01));
EditText input = (EditText) layout
.findViewById(R.id.Oldpassword_Edit1);
EditText newPass_Edit = (EditText) layout
.findViewById(R.id.NewPassword_Edit2);
EditText confirm_Edit = (EditText) layout
.findViewById(R.id.Confirm_Edit3);
String str = input.getText().toString();
String edit_2 = newPass_Edit.getText()
.toString();
String edit_3 = newPass_Edit.getText()
.toString();
validate(str, edit_2, edit_3);
}
});
alertbox.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
System.out.println("Cancel clicked");
}
});
alertbox.show();
} else {
AlertDialog.Builder alertbox = new AlertDialog.Builder(
SettingsMod.this);
alertbox.setTitle("Contact info");
alertbox.setView(LayoutInflater.from(SettingsMod.this)
.inflate(R.layout.detailschange, null));
alertbox.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
}
});
alertbox.show();
}
}
});
}
void validate(String str, String edit_2, String edit_3) {
if (str == null || str.length() == 0) {
AlertDialog.Builder adb = new AlertDialog.Builder(SettingsMod.this);
adb.setTitle("enter old password");
adb.setPositiveButton("ok", null);
adb.show();
}
if (edit_2 == null || edit_2.length() == 0) {
AlertDialog.Builder adb = new AlertDialog.Builder(SettingsMod.this);
adb.setTitle("enter new password");
adb.setPositiveButton("ok", null);
adb.show();
}
if (!edit_2.equals(edit_3)) {
AlertDialog.Builder adb = new AlertDialog.Builder(SettingsMod.this);
adb.setTitle("matched");
adb.setPositiveButton("ok", null);
adb.show();
}
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
// get the position where the user clicked on the ListView
if (position == 0) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(
SettingsMod.this);
alertbox.setMessage("Password change!");
Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater
.inflate(
R.layout.passwordchange,
(ViewGroup) findViewById(R.id.LinearLayout01));
EditText input = (EditText) layout
.findViewById(R.id.Oldpassword_Edit1);
EditText newPass_Edit = (EditText) layout
.findViewById(R.id.NewPassword_Edit2);
EditText confirm_Edit = (EditText) layout
.findViewById(R.id.Confirm_Edit3);
alertbox.setView(LayoutInflater.from(SettingsMod.this)
.inflate(R.layout.passwordchange, null));
alertbox.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
System.out.println("Save clicked");
// getting the editText data from the Dailog
String str = input.getText().toString();
String edit_2 = newPass_Edit.getText()
.toString();
String edit_3 = newPass_Edit.getText()
.toString();
validate(str, edit_2, edit_3);
}
});
alertbox.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
System.out.println("Cancel clicked");
}
});
alertbox.show();
}

Categories

Resources