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

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

Related

Android - Firebase Realtime database not working for this library

I have been using firebase for my app, all works fine, however, I recently updated my UI, by adding this library, the other data in my listview but this library's view does not update, can someone please help me with this, and there's one more issue with my code, when I update the status, i.e the library's view, only the selected items view should be updated, instead all the views in my list get updated, say if I select "Received" for one item in the list, all others get updated to "Received", this does not reflect in the firebase console, and when I re open the app, everything will fixed. Please assist me with this. Here' my git repository link if needed.
AddOrUpdateItem.java
package com.fayaz.uniabex;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class AddOrUpdateItem extends AppCompatActivity implements OnItemSelectedListener {
Button bOK,bCancel;
Item item;
int position;
EditText iName,iPono,iQty,iSupplier,iContact,iTranport,iLrno,iRemarks;
CoordinatorLayout cl;
public Spinner spinner;
String status, selectedStatus;
public ArrayAdapter<String> dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_or_update_item);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
position = getIntent().getIntExtra("Position", -1);
cl = (CoordinatorLayout) findViewById(R.id.cdlayout);
final Intent intent = new Intent(AddOrUpdateItem.this, MainActivity.class);
iName= (EditText) findViewById(R.id.iName);
iPono = (EditText) findViewById(R.id.iPoNo);
iQty = (EditText) findViewById(R.id.iQty);
iSupplier = (EditText) findViewById(R.id.iSupplier);
iContact = (EditText) findViewById(R.id.iContact);
iTranport = (EditText) findViewById(R.id.iTransport);
iLrno = (EditText) findViewById(R.id.iLrno);
iRemarks = (EditText) findViewById(R.id.iRemarks);
// Spinner element
spinner = (Spinner) findViewById(R.id.status);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
categories.add("Enquiry");
categories.add("Quotation");
categories.add("Po Rel");
categories.add("Dispatched");
categories.add("Received");
// Creating adapter for spinner
dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
bOK = (Button) findViewById(R.id.bOk);
bCancel = (Button) findViewById(R.id.bCancel);
if(position != -1) {
getSupportActionBar().setTitle("Edit Entry");
searchPerson(position);
item = new Item();
}
else {
getSupportActionBar().setTitle("Add Entry");
item = null;
}
bOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String test = iRemarks.getText().toString();
Item i = new Item();
i.setItem(iName.getText().toString());
i.setPonum(iPono.getText().toString());
i.setQty(iQty.getText().toString());
i.setSupplier(iSupplier.getText().toString());
i.setContact(iContact.getText().toString());
i.setTransporter(iTranport.getText().toString());
i.setLrnum(iQty.getText().toString());
i.setStatus(selectedStatus);
if(test.equals("\n")){
i.setRemarks(iRemarks.getText().toString());
}
else{
i.setRemarks(iRemarks.getText().toString() + "\n");
}
if (item == null)
MainActivity.getInstance().addItem(i);
else
MainActivity.getInstance().updateItemDetails(i, position);
finish();
}
});
bCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
public void searchPerson(int position) {
String clickedKey = MainActivity.getInstance().getKeysArray().get(position);
MainActivity.getInstance().getmDatabase().child(clickedKey).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user value
String test = iRemarks.getText().toString();
Item person = dataSnapshot.getValue(Item.class);
iName.setText(person.getItem());
iPono.setText(person.getPonum());
iSupplier.setText(person.getSupplier());
iQty.setText(person.getQty());
iTranport.setText(person.getTransporter());
iContact.setText(person.getContact());
iLrno.setText(person.getLrnum());
spinner.setSelection(dataAdapter.getPosition(person.getStatus()));
if(test.equals("\n")){
iRemarks.setText(person.getRemarks());
}
else{
iRemarks.setText(person.getRemarks() + "\n");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
status = parent.getItemAtPosition(position).toString();
selectedStatus = Integer.toString(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
ItemDetailsAdapter.java
package com.fayaz.uniabex;
/**
* Created by Fayaz on 21/12/2016.
*/
import android.widget.BaseAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.anton46.stepsview.StepsView;
import java.util.ArrayList;
public class ItemDetailsAdapter extends BaseAdapter {
private ArrayList<Item> arrayListItem;
private Context context;
private LayoutInflater inflater;
public String curStatus;
public ItemDetailsAdapter(Context context, ArrayList<Item> arrayListItem) {
this.context = context;
this.arrayListItem = arrayListItem;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrayListItem.size();
}
#Override
public Object getItem(int position) {
return arrayListItem.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final String[] labels = {"Enq", "Qtn", "PO", "Dspd", "Rcvd"};
View v = convertView;
Holder holder;
if (v == null) {
v = inflater.inflate(R.layout.list_item, null);
holder = new Holder();
holder.ItemName = (TextView) v.findViewById(R.id.ItemNametv);
holder.qty = (TextView) v.findViewById(R.id.qtytv);
holder.EditItem = (Button) v.findViewById(R.id.EditItem);
holder.DeleteItem = (Button) v.findViewById(R.id.DeleteItem);
holder.mStepsView = (StepsView) v.findViewById(R.id.stepsView);
curStatus = arrayListItem.get(position).getStatus();
int n = Integer.parseInt(curStatus);
holder.mStepsView.setLabels(labels)
.setBarColorIndicator(context.getResources().getColor(R.color.material_blue_grey_800))
.setProgressColorIndicator(context.getResources().getColor(R.color.colorPrimary))
.setLabelColorIndicator(context.getResources().getColor(R.color.colorPrimaryDark))
.setCompletedPosition(n)
.drawView();
v.setTag(holder);
} else {
holder = (Holder) v.getTag();
}
holder.ItemName.setText("Item: " + arrayListItem.get(position).getItem());
holder.qty.setText("Qty: " + arrayListItem.get(position).getQty());
holder.EditItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,AddOrUpdateItem.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("Position", position);
context.getApplicationContext().startActivity(intent);
}
});
holder.DeleteItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShowConfirmDialog(context, position);
}
});
return v;
}
class Holder {
TextView ItemName,qty;
Button DeleteItem, EditItem;
StepsView mStepsView;
}
public static void ShowConfirmDialog(Context context, final int position) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder
.setMessage("Are you sure you want to delete this entry?")
.setCancelable(true)
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.getInstance().deleteItem(position);
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}

