pass value from stringbuilder to textview - android

I am trying to get words from several EditTexts and display them using TextView without using any layout. But the program is force closed every-time I run it.
LOGCAT: java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.example.tablelayout/com.example.tablelayout.MainActivity}:
java.lang.NullPointerException
public class MainActivity extends Activity {
private List<EditText> editTextList = new ArrayList<EditText>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linearLayout = new LinearLayout(this);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(FILL_PARENT, WRAP_CONTENT);
linearLayout.setLayoutParams(params);
linearLayout.setOrientation(VERTICAL);
int count = 10;
linearLayout.addView(tableLayout(count));
linearLayout.addView(submitButton());
setContentView(linearLayout);
}
private Button submitButton() {
Button button = new Button(this);
button.setHeight(WRAP_CONTENT);
button.setText("Submit");
button.setOnClickListener(submitListener);
return button;
}
TextView txt=new TextView(this);
// Access the value of the EditText
private View.OnClickListener submitListener = new View.OnClickListener() {
public void onClick(View view) {
StringBuilder stringBuilder = new StringBuilder();
for (EditText editText : editTextList) {
stringBuilder.append(editText.getText().toString());
}
txt.setText(stringBuilder.toString().trim());
}
};
// Using a TableLayout as it provides you with a neat ordering structure
private TableLayout tableLayout(int count) {
TableLayout tableLayout = new TableLayout(this);
tableLayout.setStretchAllColumns(true);
int noOfRows = count / 5;
for (int i = 0; i < noOfRows; i++) {
int rowId = 5 * i;
tableLayout.addView(createOneFullRow(rowId));
}
int individualCells = count % 5;
tableLayout.addView(createLeftOverCells(individualCells, count));
return tableLayout;
}
private TableRow createLeftOverCells(int individualCells, int count) {
TableRow tableRow = new TableRow(this);
tableRow.setPadding(0, 10, 0, 0);
int rowId = count - individualCells;
for (int i = 1; i <= individualCells; i++) {
tableRow.addView(editText(String.valueOf(rowId + i)));
}
return tableRow;
}
private TableRow createOneFullRow(int rowId) {
TableRow tableRow = new TableRow(this);
tableRow.setPadding(0, 10, 0, 0);
for (int i = 1; i <= 5; i++) {
tableRow.addView(editText(String.valueOf(rowId + i)));
}
return tableRow;
}
private EditText editText(String hint) {
EditText editText = new EditText(this);
editText.setId(Integer.valueOf(hint));
editText.setHint(hint);
editTextList.add(editText);
return editText;
}
}

