How to create programmatically EditText and then get its value - android

I am trying to create phone fields programmatically in a form. How to identify it and subsequently get its values?.
The code that create the EditText fields and add to a form is this:
public void addTelephone(){
//form
TableLayout table = (TableLayout)findViewById(R.id.table);
//new row
TableRow tr = new TableRow(NewRequestActivity.this);
LayoutParams ltr = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ltr.setMargins(0, 0, 0, 2500);
tr.setLayoutParams(ltr);
//new field
EditText et = new EditText(NewRequestActivity.this);
et.setHint("telephone");
et.setInputType(InputType.TYPE_CLASS_NUMBER);
et.requestFocus();
Resources res = getResources();
float fontSize = res.getDimension(R.dimen.input_form) / getResources().getDisplayMetrics().density;
et.setTextSize(fontSize);
LayoutParams let = new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1);
et.setLayoutParams(let);
ImageView img = new ImageView(NewRequestActivity.this);
img.setTag("img_"+counttelf);
img.setImageResource(R.drawable.more);
img.setBackgroundResource(R.drawable.imagefocused);
img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
v.setVisibility(View.GONE);
addTelephone();
}
});
LayoutParams limg = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
img.setLayoutParams(limg);
tr.addView(et, 0);
tr.addView(img, 1);
table.addView(tr, ++indextelf);
}

You can just setTag to your EditText
Eg:
You have phone field:
editText.setTag("phone");
And when you want to retrieve it.
Just do,
EditText ed = (EditText)findViewByTag("phone");
String text = ed.getText().toString();

set Id to each dynamically created edit text and get values with reference to their id.
To set Id:
edittext.setId(i);
To get from Id:
int i = edittext.getId();

Related

Android align views in table row

I am trying to create a table with 2 textviews, edittextview and a button programmatically. My button height is not equal to rest of the elements.
I have tried removing padding and margin but the issue persisted.
Can anyone point out the error or provide a workaround to this.
code is as follows
public void populateItems()
{
// TODO : create uniform table row cells
TableLayout tl = (TableLayout)findViewById(R.id.placeOrderTable);
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.gravity=Gravity.CENTER_HORIZONTAL;
lp.bottomMargin=5;
LayoutParams lpTextView = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
lpTextView.weight=1;
lpTextView.width=0;
lpTextView.bottomMargin=1;
LayoutParams lpEditTextView = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lpEditTextView.weight=1;
lpEditTextView.width=0;
// lpEditTextView.
//lpEditTextView.
lpEditTextView.gravity=Gravity.CENTER_HORIZONTAL;
for(final HashMap<String,String> hm:mTodayItemsHashMap)
{
TableRow tr = new TableRow(getApplicationContext());
tr.setLayoutParams(lp);
TextView tvItemName = new TextView(getApplicationContext());
tvItemName.setLayoutParams(lpTextView);
tvItemName.setBackgroundResource(R.drawable.border_edittext);
tvItemName.setText(hm.get("item_name").toUpperCase());
tvItemName.setEms(10);
tvItemName.setTextColor(Color.BLACK);
tvItemName.setGravity(Gravity.CENTER);
// evItemName.setHint(getString(R.string.item_name));
TextView tvItemPrice = new TextView(getApplicationContext());
tvItemPrice.setLayoutParams(lpTextView);
tvItemPrice.setBackgroundResource(R.drawable.border_edittext);
tvItemPrice.setTextColor(Color.BLACK);
tvItemPrice.setText(hm.get("item_price").toUpperCase());
tvItemPrice.setGravity(Gravity.CENTER);
tvItemPrice.setEms(10);
// evItemPrice.setHint(getString(R.string.item_price));
final EditText evItemQty = new EditText(getApplicationContext());
evItemQty.setLayoutParams(lpTextView);
evItemQty.setInputType(InputType.TYPE_CLASS_NUMBER);
evItemQty.setBackgroundResource(R.drawable.border_edittext);
evItemQty.setTextColor(Color.BLACK);
evItemQty.setGravity(Gravity.CENTER);
evItemQty.setEms(10);
evItemQty.setFilters(new InputFilter[]{ new InputFilterMinMax("1", hm.get("max_qty"))});
// evItemQty.setL
evItemQty.setHint(getString(R.string.max_orders));
Button btnAddToCart=new Button(getApplicationContext());
btnAddToCart.setLayoutParams(lpTextView);
btnAddToCart.setText("Add to Cart");
btnAddToCart.setPadding(0, 0, 0, 0);
// btnAddToCart.setLayoutParams(params);
// btnAddToCart.setBackgroundResource(R.drawable.border_edittext);
btnAddToCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// mCart.
item=new Item();
item.setName(hm.get("item_name"));
item.setPrice(hm.get("item_price"));
String temp=evItemQty.getText().toString();
try{
Integer.parseInt(temp);
}
catch(NumberFormatException nfe){
Toast.makeText(getApplicationContext(), "Please specify quantity",Toast.LENGTH_LONG);
return;
}
item.setQty(evItemQty.getText().toString());
if(mCart==null)
mCart=new Cart();
mCart.add(item);
}
});
tr.addView(tvItemName);
tr.addView(tvItemPrice);
tr.addView(evItemQty);
tr.addView(btnAddToCart);
tl.addView(tr,tl.getChildCount()-1, tl.getLayoutParams());
}
}
You will probably want to override the background of the button. You'll get something like this:
This of course means you will not have the curved edges anymore. This can be fixed
as explained in this answer

