android: adding dynamically with dynamically items - java

i have list item in each row like :
item1 item2 item3 item4 item5 item6
I need
item 1 item 2 item3
item 4 item5 item 6
...
I don't need to use GridView. My getView():
LinearLayout dynamicallyLayout = null;
boolean needCreated = true;
if (json.length() > 1) {
for (int j = 0; j < json.length(); j++) {
JSONObject classesJson = json.getJSONObject(j);
String name = classesJson.getString("name");
classChbx = new CheckBox(ctx);
classChbx.setText(name);
if (value == 1) classChbx.setChecked(true);
if (needCreated) {
dynamicallyLayout = new LinearLayout(ctx);
dynamicallyLayout.setOrientation(LinearLayout.HORIZONTAL);
holder.llChbTypes.addView(dynamicallyLayout);
needCreated = false;
}else {
if (j % 3 == 0) {
needCreated = true;
dynamicallyLayout.addView(classChbx);
dynamicallyLayout = null;
break;
}
}
if (dynamicallyLayout != null)
dynamicallyLayout.addView(classChbx);
}
}else {
classChbx = new CheckBox(ctx);
classChbx.setText(json.getJSONObject(0).getString("name"));
holder.llChbTypes.addView(classChbx);
}
but it look for low resolution like: item1, item2, item3.. that's all!

I have used this approach in my code.
for ( int i = 0 ; i < 4 ; i ++ )
{
LinearLayout layoutInWhichToAdd= (LinearLayout) rootView
.findViewById(R.id.layoutInWhichToAdd);
View toadd= orderDetails.getLayoutInflater().inflate(
R.layout.include_items_invieworder, layoutInWhichToAdd,
false);
layoutInWhichToAdd.addView(toadd);
}

Related

how to count filled edit text from multiple edittext

In my app have twenty edit text,but I want to count filled edit text and that data goes in anther activity through an array. Like when I filled 3 edit text from twenty, that 3 edit text data goes next page and that 3 count goes to next page as an int.
this is my 1st java class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select);
mspin=(Spinner) findViewById(R.id.spinner1);
submit = (Button) findViewById(R.id.btn1);
layout = (LinearLayout) findViewById(R.id.linear);
lay = (LinearLayout) findViewById(R.id.li);
edt=(EditText) findViewById(R.id.ed2);
sc = (ScrollView) findViewById(R.id.sc1);
int no = 20;
allEds = new ArrayList<EditText>();
for (int i=1;i<=no;i++){
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
edtAdd = new EditText(SelectActivity.this);
layout.setLayoutParams(params);
allEds.add(edtAdd);
edtAdd.setHint("Enter Name" + i);
edtAdd.setId(i);
layout.addView(edtAdd);
}
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (allEds.size()<=9) {
Intent data = new Intent(SelectActivity.this, HalfPieChartActivity.class);
String[] items = new String[allEds.size()];
String str = String.valueOf(allEds.size());
data.putExtra("size", str); //you don't need to keep this in loop as its same.
data.putExtra("edt", edt.getText().toString());
for (int j = 0; j < allEds.size(); j++) {
items[j] = allEds.get(j).getText().toString();
data.putExtra("edData" + j, items[j]);
}
startActivity(data);
}
else {
Intent data = new Intent(SelectActivity.this, FullPieChartActivity.class);
String[] items = new String[allEds.size()];
String str = String.valueOf(allEds.size());
data.putExtra("size", str);// this is the line where I sent that count
data.putExtra("edt", edt.getText().toString());
for (int j = 0; j < allEds.size(); j++) {
items[j] = allEds.get(j).getText().toString();
data.putExtra("edData" + j, items[j]);//here is filled data send line
}
startActivity(data);
}
}
});
}
}
When I click submit 20 show in next page as an int.I want to sent that 3data and 3 as an int.
Please help me
As you have asked for sample in comment, i am posting my answer with sample.
In onclicklistener of your submit button you can add following code.
myNoneEmptyEdittextCounter = 0;
for (int i=1;i<=no;i++)
{
myEt = (EditText) findViewById(i);
if(!TextUtils.isEmpty(myEt.getText().toString()))
{
myNoneEmptyEdittextCounter +=1;
}
}
//myNoneEmptyEdittextCounter is count of your filled edittexts
This method will return list of data and its size will give you the int you are looking for which is number of filled items.
In submit button click
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(edittextValues().isEmpty()) {
//nothing has been filled
} else {
//items in edittextValues() are your data.
edittextValues().size();//this is your int which is number of edit text filled.
}
}
}
I have mentioned in comments what each step does. Hope this helps.
Method edittextValues()
ArrayList<String> edittextValues() {
ArrayList<String> filledData = new ArrayList<>(); //initialise empty string array.
for (int i=1; i<=20; i++){ //loop through ids from 1 to 20
for (int j = 0; j< layout.getChildCount(); j++) { //loop through all the children of root layout
if(layout.getChildAt(j) instanceof EditText) { //filter EditText
EditText editText = (EditText) layout.getChildAt(j);
if(editText.getId() == i) { // filter the one which u programmatically added
if(!editText.getText().toString().isEmpty()) { // check if its not empty, that's the one you are looking
filledData.add(editText.getText().toString()); //add it to the list
}
}
}
}
}
return filledData; //return string list
}