TextView txt=new TextView(this);
you can't declare and initialize a class member View at the same time, because the Context is not yet valid
change it to:
public class MainActivity extends Activity {
private List<EditText> editTextList = new ArrayList<EditText>();
private TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
txt = new TextView(this);
// other code
also I noticed that you are not adding this View to any of the containers that your provided to setContentView. The suggestion will fix the crash but you will not see the TextView's content

Exception shows problem is in your manifest file.
Your package name is manifest tag and your activity are in different locations.

Related

Android-SharedPreferences with EditText which created with For Loop

I created EditTexts with "for loop" and I want to save datas from EditText with using SharedPreferences. I can manage this with creating EditTexts via xml but this takes lots of time and efforts. Below you can see codes.With second "for loop" i have been creating 15 EditTexts (numbers will increase) and I want to store datas from those EditTexts for some calculations. How can I use SharedPreferences with "for loop" for those EditTexts?
public class MainActivity extends AppCompatActivity {
private ScrollView sV;
private LinearLayout pnl;
private GridLayout gL;
private TextView tV;
private Button btn;
private EditText eT;
private void init() {
sV = new ScrollView(this);
hsV = new HorizontalScrollView(this);
pnl = new LinearLayout(this);
pnl.setOrientation(LinearLayout.VERTICAL);
gL = new GridLayout(this);
gL.setColumnCount(2);
final String[] title = getResources().getStringArray(R.array.title);
final String[] info = getResources().getStringArray(R.array.info);
for (int j = 0; j < 2; j++) {
tV = new TextView(this);
tV.setText(title[j]);
tV.setTextSize(20);
tV.setTypeface(Typeface.DEFAULT_BOLD);
tV.setTextColor(getResources().getColor(R.color.colorText));
gL.addView(tV);
}
for (int i = 0; i < 15; i++) {
tV = new TextView(this);
tV.setText(info[i]);
tV.setTextSize(20);
tV.setTextColor(getResources().getColor(R.color.colorText));
gL.addView(tV);
eT = new EditText(this);
eT.setTextSize(20);
eT.setInputType(InputType.TYPE_CLASS_NUMBER);
gL.addView(eT);
}
btn = new Button(this);
btn.setText("Save");
gL.addView(btn);
pnl.addView(gL);
sV.addView(pnl);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
setContentView(sV);
}
}
You can add tags on your EditTexts to identify them.
You can then use these tags as keys in your SharedPreferences, something like that :
for (int i = 0; i < 15; i++) {
eT = new EditText(this);
eT.setTextSize(20);
eT.setInputType(InputType.TYPE_CLASS_NUMBER);
// adding a tag to identify the EditText
String tag = "edit" + i;
eT.setTag(tag);
gL.addView(eT);
}
How to store
#Override
public void afterTextChanged(Editable editable) {
// get values
String key = (String)editable.getTag()
String value = editable.getText().toString()
// save in SharedPreferences
sharedPreferencesEditor.putString(key, values)
sharedPreferencesEditor.commit()
}

Remove dynamically generated textviews on dynamic button click event

I need to remove each Table Rows on an individual button click event.
The Buttons are dynamically generated.
How will i achieve this?
Below is my code:
public class S2 extends Modify implements OnClickListener {
Button b;
String arry1[], category_main,str = null, catarray[];
int i,key = 0;
private static String url = "http://ashapurasoftech.com/train/test.json";
private static final String TAG_a = "menu",TAG_Name = "Name",TAG_Cat = "Category";
JSONArray items = null;
ArrayList<HashMap<String, String>> itemList;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.modify);
category_main = "";
new Getitems().execute(category_main);
b =(Button) findViewById(R.id.Order);
b.setOnClickListener(this);
itemList = new ArrayList<HashMap<String, String>>();
}
#Override
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.Order:try{ onbuttonclick();} catch(JSONException e){}
break;
}
}
private void onbuttonclick() throws JSONException {
TableRow[] tr = new TableRow[arry1.length];
final TextView[] tx = new TextView[arry1.length];
GridLayout gl = new GridLayout(S2.this);
gl.setRowCount(arry1.length);
gl.setColumnCount(1);
final TableLayout tl = (TableLayout) findViewById(R.id.tb1);
TableRow row = null;
for (i = 0; i < arry1.length; i++) {
final String cat = arry1[i].toString();
tx[i] = new TextView(S2.this);
tx[i].setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tx[i].setAllCaps(true);
tx[i].setTextSize(15);
tx[i].setText(cat);
tr[i] = new TableRow(S2.this);
tr[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tr[i].addView(tx[i],new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tl.addView(tr[i],new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
int buttonsInRow = 0;
int numRows = tl.getChildCount();
if( numRows > 0 ){
row = (TableRow) tl.getChildAt( numRows - 1 );
buttonsInRow = row.getChildCount();
}
if( numRows == 0 || buttonsInRow == 3 ){
row = new TableRow( this );
tl.addView( row );
buttonsInRow = 0;
}
if( buttonsInRow < 3 ){
Button b = new Button( this );
b.setText("Cancel");
b.setId(i);
row.addView( b, 100, 50 );
}
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
b = (Button) findViewById(i);
tl.removeView(tx[i]);
}
});
}
}
this is my screen where i want to clear each items when i click on the button aside it.
you can probably achieve what you need in
onClick(View arg0)
by getting the arg0 parent. check it is
instanceof
Table row or has a tag you set up and then set its visibility to GONE
You can use removeView method in the similar fashion you are using addView:
tr[i].removeView(<YourTextView>;

Getting dynamically added checkbox ID in Android

I'm adding a checkbox in my application dynamically, and I want to delete the records which are checked. But, I'm not getting the ID of the checkbox. How can I do this?
Code:
package com.my.StudentInfoManagement;
public class ListData extends Activity{
DataHelper dh;
TableLayout tb;
CheckBox[] ch=new CheckBox[50];
EditText ed;
int a[]=new int[50];
int k=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listdataxml);
dh=new DataHelper(this);
System.out.println("in list data");
List<String> names= this.dh.selectAll();
ed=(EditText) findViewById(R.id.ed_id);
tb=(TableLayout) findViewById(R.id.table);
int i,j=1;
TextView name1 = null,id,dob,gender,branch,email,address,mobile;
String name11,id1 = null,dob1,gender1,branch1,email1,address1,mobile1;
TableRow tr=new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
TextView tv=new TextView(this);
String c = null;
String data[]=new String[50];
int cnt=0;
for(String name:names)
{
if((!name.equals("-999")))
{
data[cnt]=name;
cnt++;
System.out.println("........."+name);
}
else
{
cnt=0;
name1=new TextView(this);
name1.setText(data[1]+" ");
id=new TextView(this);
id.setText(data[0]+" ");
System.out.println("ID is...."+data[0]);
dob=new TextView(this);
dob.setText(data[3]+" ");
gender=new TextView(this);
gender.setText(data[2]+" ");
branch=new TextView(this);
branch.setText(data[4]+" ");
mobile=new TextView(this);
mobile.setText(data[5]+" ");
email=new TextView(this);
email.setText(data[6]+" ");
address=new TextView(this);
address.setText(data[7]+" ");
tr=new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
ch[k]=new CheckBox(this);
System.out.println("sysout");
i=Integer.parseInt(data[0]);
ch[k].setId(i);
tr.addView(ch[k]);
a[k++]=i;
tr.addView(id);
tr.addView(name1);
tr.addView(dob);
tr.addView(gender);
tr.addView(branch);
tr.addView(mobile);
tr.addView(email);
tr.addView(address);
tb.addView(tr,new TableLayout.LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
j++;
System.out.println("count"+j);
}
}
}
public void delete(View v){
System.out.println("In delete");
int bb=k,id ;
for (int i=0; i <k; i++)
{
final int j = a[i];
System.out.println("in for loop"+j);
ch[j].setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
System.out.println("Checked ID :: " + ch[j].getId());
}
});
}
System.out.println("00000000000000000..."+id);
dh.deleteData(id);
}
}
strong textJust take a global variable
int chkId = 1001;
then at time of adding CheckBox dynamically, set its id as
ch.setId(++chkId);
then at time of deleting CheckBox, you can get id of Checked CheckBox simple by using
getId()
methhod
See Following Demo:
public class ChkBoxesActivity extends Activity {
int chId = 1000;
int chPos = -1;
LinearLayout ll;
String[] names = {"Tom", "Dick", "Keanu", "Harry", "Katrina", "Peter", "Julia", "Emma"};
CheckBox[] ch;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ll = (LinearLayout) findViewById(R.id.ll);
ch = new CheckBox[names.length];
for(int i=0; i<names.length; i++) {
ch[i] = new CheckBox(this);
ch[i].setId(chId++);
System.out.println("CHID :: "+chId);
System.out.println("I :: "+i);
ch[i].setText(names[i]);
ll.addView(ch[i]);
}
for (int i = 0; i < names.length; i++) {
final int j = i;
ch[j].setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
System.out.println("Checked ID :: " + ch[j].getId());
}
});
}
}
}
Views added dynamically do not have an ID until you specifically set them. So you need to call view.setId() on the view when you're adding to your layout, else you won't be able to reference it with view.getId().
I experienced a similar issue a while back when trying to dynamically create a RelativeLayout and positions the inner views relative to each other; they wouldn't align how they should have because the ID's didn't exist until I explicitly set one for them.
Also, why are you doing this:
ch.getId();
ch.setId(1);
That makes absolutely no sense. Take it out.
And also, you're going to need a reference linking the CheckBox to the View you want to delete. In this case, I would make a new ArrayList of Objects that have both a CheckBox and a View inside of it, IE.
public Class MyRow{
CheckBox c;
View v;
public MyRow() { }
}
Then when adding your views dynamically, add them to your MyRow or whatever class, then add that class to an ArrayList, and boom, you now have references between them and can remove the correct ones.