TableLayout gets empty after phone position is changed

I got problem with my TableLayout using code - adding rows dynamically.
Whenever I change position of my phone from horizontal to vertical or vertical to horizontal all the data that was inputted to my table is getting removed and table is empty. The only things that are left are column headers (TextViews) with names coded in my program.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TableLayout tableOne = (TableLayout) findViewById(R.id.dataTable1);
tableOne.setId(110);
tableOne.setBackgroundColor(Color.WHITE);
TableRow namesRow = new TableRow(MainActivity.this);
namesRow.setId(111);
namesRow.setBackgroundColor(Color.GRAY);
namesRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
TextView productName = new TextView(MainActivity.this);
productName.setId(120);
productName.setPadding(2, 0, 40, 5);
productName.setTextSize(14);
productName.setTextColor(Color.BLACK);
productName.setText("Product Name");
namesRow.addView(productName);
TextView concentration = new TextView(MainActivity.this);
concentration.setId(130);
concentration.setPadding(0, 0, 40, 5);
concentration.setTextColor(Color.BLACK);
concentration.setTextSize(14);
concentration.setText("Concentration");
namesRow.addView(concentration);
TextView packages = new TextView(MainActivity.this);
packages.setId(140);
packages.setPadding(0, 0, 40, 5);
packages.setTextSize(14);
packages.setTextColor(Color.BLACK);
packages.setText("Packages");
namesRow.addView(packages);
TextView volume = new TextView(MainActivity.this);
volume.setId(150);
volume.setPadding(0, 0, 40, 5);
volume.setTextSize(14);
volume.setTextColor(Color.BLACK);
volume.setText("Volume");
namesRow.addView(volume);
TextView totalamount = new TextView(MainActivity.this);
totalamount.setId(160);
totalamount.setPadding(0, 0, 40, 5);
totalamount.setTextSize(14);
totalamount.setTextColor(Color.BLACK);
totalamount.setText("Total Mass");
namesRow.addView(totalamount);
TextView sacksnumber = new TextView(MainActivity.this);
sacksnumber.setId(170);
sacksnumber.setPadding(0, 0, 40, 5);
sacksnumber.setText("Number of Sacks");
sacksnumber.setTextColor(Color.BLACK);
sacksnumber.setTextSize(14);
namesRow.addView(sacksnumber);
tableOne.addView(namesRow, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
The above code is fine and never disappears but below code when I create each row from data from EditText is disappearing once I change position of the code. Kind of like it resets...
Button sncbtn1 = (Button) findViewById(R.id.sncbtn);
sncbtn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText dataName = (EditText) findViewById(R.id.productField);
EditText dataConc = (EditText) findViewById(R.id.concField);
EditText dataPack = (EditText) findViewById(R.id.packageField);
EditText dataVol = (EditText) findViewById(R.id.volField);
String prodName = dataName.getText().toString();
String concValue = dataConc.getText().toString();
String packValue = dataPack.getText().toString();
String volValue = dataVol.getText().toString();
double concDoub = Double.parseDouble(concValue);
double packDoub = Double.parseDouble(packValue);
double volDoub = Double.parseDouble(volValue);
double massResult = volDoub * concDoub;
double sacksResult = massResult / packDoub;
System.out.println(prodName + " | " + concValue + " | " + packValue + " | " + volValue);
TableRow dataRow = new TableRow(MainActivity.this);
dataRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
if(tableOne.getChildCount() % 2 == 0) dataRow.setBackgroundColor(Color.LTGRAY);
TextView prodTable = new TextView(MainActivity.this);
prodTable.setText(prodName);
prodTable.setTextSize(14);
prodTable.setTextColor(Color.BLACK);
prodTable.setGravity(Gravity.CENTER);
dataRow.addView(prodTable);
TextView concTable = new TextView(MainActivity.this);
concTable.setText(concValue);
concTable.setTextColor(Color.BLACK);
concTable.setTextSize(14);
concTable.setGravity(Gravity.CENTER);
dataRow.addView(concTable);
TextView packTable = new TextView(MainActivity.this);
packTable.setText(packValue);
packTable.setTextSize(14);
packTable.setTextColor(Color.BLACK);
packTable.setGravity(Gravity.CENTER);
dataRow.addView(packTable);
TextView volTable = new TextView(MainActivity.this);
volTable.setText(volValue);
volTable.setTextSize(14);
volTable.setTextColor(Color.BLACK);
volTable.setGravity(Gravity.CENTER);
dataRow.addView(volTable);
TextView massTable = new TextView(MainActivity.this);
massTable.setText(new DecimalFormat("0.00").format(massResult));
massTable.setTextSize(14);
massTable.setTextColor(Color.BLACK);
massTable.setGravity(Gravity.CENTER);
dataRow.addView(massTable);
TextView sacksTable = new TextView(MainActivity.this);
sacksTable.setText(new DecimalFormat("0.00").format(sacksResult));
sacksTable.setTextColor(Color.BLACK);
sacksTable.setGravity(Gravity.CENTER);
sacksTable.setTextSize(14);
dataRow.addView(sacksTable);
tableOne.addView(dataRow, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}
});
Also on my LogCat I'm getting error: getExtractedText on inactive InputConnection
I have tried to rewrite app with some tutorials/research etc thinking that I might find whats wrong but after 2 days I'm done and hopefully someone can help me.
Your onCreate gets called whenever your screen orientation is changed, one way to stop that is to add this line under your relevant activity tag in your manifest file:
android:configChanges="orientation|screenSize"
This way Android OS won't recreate the UI whenever the screen is rotated and leave it up to you.