Codename one calendar UpdateButtonDayDate() issue

I am working on my project where I want to show when application starts then calendar display, which date contain events, for instance if the date contain events, then the day button contains * symbol and day, And if the date doesn't contain any event then it only displays a day.
I wrote following code, but it only displays * symbol when I am clicking on that button, So how can I manage this code that display * symbol on the date which only contain events when the application starts or that page gonna be loaded.
Following is my code:-
public class Customised extends Calendar{
ArrayList<String[]> data = new ArrayList<>();
int i,j,columns;
#Override
protected void updateButtonDayDate(Button dayButton,int currentMonth, int day) {
dayButton.setText(""+day);
dayButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
//Check which date having how many number of events===============================================================
try{
ShowEvent.removeAll();
cur = db.executeQuery("SELECT Event, Description from CalendarData WHERE Date = ? ", dateLabel.getText());
columns = cur.getColumnCount();
if(columns > 0) {
boolean next = cur.next();
if(next) {
String[] columnNames = new String[columns];
for(int iter = 0 ; iter < columns ; iter++) {
columnNames[iter] = cur.getColumnName(iter);
}
while(next) {
Row currentRow = cur.getRow();
String[] currentRowArray = new String[columns];
for(int iter = 0 ; iter < columns ; iter++) {
currentRowArray[iter] = currentRow.getString(iter);
}
data.add(currentRowArray);
next = cur.next();
}
Object[][] arr = new Object[data.size()][];
data.toArray(arr);
}
}
}catch(IOException e){
e.printStackTrace();
}
for(i = 0 ; i< data.size(); i++){
Log.p(data.get(i)[0]);
}
Label a = new Label(dateLabel.getText());
Label b = new Label(" "+i);
Container container1 = TableLayout.encloseIn(2, a,b);
container1.setUIID("container1");
ShowEvent.add(container1);
for( i = 0 ; i< data.size(); i++){
for(j = 0; j<columns; j++){
Log.p(data.get(i)[j]);
SpanLabel spanData = new SpanLabel(data.get(i)[j]);
spanData.setUIID("SpanLabel");
ShowEvent.add(spanData);
}
Label space = new Label("=======================");
ShowEvent.add(space);
Log.p("###################");
}
data.clear();
if(i>0){
if(Dialog.show("Choose action", "What you want to do?", "Add Events","View Events")){
calendar.show();
}
else{
ShowEvent.show();
}
}else{
Dialog.show("Add event","There is no event to display, Please add events first","OK","");
}
//============================================================================================================
}
});
}
#Override
protected void initComponent(){
ArrayList<String[]> data1 = new ArrayList<>();
int k;
Log.p("initComponent");
try{
cur = db.executeQuery("select Date from CalendarData");
columns = cur.getColumnCount();
if(columns > 0) {
boolean next = cur.next();
if(next) {
String[] columnNames = new String[columns];
for(int iter = 0 ; iter < columns ; iter++) {
columnNames[iter] = cur.getColumnName(iter);
}
while(next) {
Row currentRow = cur.getRow();
String[] currentRowArray = new String[columns];
for(int iter = 0 ; iter < columns ; iter++) {
currentRowArray[iter] = currentRow.getString(iter);
}
data1.add(currentRowArray);
next = cur.next();
}
Object[][] arr = new Object[data1.size()][];
data1.toArray(arr);
}
}
}catch(IOException e){
e.printStackTrace();
}
for(k = 0 ; k< data1.size(); k++){
Log.p(data1.get(k)[0]);
}
if(k>0){
//cal.setUIID("CalendarSelectedDay");
}
}
/*
#Override
protected boolean isInitialized(){
boolean result = false;
Log.p("isInitialised");
return result;
}*/
public Customised(){
}
#Override
protected Button createDay() {
Button day = new Button();
day.setAlignment(CENTER);
day.setUIID("CalendarDay1");
day.setEndsWith3Points(false);
day.setTickerEnabled(false);
return day;
}
}
And the expected result will be:-
That's because you placed the code inside the actionPerformed method which is only triggered upon Button pressed/released.
Move your code to the updateButtonDayDate scope