How can we create dynamic textview?

how to create the textview in code not in xml file. It is because number of textviews will be changing in my application according to some integer.
This is the code to create TextView Dynamically
LinearLayout layout = (LinearLayout ) findViewById(R.id.llayout);
for (int i = 0; i < 3; i++) {
TextView dynamicTextView = new TextView(this);
dynamicTextView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
dynamicTextView.setText("NewYork");
layout.addView(tstate);
}
Maybe thats what you need:
LinearLayout lin = (LinearLayout) findViewById(R.id.myLinear);
for (int i = 0; i <= 10 ; i++)
{
TextView myText = new TextView(this);
myText.setText("textview# "+ i);
lin.addView(myText);
}
Something like the following should be what you need:
final int N = 10; // total number of textviews to add
final TextView[] myTextViews = new TextView[N]; // create an empty array;
for (int i = 0; i < N; i++) {
// create a new textview
final TextView rowTextView = new TextView(this);
// set some properties of rowTextView or something
rowTextView.setText("This is TextView #" + i);
// add the textview to the linearlayout
myLinearLayout.addView(rowTextView);
// save a reference to the textview for later
myTextViews[i] = rowTextView;
}
private LinearLayout ll;
private TextView tv;
// in oncreate()
onCreate()
{
int WrapWidth = LinearLayout.LayoutParams.WRAP_CONTENT;
int WrapHeight = LinearLayout.LayoutParams.WRAP_CONTENT;
tv = new TextView(this);
ll.addView(tv,WrapWidth,WrapHeight);
}
Code is here
final int c = 12;
final TextView[] mtext = new TextView[c];
for (int i = 0; i < c; i++) {
TextView rowtxt = new TextView(this);
rowtxt.setText("Hello" + i);
myLinearLayout.addView(rowtxt);
myTextViews[i] = rowtxt;
myTextViews[i].setOnClickListener(onclicklistener);//textview click
}
OnClickListeners code is here
OnClickListener onclicklistener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == myTextViews[0]){
//do whatever you want....
}
}
};
Hope it is helpful for you
You use TextView textView = new TextView(CurrentActivity.this);
and then you add setter arguments that come with the TextView class