how can i add and remove element dynamically from linear layout?

LinearLayout linContact = (LinearLayout) mView.findViewById(R.id.linContacts);
LinearLayout.LayoutParams leftGravityparas = new LinearLayout.LayoutParams(0,LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams rightGravityParams = new LinearLayout.LayoutParams(30, 30);
for (int i = 0; i < contactList.size(); i++) {
final ClsAdviserData contact = .contactList.get(i);
if (contact.isSelected()) {
linearLayout = new LinearLayout(getActivity());
LinearLayout.LayoutParams linMainparam = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
linearLayout.setBackgroundColor(getActivity().getResources().getColor(R.color.light_grey_backgeound));
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setLayoutParams(linMainparam);
linMainparam.setMargins(0, 10, 0, 0);
leftGravityparas.gravity = Gravity.LEFT;
leftGravityparas.weight = 0.9f;
TextView txtContact = new TextView(getActivity());
txtContact.setTextSize(16);
// txtContact.setBackgroundColor(getActivity().getResources().getColor(R.color.light_grey_backgeound));
txtContact.setLayoutParams(leftGravityparas);
txtContact.setId(i);
leftGravityparas.setMargins(0, 10, 0, 0);
txtContact.setPadding(20, 10, 10, 10);
txtContact.setText(contact.getName());
linearLayout.addView(txtContact, leftGravityparas);
rightGravityParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
rightGravityParams.weight = 0.1f;
final ImageView imgDelContact = new ImageView(getActivity());
imgDelContact.setLayoutParams(rightGravityParams);
imgDelContact.setTag(i);
imgDelContact.setClickable(true);
imgDelContact.setOnClickListener(this);
imgDelContact.setImageResource(R.drawable.ic_close_grey);
linearLayout.addView(imgDelContact, rightGravityParams);
// linContact.setTag(i);
linContact.addView(linearLayout);
imgDelContact.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Toast ==>" + contact.getName() + v.getTag(), Toast.LENGTH_SHORT).show();
// linContact.removeViewAt((Integer) v.getTag());
linearLayout.setVisibility(View.GONE);
// lin.removeViewAt((Integer)v.getTag());
}
});
}
}
I wrote the above code to create the textfields and buttons dynamically; But now I need to remove 2 textfields and a button when the button is clicked. How do I do that?
adding -
After initializing add subview using addView() method declared in LinearLayout
linearLayout.addView(txtContact);
linearLayout.addView(imgDelContact);
Hide -
To hide View ,so that you can get it again whenever required
imgDelContact.setVisibility(View.GONE);
txtContact.setVisibility(View.GONE);
Remove -
Or you can remove if you don't want to use it again.
linearLayout.removeView(txtContact);
linearLayout.removeView(imgDelContact);
To remove any view you can use
aLinearLayout.removeView(view)// to remove particular view
aLinearLayout.removeViewAt(position);// to remove view from particular position
If you are dynamically creating views and you just need to remove all the views just use
aLinearLayout.removeAllViews();
This will clear the layout.

