Programmatically created textviews not displaying correctly or saving - android

I have an activity setup with an edittext field and an add button. Essentially when the user makes changes to the edittext and hits Add, a new textview should be created with the edittext field. In addition i want the textviews created to be available even after i leave the screen or activity. The problem i have is that when i click add, a default values shows in the newly created textview each time, and when i leave the activity, all the textviews are gone altogether. Any suggestions?
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.adddocnote);
etDocNote = (EditText) findViewById(R.id.editDocNote);
btnAdd1 = (Button) findViewById(R.id.btnAdd1);
nLayout = (LinearLayout) findViewById(R.id.linearLayout);
TextView tvNote = new TextView(this);
tvNote.setText("");
btnAdd1.setOnClickListener(onClick());
etDocNote.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v1, int keyCode1, KeyEvent event1) {
if ((event1.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode1 == KeyEvent.KEYCODE_ENTER)) {
getSharedPreferences("myprefs", 0).edit().putString("etDocNote", etDocNote.getText().toString()).commit();
return true;
}
return false;
}
});
}
private OnClickListener onClick() {
// TODO Auto-generated method stub
return new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
String newDocNote = getSharedPreferences("myprefs", 0).getString("etDocNote", "" );
nLayout.addView(createNewTextView(newDocNote));
}
};
}
private TextView createNewTextView(String newText) {
// TODO Auto-generated method stub
LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tvNote = new TextView(this);
tvNote.setLayoutParams(lparams);
tvNote.setText(newText);
return tvNote;
}
}

So your question has two parts:
How do you correctly add the textView with the text from the editText:
Right now you have a timing issue. You are trying to save in shared preferences the text when someone punched keys. This is not necessary since you can retrieve the editText contents when the add button is clicked.
Here is what you need to do: Remove setOnKeyListener and change your onClick() function to be
return new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
String value = etDocNote.getText().toString();
nLayout.addView(createNewTextView(value));
// Save to shared preferences
getSharedPreferences("myprefs", 0).edit().putString("etDocNote", value).commit();
}
};
How do you restore your view when you return to the activity.
Since your text is now saved in shared preferebnces. In your oncreate, you need to retrieve and restore your TextViews.

Related

Android dynamic listview added position

Hi I am working with android listview.I want to create a dynamic list view in which user can add data dynamically to listview .So far its works fine. Now my problem is my contets are added at start position of listview .I want to add the added contents at last position of list view (like adding comments in facebook post). Is it possible to make ?? Please help me .Thanks in advance :)
MY activity class
public class MainActivity extends Activity {
private EditText etInput;
private Button btnAdd;
private ListView lvItem;
private ArrayList<String> itemArrey;
private ArrayAdapter<String> itemAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpView();
}
private void setUpView() {
// TODO Auto-generated method stub
etInput = (EditText)this.findViewById(R.id.editText_input);
btnAdd = (Button)this.findViewById(R.id.button_add);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
etInput.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_ENTER) {
addItemList();
}
return true;
}
});
}
protected void addItemList() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
if (isInputValid(etInput)) {
itemArrey.add(0,etInput.getText().toString());
etInput.setText("");
itemAdapter.notifyDataSetChanged();
}
}
protected boolean isInputValid(EditText etInput2) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
etInput2.setError("Please Enter Item");
return false;
} else {
return true;
}
}
}
Remove position from
itemArrey.add(0,etInput.getText().toString()); // Position=0
Try this way.
itemArrey.add(etInput.getText().toString());
that directly add your string at the end.
You are specifying position to add new element to. Just avoid using position and new item will be added at the end of list.
itemArrey.add( etInput.getText().toString() );
Further more, you might also like to scroll down to this newly added item. So you can use these in xml
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll"
or use setSelection() to do so like -
lvItem.setSelection(countOfItems-1);

Android Trouble with Edit Text Views

