Can someone help with this? My EditText is not empty but the toast still shows up. My app require users to select Date and Time, then select 1 item on the listview to proceed. A dialog will pop out after that. However for some reason, even though my edittext isn't empty, it still won't allow me to continue. I can't seem to figure out what's wrong, I mean the code is just that simple, nothing complicate.
final String date = textDate1.getText().toString().trim();
final String time = textTime1.getText().toString().trim();
listViewHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final Team team = teams.get(i);
if(TextUtils.isEmpty(date)){
Toast.makeText(RecreateActivity.this,"Please choose a date.",Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(time)){
Toast.makeText(RecreateActivity.this,"Please choose a time.",Toast.LENGTH_LONG).show();
return;
}
//the rest of the code
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(RecreateActivity.this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.confirm_layout, null);
dialogBuilder.setView(dialogView);
final Button buttonYes2 = (Button) dialogView.findViewById(R.id.buttonYes2);
final Button buttonNo2 = (Button) dialogView.findViewById(R.id.buttonNo2);
//final Team team = teams.get();
final AlertDialog b = dialogBuilder.create();
b.show();
buttonYes2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
databaseMembers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final ArrayList<String> CheckList = new ArrayList<String>();
for (DataSnapshot check : dataSnapshot.child("teams").getChildren()) {
CheckList.add(check.getKey());
}
if (CheckList.contains(team.getTeamName())) {
Toast.makeText(RecreateActivity.this, "Team already exist.", Toast.LENGTH_LONG).show();
return;
}
databaseMembers.child("History").child(team.getTeamName()).child("date").setValue(date);
databaseMembers.child("History").child(team.getTeamName()).child("time").setValue(time);
for (DataSnapshot history : dataSnapshot.child("History").child(encodedEmailAddress).getChildren()) {
String key = history.getKey();
if (key.equals(team.getTeamName())) {
teams.clear();
Team team = history.getValue(Team.class);
teams.add(team);
databaseTeams.child(team.getTeamName()).setValue(team);
}
if (key.equals("teamMember")) {
for (DataSnapshot members : dataSnapshot.child("History").child(encodedEmailAddress).child("teamMember").getChildren()) {
String key2 = members.getKey();
String value = members.getValue(String.class);
Map<String, Object> map = new HashMap<>();
map.put(key2, value);
databaseMembers.child("members").child(team.getTeamName()).child("teamMember").updateChildren(map);
b.dismiss();
}
}
}
Toast.makeText(RecreateActivity.this, "Team created.", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(RecreateActivity.this,
MainActivity.class);
startActivity(myIntent);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
XML:
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Previous Team"
android:textAppearance="#style/TextAppearance.AppCompat.Title"
android:textAlignment="center"/>
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select new Date/Time and tap on the Team."
android:textAlignment="center"/>
<ListView
android:id="#+id/listViewHistory"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</ListView>
<TextView
android:id="#+id/textView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Members:"
android:textAppearance="#style/TextAppearance.AppCompat.Headline" />
<TextView
android:id="#+id/textViewList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="#style/TextAppearance.AppCompat.Medium" />
<EditText
android:id="#+id/textDate1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Select Date..."
android:layout_alignParentStart="true" />
<EditText
android:id="#+id/textTime1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Select Time..."
android:layout_below="#+id/textDate"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/buttonAddHistory"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Create Team"
android:textAlignment="center"
android:textAllCaps="false"
tools:textSize="20sp" />
You are getting string from EditText only once - before setting OnItemClickListener. You need to get string inside the listener.
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final Team team = teams.get(i);
final String date = textDate1.getText().toString().trim();
final String time = textTime1.getText().toString().trim();
if(TextUtils.isEmpty(date)){
Toast.makeText(RecreateActivity.this,"Please choose a date.",Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(time)){
Toast.makeText(RecreateActivity.this,"Please choose a time.",Toast.LENGTH_LONG).show();
return;
}
}
Your field is initialized only once. I don't know the context, this may be actually what you want, but then it doesn't make any sense to validate it every time, those fields have the same value every time the listener code is run. Try to add the code to get date and time in the listener itself.
Your code is setting [date] and [time] outside of the onClickListener. When the user clicks the button, your code isn't resetting the variables. I'd evaluate the EditText directly from your onClickListener code:
listViewHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final Team team = teams.get(i);
if(TextUtils.isEmpty(textDate1.getText().toString().trim())){
Toast.makeText(RecreateActivity.this,"Please choose a date.",Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(textTime1.getText().toString().trim())){
Toast.makeText(RecreateActivity.this,"Please choose a time.",Toast.LENGTH_LONG).show();
return;
}
Try getting date value of edittext inside the click listener.
listViewHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final Team team = teams.get(i);
final String date = textDate1.getText().toString().trim();
final String time = textTime1.getText().toString().trim();
if(date.isEmpty()){
Toast.makeText(RecreateActivity.this,"Please choose a date.",Toast.LENGTH_LONG).show();
return;
}
if(time.isEmpty()){
Toast.makeText(RecreateActivity.this,"Please choose a time.",Toast.LENGTH_LONG).show();
return;
}
Related
Actually I have update item option in database when I click its position on listView.
Code in onCreate method:
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listViewOrganizacje, View view, int position, long id) {
Intent intent = new Intent(BazaDanych.this, BazaDanychAktualizacja.class);
intent.putExtra(BazaDanychAktualizacja.EXTRA_ORGANIZACJA_ID, (int) id);
startActivity(intent);
}
};
listViewSeriale.setOnItemClickListener(itemClickListener);
And it work fine. But I added "update" button for my items on listView and I would like to use it and use the same code like above but I don't know how to use it with button on list.
My update button preferences in .xml:
<Button
android:id="#+id/updateButton"
style="#android:style/Widget.Holo.Button"
android:layout_width="36dp"
android:layout_height="25dp"
android:layout_weight="1"
android:background="#000000"
android:text="update"
android:textAlignment="center"
android:textAllCaps="false"
android:textSize="15dp"
android:onClick="clickUpdateButton"
/>
And here is a method where I try to use it:
public void clickUpdateButton(View view) {
// AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
// #Override
// public void onItemClick(AdapterView<?> listViewOrganizacje, View view, int position, long id) {
// Intent intent = new Intent(BazaDanych.this, BazaDanychAktualizacja.class);
// intent.putExtra(BazaDanychAktualizacja.EXTRA_ORGANIZACJA_ID, (int) id);
// startActivity(intent);
// }
// };
// listViewSeriale.setOnItemClickListener(itemClickListener);
}
Problem solved.
Here is a solution code in clickUpdateButton method:
int position = listViewSeriale.getPositionForView((View)view.getParent());
Cursor c = (Cursor) listAdapter.getItem(position);
String id = cursor.getString(0); // column number in database
I am working on android application in my application there are registration page in that page i am using #slackid, when user fill the registration form and enter slack id without # its show validation message like # is necessary. Than he move to the next. Kindly please tell me how i use this # validation message. Here is the code
activity_registration.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".RegisterActivity">
<EditText
android:id="#+id/name_reg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Your Name"/>
<EditText
android:id="#+id/email_reg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Your email id"
android:inputType="textEmailAddress"/>
<EditText
android:id="#+id/slackid_reg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint=" #slackId"/>
<EditText
android:id="#+id/password_reg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Password"/>
<EditText
android:id="#+id/confirm_password_reg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Retype Password"/>
<EditText
android:id="#+id/info_reg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Information/Phone no/Optional"/>
<Button
android:id="#+id/register_reg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:text="Register"/>
</LinearLayout>
RegistrationActivity.java
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
private EditText name,emailId,slackId,password,conPasword,info;
private Button registerB;
// Alert dialog
AlertDialog.Builder alertBuilder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
name = findViewById(R.id.name_reg);
emailId = findViewById(R.id.email_reg);
slackId = findViewById(R.id.slackid_reg);
password = findViewById(R.id.password_reg);
conPasword = findViewById(R.id.confirm_password_reg);
info = findViewById(R.id.info_reg);
registerB = findViewById(R.id.register_reg);
//set register to onClick event
registerB.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.register_reg:
// Check all requir field empty or not
//Apply the validation in each field including slack Id
if(name.getText().toString().length()==0) {
name.setError("Name cannot be blank");
}
if(emailId.getText().toString().equals("")) {
emailId.setError("Email cannot be blank");
}
if(String.valueOf(slackId.getText().toString().charAt(0)).equals("#")) {
slackId.setError("Slack id cannot be blank");
}
if (password.getText().toString().equals("")) {
password.setError("password cannot be blank");
}
if(conPasword.getText().toString().equals("")) {
conPasword.setError("confirm password cannot be blank");
// if any of the required field empty "Show Dialog to fill the required field
alertBuilder = new AlertDialog.Builder(RegisterActivity.this);
alertBuilder.setTitle("Something Wrong");
alertBuilder.setMessage("Please Fill all required field");
alertBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = alertBuilder.create();
alertDialog.show();
}else if(!(password.getText().toString().equals(conPasword.getText().toString()))){
//check pasword and confirm pasword mismatch
alertBuilder = new AlertDialog.Builder(RegisterActivity.this);
alertBuilder.setTitle("Something Wrong");
alertBuilder.setMessage("Pasword Mismatch");
alertBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
password.setText("");
conPasword.setText("");
}
});
AlertDialog alertDialog = alertBuilder.create();
alertDialog.show();
}else{
// Background task to insert user information into database
BackgroundLoginTask backgroundLoginTask = new BackgroundLoginTask(RegisterActivity.this);
backgroundLoginTask.execute("register",name.getText().toString(),
emailId.getText().toString(),
slackId.getText().toString(),
password.getText().toString(),
info.getText().toString());
}
break;
}
}
}
Try :
edittext.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if(!edittext.getText().toString().contains("#")) {
edittext.setError("# not detected");
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
If you want something that the id should start with # then can use this pattern : ^#.*
You can blank validation by using TextUtils.isEmpty(slackId.getText().toString())
This will check if text is null or empty
In your code you did validation like
if(String.valueOf(slackId.getText().toString().charAt(0)).equals("#")) {
slackId.setError("Slack id cannot be blank");
}
this will not validate weather is contains # or not.
do this:
if(!slackId.getText().toString().contains("#")){
//show your error message here
}
Hope it will help you!!
You can make a validation like
if(!slackId.getText().toString().contains("#")){}
You can use this as its better than using textChange listener for your case to check the text edit after losing focus , which will give you the needed validation without submitting .
EditText ed= (EditText) findViewById(R.id.edittxt);
ed.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus && !ed.getText().toString().contains("#")) {
ed.setError("# not detected")
}
}
});
I have an activity with RecyclerView and each item in the list looks like below. The star should be clickable and when the user clicks it, it is expected to be changed to dark star. If the use clicks on the list item, it enters a new activity, where further details are provided corresponding to the list item selected. :
This is the XML of list item.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cont_item_root"
android:layout_width="match_parent"
android:layout_height="85dp"
android:background="#drawable/background_state_drawable"
android:clickable="true"
>
<ImageView
android:id="#+id/im_item_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:src="#mipmap/ic_tonality_black_36dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/lbl_item_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/im_item_icon"
android:layout_marginLeft="72dp"
android:layout_marginRight="48dp"
android:ellipsize="end"
android:fontFamily="sans-serif"
android:singleLine="true"
android:text="Sois comme l'eau mon ami"
android:textColor="#android:color/black"
android:textSize="16sp" />
<TextView
android:id="#+id/lbl_item_sub_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/lbl_item_text"
android:layout_marginLeft="72dp"
android:layout_marginRight="48dp"
android:ellipsize="end"
android:fontFamily="sans-serif"
android:singleLine="true"
android:text="Mononc' J"
android:textSize="14sp" />
<ImageView
android:id="#+id/im_item_icon_secondary"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:padding="16dp"
android:src="#mipmap/ic_star_border_black_24dp"
android:background="#drawable/background_state_drawable"
/>
</RelativeLayout>
A nested class in Adapter handles the click events for me.
class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
private TextView title;
private TextView subTitle;
private ImageView thumbnail;
private ImageView secondaryIcon;
private View container;
public DerpHolder(View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.lbl_item_text);
subTitle = (TextView)itemView.findViewById(R.id.lbl_item_sub_title);
thumbnail = (ImageView)itemView.findViewById(R.id.im_item_icon);
secondaryIcon = (ImageView)itemView.findViewById(R.id.im_item_icon_secondary);
container = (View)itemView.findViewById(R.id.cont_item_root);
container.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Log.w("RecyclerView","Item with id : " + v.getId() + " touched");
if(v.getId() == R.id.cont_item_root)
{
Log.w("RecyclerView","list item clicked");
itemClickCallback.onItemClick(getAdapterPosition());
}
else
{
Log.w("RecyclerView","star clicked");
itemClickCallback.onSecondaryIconClick(getAdapterPosition()); //not able to come here
}
}
}
I am able to enter the first part of if, i.e. I am able to receive the click event of listItem click. However, when the user clicks star, it is also treated as if the whole list item is clicked as the star lies inside the container.
How can I receive the click on star seperately, so that the click on star is not treated as the click on list item?
EDIT
Adding the line android:descendantFocusability="blocksDescendants" in the RelativeLayout of list item fixed the issue. But can anyone please explain how it fixed it. By name, it is expected to block the descendants and eat the click events. However, the behaviour is opposite.
Since you just want to get the click of the star, you should set the OnClickListener just for the star:
public DerpHolder(View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.lbl_item_text);
subTitle = (TextView)itemView.findViewById(R.id.lbl_item_sub_title);
thumbnail = (ImageView)itemView.findViewById(R.id.im_item_icon);
secondaryIcon = (ImageView)itemView.findViewById(R.id.im_item_icon_secondary);
secondaryIcon.setOnClickListener(this);
}
reverse the if / else statement and add a click listener for the star image. It should work since you want to trigger the listener for the recyclerview item if the star is not clicked
class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
private TextView title;
private TextView subTitle;
private ImageView thumbnail;
private ImageView secondaryIcon;
private View container;
public DerpHolder(View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.lbl_item_text);
subTitle = (TextView)itemView.findViewById(R.id.lbl_item_sub_title);
thumbnail = (ImageView)itemView.findViewById(R.id.im_item_icon);
secondaryIcon = (ImageView)itemView.findViewById(R.id.im_item_icon_secondary);
container = (View)itemView.findViewById(R.id.cont_item_root);
container.setOnClickListener(this);
secondaryIcon.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Log.w("RecyclerView","Item with id : " + v.getId() + " touched");
if(v.getId() == R.id.im_item_icon_secondary)
{
Log.w("RecyclerView","star clicked");
itemClickCallback.onSecondaryIconClick(getAdapterPosition());
}
else
{
Log.w("RecyclerView","list item clicked");
itemClickCallback.onItemClick(getAdapterPosition());
}
}
}
Hope this helps
You forgot to add onClick listener to secondaryIcon.
Try this:
class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
private TextView title;
private TextView subTitle;
private ImageView thumbnail;
private ImageView secondaryIcon;
private View container;
public DerpHolder(View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.lbl_item_text);
subTitle = (TextView)itemView.findViewById(R.id.lbl_item_sub_title);
thumbnail = (ImageView)itemView.findViewById(R.id.im_item_icon);
secondaryIcon = (ImageView)itemView.findViewById(R.id.im_item_icon_secondary);
container = (View)itemView.findViewById(R.id.cont_item_root);
container.setOnClickListener(this);
secondaryIcon.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == secondaryIcon.getId())
{
Log.w("RecyclerView","star clicked");
itemClickCallback.onSecondaryIconClick(getAdapterPosition());
}
else
{
Log.w("RecyclerView","list item clicked");
itemClickCallback.onItemClick(getAdapterPosition());
}
}
}
Hope this will help~
You can also declare onclick item for specific views's of row like below in recycler adapter class.
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.linRootMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Do your stuff here.
}
});
holder.imgStart.setOnClickListner(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Do your stuff here.
}
});
}
I hope this will help you.
Making a to-do list. Having 2 issues, The not so important issue is that for some reason I can't see the TextView's that I set up as "labels". The more important thing is that when I click the create new task button, my alert pops up, I can put values in my EditText boxes, but when I hit create, it crashes and I get a NullPointer exception saying I'm trying to call getText() on a null object reference. I can't figure out if I'm inflating incorrectly or if I'm not linking the EditTexts to the alert properly. The annoying thing is that my edittext alert box works just fine editing existing list items(that I hardcoded for testing). Here's my layout and activity, I commented the line in which it breaks. Sorry about all the Log.d's I'm really trying to visualize how all this works.
The Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<EditText
android:layout_width="55dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/txtCreatePriority"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="25dp"
android:hint="1"
android:textAlignment="center" />
<EditText
android:layout_width="235dp"
android:layout_height="wrap_content"
android:id="#+id/txtCreateItemContent"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/txtCreatePriority"
android:layout_toEndOf="#+id/txtCreatePriority"
android:layout_marginLeft="15dp"
android:hint="Do Laundry"
android:textAlignment="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Priority"
android:id="#+id/lblPriority"
android:layout_above="#+id/txtCreatePriority"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="17dp"
android:textStyle="bold"
android:textSize="23dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Task to-do"
android:id="#+id/lblItemContent"
android:layout_above="#+id/txtCreateItemContent"
android:layout_toRightOf="#+id/lblPriority"
android:layout_toEndOf="#+id/lblPriority"
android:layout_marginLeft="65dp"
android:textStyle="bold"
android:textSize="23dp" />
</RelativeLayout>
The Activity
public class MainActivity extends AppCompatActivity {
private ListDataSource ds;
private ListView listViewToDo;
private Button btnAddNew;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Context context = this;
Log.d("MainActivity","Attempting to create data source");
try {
ds = new ListDataSource();
}
catch(Exception e)
{
e.printStackTrace();
Log.d("MainActivity","Failed to create data source");
}
btnAddNew = (Button)findViewById(R.id.btnAddNew);
Log.d("Main Activity","Attempting to link empty list view to on screen view");
listViewToDo = (ListView)findViewById(R.id.listOfLists);
Log.d("Main Activity", "Views linked, Attempting to set adapter to listView");
listViewToDo.setAdapter(new ListDataSourceAdapter(this, ds));
Log.d("Main Activity", "Successfully set Adapter");
btnAddNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("addItem", "Entered onclick, Attempting to create AlertDialog");
AlertDialog.Builder addItem = new AlertDialog.Builder(context);
Log.d("addItem", "AlertDialog Built, attempting to create inflater");
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
addItem.setView(inflater.inflate(R.layout.create_item_layout, null));
Log.d("addItem", "inflater built linking text boxes");
final TextView txtCreatePriority = (TextView)findViewById(R.id.txtCreatePriority);
final TextView txtCreateCellContent = (TextView)findViewById(R.id.txtCreateItemContent);
final TextView lblPriority = (TextView)findViewById(R.id.lblPriority);
final TextView lblItemContent = (TextView)findViewById(R.id.lblItemContent);
addItem.setTitle("Create new item");
addItem
.setCancelable(false)
.setPositiveButton("Create", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("editText onClick", "in onClick method, preparing to add entry");
// This is where the code breaks
ds.getList().add(Integer.valueOf(txtCreatePriority.getText().toString()), new CellContent(Integer.valueOf(txtCreatePriority.getText().toString()) + 1, txtCreateCellContent.getText().toString().trim()));
Log.d("editText onClick", "added new entry");
ListDataSourceAdapter adapter = new ListDataSourceAdapter(context, ds);
Log.d("editText onClick", "reestablished link to adapter");
listViewToDo.setAdapter(adapter);
Log.d("editText onClick", "adapter set");
adapter.notifyDataSetChanged();
Log.d("editText onClick", "DataSetChanged");
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = addItem.create();
alertDialog.show();
}
});
// add button listener
listViewToDo.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id)
{
AlertDialog.Builder editItem = new AlertDialog.Builder(context);
final EditText edittext = new EditText(context);
editItem.setTitle("Change item");
editItem
.setMessage("Set new todo item")
.setView(edittext)
.setCancelable(false)
.setPositiveButton("Submit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
Log.d("editText onClick","in onClick method, preparing to remove previous entry");
ds.getList().remove(position);
Log.d("editText onClick", "removed previous entry");
ds.getList().add(position, new CellContent(position + 1, edittext.getText().toString().trim()));
Log.d("editText onClick", "added new entry");
ListDataSourceAdapter adapter = new ListDataSourceAdapter(context,ds);
Log.d("editText onClick","reestablished link to adapter");
listViewToDo.setAdapter(adapter);
Log.d("editText onClick", "adapter set");
adapter.notifyDataSetChanged();
Log.d("editText onClick", "DataSetChanged");
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = editItem.create();
alertDialog.show();
}
});
}
}
The Error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
You're calling "(EditText)v.findViewById" on the view v.
The view v is the view passed back in the onClickListener, which is the button itself.
Since that button does not contain the EditTexts within it, those views are null. And crash when you try to access them.
I'm a little uncertain where the layout with the edit texts is in this code. Is it in the same layout as the listview, or in create_item_layout?
If its create_item_layout, that needs to be inflated before getting the EditTexts. Use the view you inflate to findViewById.
Hi All I have followed the following example http://www.google.com/codesearch#search/&q=NumberFormattingTextWatcher&exact_package=android&type=cs
I have CurrencyTextWatcher as a seperate class. I need this as I will be applying to several pages.
I can't figure out why, but if I use setContentView(text) it will work as only 1 big text box, then I can't see the rest of my xml .
If I use setContentView(R.layout.main); my xml works properly except for the TextWatcher wont fire for my txta EditText box
Java
public class CalcTestActivity extends Activity {
private EditText txta;
private TextView txtb;
private TextView txtc;
private EditText text;
private double a = 0;
private double b = 0;
private double c = 0;
private Button buttonCalc;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
text = new EditText(this);
text.addTextChangedListener(new CurrencyTextWatcher());
//setContentView(text);
}
private String FormatValue(double value)
{
NumberFormat nf = NumberFormat.getInstance();
return "$ "+ nf.format(value);
}
private void initControls() {
txta = (EditText)findViewById(R.id.txta);
txtb = (TextView)findViewById(R.id.txtb);
txtc = (TextView)findViewById(R.id.txtc);
buttonCalc = (Button)findViewById(R.id.buttonCalc);
buttonCalc.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {calculate(); }
private void calculate() {
a=Double.parseDouble(txta.getText().toString());
b=Math.round(a*.88);
txtb.setText(FormatValue(b));
c=Math.round((a*.87)-(b*.28));
txtc.setText(FormatValue(c));
}
});
}
}
CurrencyTextWatcher Class
public class CurrencyTextWatcher implements TextWatcher {
boolean mEditing;
public CurrencyTextWatcher() {
mEditing = false;
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if(!mEditing) {
mEditing = true;
String digits = s.toString().replaceAll("\\D", "");
NumberFormat nf = NumberFormat.getCurrencyInstance();
try{
String formatted = nf.format(Double.parseDouble(digits)/100);
s.replace(0, s.length(), formatted);
} catch (NumberFormatException nfe) {
s.clear();
}
mEditing = false;
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
}
XML
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number1"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/txta"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:numeric="integer"/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number2"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/txtb"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Answer is"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/txtc"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:hint="0" />
<Button
android:id="#+id/buttonCalc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate" />
</LinearLayout>
I took your code. I observed that the code you have shared here is getting all views from xml.
In this case you are calling
text.addTextChangedListener(new CurrencyTextWatcher());
in your onCreate method, wherein text is done using java. You wont get a call back for your onTextChanged, beforeTextChanged or afterTextChanged because all your views are taken from xml. So please after your
initControls();
in onCreate() add below line
txta.addTextChangedListener(new CurrencyTextWatcher());
and comment
text.addTextChangedListener(new CurrencyTextWatcher());
that line is not needed. I have verified its working fine.
if works vote and accept the answer
what the code you have implemented in afterTextChanged implement the same for onTextChanged. It will fire and gives the call back.
Secondly, If there is problem in views check your layout and their params. if it is not proper it wont appear properly in the UI