Adding row with 2 columns to Android table layout - 2nd column invisible

I add columns to an android table layout in this way:
public void addWebAction(TableLayout table){
TableRow rowWeb = new TableRow(this);
rowWeb.setWeightSum(1f);
TextView tvWeb = new TextView(this);
tvWeb.setTextSize(18);
tvWeb.setPadding(0, 10, 0, 0);
tvWeb.setText(contact.getWeb());
TableRow.LayoutParams trlp = new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, 0.8f);
tvWeb.setLayoutParams(trlp);
rowWeb.addView(tvWeb);
ImageButton ibWeb = new ImageButton(this);
ibWeb.setBackgroundColor(Color.TRANSPARENT);
ibWeb.setImageResource(R.drawable.ic_action_search);
ibWeb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(contact.getWeb()));
startActivity(browserIntent);
}
});
trlp.weight = 0.1f;
ibWeb.setLayoutParams(trlp);
rowWeb.addView(ibWeb);
ImageButton abWeb = new ImageButton(this);
abWeb.setBackgroundColor(Color.TRANSPARENT);
abWeb.setImageResource(R.drawable.ic_action_chat);
abWeb.setLayoutParams(trlp);
rowWeb.addView(abWeb);
table.addView(rowWeb);
}
The problem is: If the textview contains a long string the 2nd column is moved out of the screen. In which way did I have to add TableRow Parameters to fix this?
You must give weightSum to table layout and divide edittexts weights two.
You can see the simple example in this link: https://stackoverflow.com/a/9590974/3098590

Android dynamic RelativeLayout overlaps each other