How to update cards data on click of button which is in fragment

I have fragment called Receipt,in which i have spinner which loads customers below is the enter amount field and then button ADJUST and below is the recycle view displaying bills.
I need to update the cards data on clicking adjust button.
How to handle it ?? can somebdy help out. How to trigger cards
Here is ma code for Receipt Fragment
code for button adjust
// adjust bills
btnAdjust.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!editTxtAmount.getText().toString().equals(0)){
OrderApplication.ENTERED_BILL_AMOUNT = Integer.parseInt(editTxtAmount.getText().toString());
Log.e("ENTERED_AMOUNT ",OrderApplication.ENTERED_BILL_AMOUNT + "");
}
}
});
and here is my adapter for bills
#Override
public void onBindViewHolder(final ViewHolder viewHolder, int i) {
final Reciept items = aBillArr.get(i);
viewHolder.textDate.setText(items.getrecptDate());
viewHolder.txtVBillNo.setText(items.getBillNo() + "");
viewHolder.textVamount.setText(items.getOrdAmnt() + "");
viewHolder.textVpendingAmnt.setText(items.getPendingAmnt());
int enteredAmnt,paidAmount = 0;
String billNo;
enteredAmnt = OrderApplication.ENTERED_BILL_AMOUNT;
Log.e("Prachi","Entered Amount" +enteredAmnt);
if(enteredAmnt != 0){
for(int j = 0 ; j < aBillArr.size() ; j ++){
int pendingAmount = Integer.parseInt(aBillArr.get(j).getPendingAmnt());
// billNo = Integer.parseInt(items.getbillNo());
billNo = aBillArr.get(j).getBillNo();
if(enteredAmnt > pendingAmount){
enteredAmnt = enteredAmnt - pendingAmount ;
paidAmount = paidAmount + pendingAmount ;
pendingAmount = 0 ;
db.updateReceipt(billNo,pendingAmount,paidAmount);
viewHolder.textVpendingAmnt.setText(items.getPendingAmnt());
Log.e("Prachi","Bill No" +billNo);
Log.e("Prachi","Pending Amount" +pendingAmount);
Log.e("Prachi","Paid Amount" +paidAmount);
}
else if(enteredAmnt < pendingAmount){
enteredAmnt = enteredAmnt - pendingAmount ;
paidAmount = paidAmount + pendingAmount ;
pendingAmount = abs(pendingAmount - enteredAmnt) ;
db.updateReceipt(billNo,pendingAmount,paidAmount);
viewHolder.textVpendingAmnt.setText(items.getPendingAmnt());
}
else if( enteredAmnt == pendingAmount){
enteredAmnt = enteredAmnt - pendingAmount ;
paidAmount = paidAmount + pendingAmount ;
pendingAmount = 0;
db.updateReceipt(billNo,pendingAmount,paidAmount);
viewHolder.textVpendingAmnt.setText(items.getPendingAmnt());
}
}
}
}