How can I achieve setOnLongClickListener?

I've seen many examples of setOnLongClickListener in a ListView, but I'm using an AndroidHive's ExpandableListView, so it doesn't seem to recognized (error: setOnLongClickListener cannot be resolved to a type). How would I go about making it so that I can use setOnLongClickListener?
ExpandableListView expListView;
...
expListView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongChildClick(View v) {
return true;
}
});
MainActivity.java (listener located in first method):
package com.example.groceryrunnerv4;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.Toast;
public class MainActivity extends Activity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview on child click listener
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
//((TextView) v).setPaintFlags(((TextView) v).getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
//listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition) .setPaintFlags(CHILD.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
return false;
}
});
expListView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongChildClick(View v) {
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Adds food group data
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data groups
listDataHeader.add("Produce");
listDataHeader.add("Grains");
listDataHeader.add("Meat & Seafood");
listDataHeader.add("Frozen");
listDataHeader.add("Canned");
listDataHeader.add("Bakery");
listDataHeader.add("Beverages");
listDataHeader.add("Other");
// Adding child data items
List<String> Produce = new ArrayList<String>();
Produce.add("Chaquita Bananas");
Produce.add("Apples (8)");
Produce.add("Kiwi");
Produce.add("Romaine Lettuce (3)");
List<String> Grains = new ArrayList<String>();
Grains.add("Whole Grain Bread");
Grains.add("Whole Wheat English Muffins");
Grains.add("Pasta");
Grains.add("Oatmeal");
List<String> MeatSeafood = new ArrayList<String>();
MeatSeafood.add("My dead friends");
List<String> Frozen = new ArrayList<String>();
Frozen.add("Edamame");
Frozen.add("Bean Burgers");
List<String> Canned = new ArrayList<String>();
Canned.add("Amy's Lentils");
Canned.add("Jam");
Canned.add("Peanu Butter");
List<String> Bakery = new ArrayList<String>();
Canned.add("Fresh Bread");
List<String> Beverages = new ArrayList<String>();
Canned.add("Water");
listDataChild.put(listDataHeader.get(0), Produce);
listDataChild.put(listDataHeader.get(1), Grains);
listDataChild.put(listDataHeader.get(2), MeatSeafood);
listDataChild.put(listDataHeader.get(3), Frozen);
listDataChild.put(listDataHeader.get(4), Canned);
listDataChild.put(listDataHeader.get(5), Bakery);
listDataChild.put(listDataHeader.get(6), Beverages);
}
// Method for activity events
public void onButtonClick(View v) {
final int id = v.getId();
switch (id) {
case R.id.CreateLG:
createLGPopup(v);
break;
case R.id.EditButton:
createEditButtonPopup(v);
break;
case R.id.SaveButton:
Toast.makeText(getApplicationContext(), "List saved.",
Toast.LENGTH_SHORT).show();
break;
case R.id.ListButton:
// chooseListDialog()
}
}
// findViewById(R.id.GetStarted).setVisibility(View.INVISIBLE);
// TextView text = (TextView) findViewById(R.id.GetStarted);
// text.setText(choice);
// CreateLG Button's Popup Menu
public void createLGPopup(View v) {
PopupMenu LGMenu = new PopupMenu(this, v);
LGMenu.getMenuInflater().inflate(R.menu.createlg_menu, LGMenu.getMenu());
LGMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
String choice = new String((String) item.getTitle());
if (choice.equals("Create List")) {
createListDialog();
}
else if (choice.equals("Create Group")) {
createGroupDialog();
}
return false;
}
});
LGMenu.show();
}
// Create Edit Button's Popup Menu
public void createEditButtonPopup(View v) {
PopupMenu EditMenu = new PopupMenu(this, v);
EditMenu.getMenuInflater().inflate(R.menu.editlist_menu, EditMenu.getMenu());
EditMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
String choice = new String((String) item.getTitle());
if (choice.equals("Edit List Name")) {
editListDialog();
}
else if (choice.equals("Clear All Items")) {
Toast.makeText(getApplicationContext(), "All list items deleted.",
Toast.LENGTH_SHORT).show();
}
else if (choice.equals("Delete List")) {
TextView text = (TextView) findViewById(R.id.ListName);
text.setText("Grocery Runner");
Toast.makeText(getApplicationContext(), "\"" + text.getText().toString() + "\" list edited.",
Toast.LENGTH_SHORT).show();
}
return false;
}
});
EditMenu.show();
}
// Create List Dialog
public AlertDialog.Builder dialogBuilder;
private void createListDialog() {
dialogBuilder = new AlertDialog.Builder(this);
final EditText textInput = new EditText(this);
dialogBuilder.setTitle("Create new list");
dialogBuilder.setMessage("Name your list: ");
dialogBuilder.setView(textInput);
dialogBuilder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
TextView text = (TextView) findViewById(R.id.ListName);
text.setText(textInput.getText().toString());
Toast.makeText(getApplicationContext(), "\"" + textInput.getText().toString() + "\" list created.",
Toast.LENGTH_SHORT).show();
//add list to ListsButton
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Cancelled.",
Toast.LENGTH_SHORT).show();
}
});
// Output
AlertDialog dialogue = dialogBuilder.create();
dialogue.show();
}
// Create Group Dialog
private void createGroupDialog() {
dialogBuilder = new AlertDialog.Builder(this);
final EditText textInput = new EditText(this);
dialogBuilder.setTitle("Create new group");
dialogBuilder.setMessage("Name your group: ");
dialogBuilder.setView(textInput);
dialogBuilder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
createGroup(textInput.getText().toString());
Toast.makeText(getApplicationContext(), "\"" + textInput.getText().toString() + "\" group created.",
Toast.LENGTH_SHORT).show();
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Cancelled.",
Toast.LENGTH_SHORT).show();
}
});
// Output
AlertDialog dialogue = dialogBuilder.create();
dialogue.show();
}
public void createGroup(String inputGroup){
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data group
listDataHeader.add(inputGroup);
// Adding child data items
List<String> group = new ArrayList<String>();
Integer groupIndex = listDataHeader.indexOf(inputGroup);
listDataChild.put(listDataHeader.get(groupIndex), group);
}
// Create List Dialog
private void editListDialog() {
dialogBuilder = new AlertDialog.Builder(this);
final EditText textInput = new EditText(this);
dialogBuilder.setTitle("Edit list name");
dialogBuilder.setMessage("Name your list: ");
dialogBuilder.setView(textInput);
dialogBuilder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
TextView text = (TextView) findViewById(R.id.ListName);
text.setText(textInput.getText().toString());
Toast.makeText(getApplicationContext(), "\"" + textInput.getText().toString() + "\" list edited.",
Toast.LENGTH_SHORT).show();
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Cancelled.",
Toast.LENGTH_SHORT).show();
}
});
// Output
AlertDialog dialogue = dialogBuilder.create();
dialogue.show();
}
}
ExpandableListAdapter.java:
package com.example.groceryrunnerv4;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
getExpandableListView().setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
int groupPosition = ExpandableListView.getPackedPositionGroup(id);
int childPosition = ExpandableListView.getPackedPositionChild(id);
// You now have everything that you would as if this was an OnChildClickListener()
// Add your logic here.
// Return true as we are handling the event.
return true;
}
return false;
}
});
from Android: long click on the child views of a ExpandableListView?