I use this code to dynamically print the vaules from my database with a buttonClick-event.
The buttonClick-event to delete the database entry is present inside the a loop.
Here my code:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout3);
final DatabaseHandler dbpin = new DatabaseHandler(this);
// Log.d("Reading: ", "Reading all tasks..");
List<Detail> detail1 = dbpin.getAllDetail();
Button[] button=new Button[1000];
for (Detail cn : detail1) {
String log = cn.getTitle();
final int i = cn.getID();
button[i] = new Button(this);
button[i].setText("Delete");
button[i].setTextSize(10);
button[i].setId(2000 + i);
int width = 80;
int height = 60;
TextView textview = new TextView(this);
textview.setText(log);
textview.setWidth(200);
textview.setTextSize(20);
textview.setPadding( 0, 10, 0, 0);
textview.setId(2000 + i);
if (i == 0) {
RelativeLayout.LayoutParams rlp2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
rlp2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
rlp2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
textview.setLayoutParams(rlp2);
rl.addView(textview);
RelativeLayout.LayoutParams rlp1 = new RelativeLayout.LayoutParams(
width, height);
rlp1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
rlp1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
button[i].setLayoutParams(rlp1);
rl.addView(button[i]);
} else {
RelativeLayout.LayoutParams rlp2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
rlp2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
rlp2.addRule(RelativeLayout.BELOW, button[i].getId() - 1);
textview.setLayoutParams(rlp2);
rl.addView(textview);
RelativeLayout.LayoutParams rlp1 = new RelativeLayout.LayoutParams(
width, height);
rlp1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
rlp1.addRule(RelativeLayout.BELOW, button[i].getId() - 1);
button[i].setLayoutParams(rlp1);
rl.addView(button[i]);
}
button[i].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(), details.class);
Detail detail = new Detail();
detail.setID(i);
dbpin.deleteDetail(detail);
startActivityForResult(myIntent, 1);
}
});
}
Following the database handler code is, to retrieve all details from database using a loop:
// Getting All detail
public List<Detail> getAllDetail() {
List<Detail> detailList = new ArrayList<Detail>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_DETAIL;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Detail detail = new Detail();
detail.setID(Integer.parseInt(cursor.getString(0)));
detail.setTitle(cursor.getString(1));
detail.setDetail(cursor.getString(2));
// Adding contact to list
detailList.add(detail);
} while (cursor.moveToNext());
}
// return contact list
return detailList;
}
// Deleting single detail
public void deleteDetail(Detail detail) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_DETAIL, KEY_DETID + " = ?",
new String[] { String.valueOf(detail.getID()) });
db.close();
}
At first the layout is normal. Deleting first or the last data row doesn't cause any change, but if a row in the middle is deleted, then the layout overlaps each other.
Please give me suggestions to clear this logical error.
Ok I have understand your problem. Problem is that you are using relative layout as your parent layout in which you are adding all your child relative layouts. Now if you delete your first relative layout then it automatically align with its parent so there will be no problem.
If you delete last relative layout then also not problem occurs.
Now you have align all your relative layout form their above layout so if you delete above one it automatically aligns to its parent.
Solution is simple. Use your parent layout as linear layout so that you dont need to align relative layouts with their above layout. It will automatically arrange in a linear way....
RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout3); convert this layout in linearlayout in your xml file.
This the code which can help you:
LinearLayout lp = (LinearLayout) findViewById(R.id.LinearLayout1);
// for loop start from here
RelativeLayout rl = new RelativeLayout(getApplicationContext());
RelativeLayout.LayoutParams lp_btn = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp_btn.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
Button temp_button = new Button(getApplicationContext());
temp_button.setText("button");
rl.addView(temp_button, lp_btn);
TextView tv = new TextView(getApplicationContext());
tv.setText("bharat");
tv.setBackgroundColor(Color.GREEN);
RelativeLayout.LayoutParams lp_tv = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp_tv.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
rl.addView(tv, lp_tv);
lp.addView(rl);
// for loop will end here
I think you should use listview for your purpose it will be better. Anyway this will also work you have to manage relativelayout array and button array for your purpose.

Categories

Resources