In my application,on press of a button "Add contact" phone book gets open and then user selects a contact that get displayed in Edittext View and when another button "Add More Contacts" is pressed, a another Edit-Text View gets displayed on the top for which i can again select the contact from phone book. But the problem that i am facing is that i want that user can only add up to 5 Edit Text .
I am using the following code, but its force crashing the application. Please help.
And also i want the Edit Text Views to be non editable, for which i tried editable=false but its working only for the first Edit Text View not on the other Views, that user adds afterwards.
int id = 1;
layoutLinear = (LinearLayout) findViewById(R.id.mLayout);
btn_addmore_cntct = (Button) findViewById(R.id.baddmorecontacts);
btn_addmore_cntct.setOnClickListener(OnClick());
EditText editview = new EditText(this);
editview.setText("Add more");
editview.setEnabled(false);
editview.setFocusable(false);
}
// implementing OnClickListener OnClick() method for "btn_addmore_cntct"
// button
private OnClickListener OnClick() {
// TODO Auto-generated method stub
// changing return type "null" to "new OnClickListner"
return new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(layoutLinear.getChildCount()>5){
}else{
final EditText tab = new EditText(getApplicationContext());
tab.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
tab.setId(id);
id++;
layoutLinear.addView(tab,0);
tab.requestFocus();
}
Just check number of layoutLinear child
if(layoutLinear.getChildCount()>5){
//nothing to do
}else{
//create new EditText and add to layoutLinear
}
user this code to disable EditText
edittext.setEnabled(false);
edittext.setFocusable(false);
You can use following way.
int temp;
public void onCreate(Bundle savedinstance) {
super.onCreate(savedinstance);
setContentView(R.layout.yourlayout);
temp=1;
layoutLinear = (LinearLayout) findViewById(R.id.mLayout);
btn_addmore_cntct = (Button) findViewById(R.id.baddmorecontacts);
btn_addmore_cntct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(temp<=5){
EditText tab = new EditText(getApplicationContext());
tab.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
tab.setEnabled(false);
tab.setFocusable(false);
layoutLinear.addView(tab);
temp++;
}else{
//Print message to user Cant add more editText.
}
}
});
}
Let me know its working or not.

How two build two line of text and one image in one item?

i am using java android .
i have a problem in my app and i need some code that can make my item has two lines of texts and one image .
please save me and help .
here is the code for what i tried please make sure that you can help and give your opinion and how i can solve it cause i stucked here.
the main activity
private void setUpView() {
// TODO Auto-generated method stub
etInput = (EditText)this.findViewById(R.id.editText_input);
Pinput = (EditText)this.findViewById(R.id.editText1);
btnAdd = (Button)this.findViewById(R.id.button_add);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
etInput.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_ENTER){
addItemList();
}
return false ;
}
});
Pinput.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(keyCode== KeyEvent.KEYCODE_NUM) {
addItemList();
}
return;
}
});
}
protected void addItemList() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
if (isInputValid(Pinput )) {
itemArrey.add(Pinput.getText().toString());
itemArrey.add(etInput.getText().toString());
Pinput.setText("");
etInput.setText("");
itemAdapter.notifyDataSetChanged();
} if (isInputValid(etInput )) {
itemArrey.add(Pinput.getText().toString());
itemArrey.add(etInput.getText().toString());
Pinput.setText("");
etInput.setText("");
itemAdapter.notifyDataSetChanged();
}
}
protected boolean isInputValid(EditText etInput2 ) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
return false;
} else {
return true;
}
}
}
If you want a custom view in your ListView I recommend doing one xml layout by yourself and replace android.R.layout.simple_list_item_1 in your Adapter call with the new created one.
This would be the easiest way but as I think that you might need more freedom to create/modify the content of the row, I strongly suggest to create your own Adapter extending from BaseAdapter. In the getView() method of the adapter you can easily inflate and set up the layout like you want for that row.
Okie... you tag android-listview and list view item. So I think you need list view with image and and Text.
For that you have to use Custom List View.
See this
May be this will help you. and not then pls make your que more clear. :)