table row selection error in scrollview

i am creating a table layout with radio group by dynamically adding radiobuttons to it and i want to know which row is selected containing the radio group and i want to retrive the texview data also in the same row .how can i do that any suggestion will be a great help for me.
public class TabActivity extends Activity {
TableLayout table;
RadioGroup mRadioGroup;
ArrayList<String> list_name;
int color_blue = -16776961;
int color_gray = -7829368;
int color_black = -16777216;
int color_white = -1;
final int CHECK_BUTTON_ID = 982301;
int ids_check[];
boolean bool_check[];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
table = (TableLayout) findViewById(R.id.tableLayout1);
list_name = new ArrayList<String>();
list_name.add("Close");
list_name.add("Cristiano");
list_name.add("David");
list_name.add("Fernando");
list_name.add("Messi");
list_name.add("Kaka");
list_name.add("Wayne");
list_name.add("use");
list_name.add("e");
list_name.add("eff");
list_name.add("euyr");
list_name.add("ejjyytuty");
list_name.add("madre");
list_name.add("yuir");
list_name.add("eyrty");
list_name.add("etytr");
list_name.add("ewrrtt");
bool_check = new boolean[list_name.size()];
ids_check = new int[list_name.size()];
createTableRows();
}
public void createTableRows()
{
for (int i = 0; i < list_name.size(); i++)
{
final TableRow table_row = new TableRow(this);
TextView tv_name = new TextView(this);
Button btn_check = new Button(this);
ImageView img_line = new ImageView(this);
table_row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
table_row.setBackgroundColor(color_black);
table_row.setGravity(Gravity.CENTER_HORIZONTAL);
// table_row.setFocusable(true);
mRadioGroup = new RadioGroup(this);
// test adding a radio button programmatically
final RadioButton[] mbutton=new RadioButton[7];
for(int l=0;l<7;l++){
mbutton[l]=new RadioButton(this);
mbutton[l].setText("test"+l);
mRadioGroup.addView(mbutton[l]);
}
// LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
// RadioGroup.LayoutParams.WRAP_CONTENT,
// RadioGroup.LayoutParams.WRAP_CONTENT);
// mRadioGroup.addView(newRadioButton);
tv_name.setText((CharSequence) list_name.get(i));
tv_name.setTextColor(color_blue);
tv_name.setTextSize(30);
tv_name.setTypeface(Typeface.DEFAULT_BOLD);
tv_name.setWidth(150);
btn_check.setLayoutParams(new LayoutParams(30, 30));
btn_check.setBackgroundResource(R.drawable.small_checkbox_unchecked);
img_line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 2));
img_line.setBackgroundResource(R.drawable.separater_line);
table_row.addView(tv_name);
table_row.addView(btn_check);
table_row.addView(mRadioGroup);
table.addView(table_row);
table.addView(img_line);
//table.addView(mRadioGroup);
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup mRadioGroup, int checkedId) {
for(int i=0; i<mRadioGroup.getChildCount(); i++) {
RadioButton btn = (RadioButton) mRadioGroup.getChildAt(i);
int t=table.indexOfChild(table_row);
System.out.println(t);
if(btn.getId() == checkedId) {
String text = btn.getText().toString();
// do something with text
Log.d(text," event1");
return;
}
}
}
});
}
}
}
Why are you not using ListView ? there's nothing in the code that cannot be done by a list view?
You can add you layout by setting the custom adapter.

Categories

Resources