adding textview dynamically without results

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

BaseExpandableListAdapter notifyDataSetChanged() error

I looked through a lot of information, but have not found the right solution.
My code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.safety.Whitelist;
import org.jsoup.select.Elements;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
MyPointsDB db;
ArrayList<String> arr_book_title = new ArrayList<String>();
ArrayList<String> arr_book_href = new ArrayList<String>();
String selGroupParam;
String selItemParam;
public static String PACKAGE_NAME;
File directory;
String directory_string;
private Context _context;
private List<String> _listDataHeader; // header titles
private List<String> _paramDataHeader;
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
private List<String> _paramDataChild;
AlertDialog dialog;
public ExpandableListAdapter(Context context, List<String> listDataHeader, List<String> paramDataHeader, HashMap<String, List<String>> listChildData, List<String> paramChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._paramDataHeader = paramDataHeader;
this._listDataChild = listChildData;
this._paramDataChild = paramChildData;
//PACKAGE_NAME = _context.getPackageName();
this.db = new MyPointsDB(_context);
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public String getChildParam(int groupPosition, int childPosition) {
return _paramDataChild.get(childPosition).toString();
}
#Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView.findViewById(R.id.lblListItem);
txtListChild.setTag(_paramDataChild.get(childPosition).toString());
txtListChild.setText(childText);
Button btnItem = (Button) convertView.findViewById(R.id.iconShowParamItem);
btnItem.setTag(_paramDataChild.get(childPosition).toString());
btnItem.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
selItemParam = view.getTag().toString().trim();
final CharSequence[] items = {_context.getString(R.string.operation_del_book)};
AlertDialog.Builder builder = new AlertDialog.Builder(_context);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String[] separated = selItemParam.split(";");
String url_base = separated[1];
// Delete book
if (items[item] == _context.getString(R.string.operation_del_book)) {
new AlertDialog.Builder(_context)
.setTitle(R.string.alert_del_book_caption)
.setMessage(R.string.alert_del_book_message)
.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String[] separated = selItemParam.split(";");
String _id = separated[0];
db.deleteBOOKid(_id);
//Toast.makeText(_context, selItemParam, Toast.LENGTH_LONG).show();
//refreshList();
//Toast.makeText(_context, _context.getString(R.string.operation_del_book), Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton(R.string.button_cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
Button btnGroup = (Button) convertView.findViewById(R.id.iconShowParamGroup);
btnGroup.setTag(_paramDataHeader.get(groupPosition).toString());
btnGroup.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(_context, "btnGroup", Toast.LENGTH_SHORT).show();
selGroupParam = view.getTag().toString().trim();
final CharSequence[] items = {_context.getString(R.string.operation_add_book), _context.getString(R.string.operation_del_autor)};
AlertDialog.Builder builder = new AlertDialog.Builder(_context);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//Toast.makeText(_context, items[item], Toast.LENGTH_SHORT).show();
String[] separated = selGroupParam.split(";");
String url_base = separated[1];
// Add book
if (items[item] == _context.getString(R.string.operation_add_book)) {
new selectBookInAutor().execute(url_base);
}
// Delete book
if (items[item] == _context.getString(R.string.operation_del_autor)) {
new AlertDialog.Builder(_context)
.setTitle(R.string.alert_del_autor_caption)
.setMessage(R.string.alert_del_autor_message)
.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String[] separated = selGroupParam.split(";");
String _id = separated[0];
db.deleteAUTORid(_id);
notifyDataSetChanged();
}
})
.setNegativeButton(R.string.button_cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
private class selectBookInAutor extends AsyncTask<String, Void, String> {
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
arr_book_title.clear();
arr_book_href.clear();
mProgressDialog = new ProgressDialog(_context);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
StringBuilder sb = new StringBuilder();
try {
doc = Jsoup.connect(params[0]).userAgent("Mozilla").get();
//Elements links = doc.select("dl>dl>dt>li>a");
Elements links = doc.select("li>a");
for (Element link : links) {
sb.append(link.text());
arr_book_title.add(link.text());
arr_book_href.add(Jsoup.clean(link.attr("abs:href"), Whitelist.basic()));
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
if(!result.equals("")){
//Toast.makeText(_context, result, Toast.LENGTH_LONG).show();
final CharSequence[] items = arr_book_title.toArray(new CharSequence[arr_book_title.size()]);
final ArrayList seletedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(_context);
builder.setTitle("Select The Difficulty Level");
builder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
if (isChecked) {
seletedItems.add(indexSelected);
}else if(seletedItems.contains(indexSelected)){
seletedItems.remove(Integer.valueOf(indexSelected));
}
}
}).setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Toast.makeText(_context, seletedItems.toString(), Toast.LENGTH_SHORT).show();
for (Object s : seletedItems){
String[] separated = selGroupParam.split(";");
String _idautor = separated[0].toString();
long id_book = db.insertBOOK(_idautor, arr_book_href.get(Integer.valueOf(s.toString())).toString(), "", arr_book_title.get(Integer.valueOf(s.toString())).toString());
new saveBookInAutor().execute(arr_book_href.get(Integer.valueOf(s.toString())).toString(), _idautor, String.valueOf(id_book));
}
//refreshList();
}
}).setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
}).create().show();
}else{
Toast.makeText(_context, "Error get book autor", Toast.LENGTH_SHORT).show();
}
mProgressDialog.dismiss();
}
}
private class saveBookInAutor extends AsyncTask<String, Void, String> {
ProgressDialog mProgressDialog2;
String _idautor = "", _idbook = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog2 = new ProgressDialog(_context);
mProgressDialog2.setMessage("Save page...");
mProgressDialog2.setIndeterminate(false);
mProgressDialog2.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
String _html = "";
_idautor = params[1];
_idbook = params[2];
try {
doc = Jsoup.connect(params[0]).userAgent("Mozilla").get();
_html = doc.select("dd").outerHtml();
} catch (IOException e) {
e.printStackTrace();
}
return Jsoup.clean(_html, Whitelist.basic());
}
#Override
protected void onPostExecute(String result) {
if(!result.equals("")){
Toast.makeText(_context, "Save file", Toast.LENGTH_SHORT).show();
String html = "<html lang='ru'><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/></head><body>"+result+"</body></html>";
//String html = result;
savePageToFile(_idautor + "_" + String.valueOf(_idbook), html);
}else{
Toast.makeText(_context, "Error save page", Toast.LENGTH_SHORT).show();
}
mProgressDialog2.dismiss();
}
}
public void refreshList() {
Intent intent = new Intent(_context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
_context.startActivity(intent);
}
public void savePageToFile(String filename, String html) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(_context.openFileOutput(filename, Context.MODE_PRIVATE));
outputStreamWriter.write(html);
outputStreamWriter.close();
}
catch (IOException e) {
//Log.e("Exception", "File write failed: " + e.toString());
}
}
public String readPageFile(String filename) {
String ret = "";
try {
InputStream inputStream = _context.openFileInput(filename);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
//Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
//Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
}
Problem is Delete book. After removal of the book from the database I want to update the screen ExpandableListView. This error occurs when you call the notifyDataSetChanged(). The element does not disappears from the screen.
I found a crutch to solve the problem:
Intent intent = new Intent(_context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
_context.startActivity(intent);
But this is not entirely correct.
I ask your help.
You delete the item from the database, but it is still present in the lists that you have. You have to update the _listDataHeader list after you delete the item, and then notifyDataSetChanged. Also you should remove the child which corresponds to this item. Since you have many lists, update them also when an item is deleted.
.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String[] separated = selItemParam.split(";");
String _id = separated[0];
db.deleteBOOKid(_id);
//update lists here, and remove the header, child items and anything related..
// _listDataHeader.remove(groupPosition) // groupPosition should be final
// etc. etc.
notifyDataSetChanged();
} })
To ensure that data is consistent, when you delete something.. delete other related items too.. for example:
if _paramDataChild and _paramDataHeader are related to the item being deleted, you may want to update them too.. so that they don't have values which relate to the deleted item. (this depends on your scenario, i am just giving an example)

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...

Categories

Resources