Java Array Sorting based on multiple parameters

I have an array that I want to sort in ascending order. However, I want to sort them with reference to a boolean array.I would like to sort the values that are true in ascending order, followed by the values that are false in ascending order.
Little stuck on how to get there.
This is what I have currently:
Object[] arr = new Object[6];
arr[0] = new Object(2);
arr[1] = new Object(5);
arr[2] = new Object(3);
arr[3] = new Object(1);
arr[4] = new Object(6);
arr[5] = new Object(4);
Available[] avalarr = new Available[6];
availarr[0] = new Available (true);
availarr[1] = new Available (false);
availarr[2] = new Available (false);
availarr[3] = new Available (true);
availarr[4] = new Available (true);
availarr[5] = new Available (false);
I need the output to be:
1 2 6 3 4 5
Code:
import java.util.Arrays;
public class SelectiveSort {
public static void main(String[] args) {
Item [] items = new Item [6];
items[0] = new Item(2, true);
items[1] = new Item(5, false);
items[2] = new Item(3, false);
items[3] = new Item(1, true);
items[4] = new Item(6, true);
items[5] = new Item(4, false);
System.out.println("Before Sorting:");
// Removed enhanced for loop
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
// Sorting
Arrays.sort(items);
System.out.println("\n\nAfter Sorting:");
// Removed enhanced for loop
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
System.out.println();
}
}
class Item implements Comparable<Item> {
private int _intValue;
private boolean _boolValue;
public Item(int intValue, boolean boolValue) {
_intValue = intValue;
_boolValue = boolValue;
}
public int getIntValue() { return _intValue; }
public boolean getBoolValue() { return _boolValue; }
#Override
public int compareTo(Item otherItem) {
// Using explicit comparison
int boolComparison = (_boolValue == otherItem._boolValue) ? 0 :
(_boolValue) ? 1 : -1;
return (boolComparison != 0) ? -boolComparison :
( (_intValue == otherItem.getIntValue()) ? 0 :
(_intValue > otherItem.getIntValue()) ? 1 : -1);
}
}
Output:
Before Sorting:
2 5 3 1 6 4
After Sorting:
1 2 6 3 4 5
Explanation:
The idea is to let your "Item" implement Comparable, and override the compareTo(Item otherItem) function based on the desired order.
Once that is done, all you need to do is to call Arrays.sort() on your array of Item.
Version 2 (w/o Comparable/Comparator):
public class SelectiveSort {
public static void main(String[] args) {
Item [] items = new Item [6];
items[0] = new Item(2, true);
items[1] = new Item(5, false);
items[2] = new Item(3, false);
items[3] = new Item(1, true);
items[4] = new Item(6, true);
items[5] = new Item(4, false);
System.out.println("Before Sorting:");
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
// Sorting
bubbleSort(items);
System.out.println("\n\nAfter Sorting:");
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
System.out.println();
}
public static void bubbleSort(Item [] items) {
int n = items.length;
do {
int newN = 0;
for(int i = 1; i < n; i++) {
if(compareTo(items[i-1], items[i]) == 1) {
Item temp = items[i-1];
items[i-1] = items[i];
items[i] = temp;
newN = i;
}
}
n = newN;
} while (n != 0);
}
public static int compareTo(Item item1, Item item2) {
int boolComparison = (item1.getBoolValue() == item2.getBoolValue())
? 0 : (item1.getBoolValue()) ? 1 : -1;
return (boolComparison != 0) ? -boolComparison :
( (item1.getIntValue() == item2.getIntValue()) ? 0 :
(item1.getIntValue() > item2.getIntValue()) ? 1 : -1);
}
}
(To expand on my comment:
You need a basic "thing":
class Thing {
boolean newAvailable;
int order;
public Thing(boolean newAvailable, int order) {
...
}
}
...and a Comparable...
class CompareThings implements Comparator<Thing> {
...
int compare(Thing t1, Thing t2) {
if (t1.newAvailable!=t2.newAvailable)
return t1.newAvailable==true ? 1 : -1;
return t1.order-t2.order;
}
}
(Note that t1.newAvailable==true is redundant, but I think it clarifies what's going on here.)
Now build an array of Thing and call Arrays.sort(Thing[] things, CompareThings);

Listview shows previous item as checked android

I have alertdialog with listview and listview header with "check all" and "uncheck all" button and listview footer with "Done" button. Listview is CHOICE_MODE_MULTIPLE with arrayList value EavesList. EavesList will be cross checked with another arrayList selectedItems to show those items as checked. the issue i am facing is Listview shows correct value but shows previous item as checked.
Here's my code:
AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
builder.setTitle("Select Category List");
final ListView modeList = new ListView(getActivity());
LayoutInflater inflater = LayoutInflater.from(getActivity());
View rootView = inflater.inflate(
R.layout.listview_header_eavesdrop, null);
modeList.addHeaderView(rootView);
Button btnDone = new Button(getActivity());
btnDone.setText("Done");
btnDone.setTextColor(getActivity().getResources().getColor(
android.R.color.white));
final ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(
getActivity(),
android.R.layout.simple_list_item_multiple_choice,
android.R.id.text1, EavesList);
modeList.addFooterView(btnDone);
modeList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
modeList.setAdapter(modeAdapter);
if (selectedItems.size() != 0) {
for (int i = 0; i < EavesList.size(); i++) {
if (selectedItems.size() != 0) {
// modeList.setItemChecked(2, true);
for (int j = 0; j < selectedItems.size(); j++) {
if (EavesList.get(i).contains(
selectedItems.get(j))) {
modeList.setItemChecked(i, true);
Log.e("Selected Item ",
"there Values true "
+ selectedItems.get(j));
j = selectedItems.size() + 2;
}
}
} else {
Log.e("Selected Item ", "No Values");
}
}
} else {
for (int i = 0; i < EavesList.size(); i++) {
if (category.size() != 0) {
for (int j = 0; j < category.size(); j++) {
if (EavesList_id.get(i).contains(category.get(j))) {
modeList.setItemChecked(i, true);
Log.e("List " + EavesList_id.get(i), ""+ category.get(j));
Log.e("Selected category Item ",
"there Values true "
+ category.get(j));
} else {
if (j == category.size()) {
modeList.setItemChecked(i, false);
Log.e("Selected category Item ",
"there Values false "
+ category.get(j));
}
}
}
} else {
Log.e("Selected Item ", "No Values");
}
}
}
builder.setView(modeList);
final Dialog dialog = builder.create();
btnDone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
selectedItems.clear();
eavesdropping.setText("");
SparseBooleanArray checked = modeList
.getCheckedItemPositions();
selected_community_id = new String[checked.size()];
String[] evas_id;
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
selectedItems.add(EavesList.get(position));
selected_community_id[i] = EavesList_id
.get(position);
}
for (int i = 0; i < selected_community_id.length; i++) {
eavesdropping_hide.append(selected_community_id[i]);
if (i != selected_community_id.length ) {
eavesdropping_hide.append(",");
}
}
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
eavesdropping.append(outputStrArr[i]);
eavesdropping.append(" | ");
}
dialog.dismiss();
}
});
dialog.show();
P.S: Listview shows proper content but the checked item of listview is always one previous item is always checked and the item to be checked is unchecked.
Why don't try this method on your submit button click
SparseBooleanArray sparseBooleanArray = list.getCheckedItemPositions();
List<String> lstCheck= new ArrayList<String>();
for (int i = 0; i < list.getCount(); i++) {
if (sparseBooleanArray.get(i) == true) {
lstCheck.add(list.getItemAtPosition(i).toString());
}
}
Now as lstCheck will result in only the checked values compare it with your EavesList and find those items that do not exist and you will also have you non-selected values
Use the following: (it is pseudo code):
ArrayList<String> data;
ArrayList<String> checkboxes;
.....
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
if(chockBoxes.containds(data.get(position))){
chockBoxes.remove(data.get(position));
}else{
chockBoxes.add(data.get(position))
}
}
});
...
now in your adapter getView():
if(checkBoxes.contains(data.get(position))){
checkBox.setChecked(true);
}else{
checkBox.setChecked(false);
}

Categories