retrieving and restoring textview information from sharedpreferences

I have an activity that allows user to enter notes and store them in dynamically created textviews. However, when the use leaves the activity and returns, all the created textviews disappear. How can i store store or retrieve all of these created textviews, whenever i return to the activity? Also, i think that my sharedpreferences will be overwriting each time a new textview is added. Any suggestions?
public class DocNoteActivity extends Activity {
private LinearLayout nLayout;
private EditText etDocNote;
private Button btnAdd1;
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.adddocnote);
etDocNote = (EditText) findViewById(R.id.editDocNote);
btnAdd1 = (Button) findViewById(R.id.btnAdd1);
nLayout = (LinearLayout) findViewById(R.id.linearLayout);
TextView tvNote = new TextView(this);
tvNote.setText("");
btnAdd1.setOnClickListener(onClick());
}
private OnClickListener onClick() {
// TODO Auto-generated method stub
return new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
String newDocNote = etDocNote.getText().toString();
nLayout.addView(createNewTextView(newDocNote));
getSharedPreferences("myprefs", 0).edit().putString("etDocNote", newDocNote).commit();
}
};
}
private TextView createNewTextView(String newText) {
// TODO Auto-generated method stub
LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tvNote = new TextView(this);
tvNote.setLayoutParams(lparams);
tvNote.setText(newText);
return tvNote;
}
}
If you want to retrieve the Notes you have to use the Database (i.e. SQLite) because every time you save the notes in SharedPreferences it will be override. So I recommend you to use the Database. For that here are some useful resources which i think help you.
1 - http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
2 - http://www.vogella.com/articles/AndroidSQLite/article.html
3 - http://android-er.blogspot.in/2011/06/simple-example-using-androids-sqlite_02.html
NOTE - SharedPreferences are used to store key-value pair data. Mostly it is we can say one kind of Session Management in Android way. I mostly store username & password kind of data in SharedPreferences.
Hope this helps.

Create and validate check box programmatically using Java in Android

I need to create a number of check boxes programmatically using Java, check if one of them is checked and when I click Next Button the control will move to next page. If none of them is checked a toast message has to be displayed. Please suggest as I am new to Android.
Here is my code:
public class TestValidCheckboxActivity extends Activity implements OnCheckedChangeListener{
private RelativeLayout layoutMiddle = null;
private TableLayout layout1;
private CheckBox chk;
private String[] resarr = {"silu", "pinky", "meera"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
layoutMiddle = (RelativeLayout)findViewById(R.id.layoutMiddleUp);
layout1 = (TableLayout)findViewById(R.id.tableId1);
final Button btnNext = (Button)findViewById(R.id.btnNext);
int i = 0;
for(String res: resarr){
TableRow tr=new TableRow(this);
chk=new CheckBox(this);
chk.setId(i);
chk.setText(res);
chk.setTextColor(Color.BLACK);
tr.addView(chk);
i++;
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
lay.addRule(RelativeLayout.BELOW, layoutMiddle.getId());
layout1.addView(tr, lay);
}
chk.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
if (arg1)
{
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(final View view) {
Log.e("1111111111","111111111");
if(chk.isChecked()){
Intent intent = new Intent(view.getContext(),NextPage.class);
startActivityForResult(intent, 0);
}else{
Toast msg = Toast.makeText(view.getContext(), "please choose at least one option", Toast.LENGTH_LONG);
msg.show();
}
}
});
}else{
Toast msg = Toast.makeText(TestValidCheckboxActivity.this, "please choose at least one option", Toast.LENGTH_LONG);
}
}
});
}
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
}
}
this can be easily done
take a boolean flag and set true it on checkbox.isChecked();(inbuilt)
then check if flag is set then navigate to next else TOAST
Can you show us some of your layout code, meaning, are the checkboxes defined in an xml file and do they have IDs?
If they do, you can access each of them with findViewByID and check their status one by one.

Categories

Resources