editText.getText().toString returns empty - java

I'm new to Android and with the help of this site I've put together this code :
java:
public class Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
String input1 = ((EditText) findViewById(R.id.editText)).getText().toString().trim();
TextView TextView = (TextView) findViewById(R.id.textView);
if (input1.length() == 0) {
TextView.setText("empty");
}
else {
TextView.setText(input1);
}
}
}
xml:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:hint="text" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="28dp"
android:layout_marginStart="28dp"
android:layout_marginTop="20dp"
android:id="#+id/textView" />
But the textView shows empty when I type , tried a lot of things but nothing worked .
What I'm trying to do is get the value of editText and store it in a variable so I can work with it . I used a textView to see if it works but returns empty . I want the value to be updated real time , just like Android default calculator app .
EDIT
For my purpose I had to put a textWatcher.
public class Activity extends AppCompatActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
EditText editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
textView.setText(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}

As pointed out by #Selvin, a Listener for text changes in the EditText would help.
TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.length() == 0) {
TextView.setText("empty");
}
else {
TextView.setText(charSequence);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
};
EditText editText = (EditText) findViewById(R.id.editText);
editText.addTextChangedListener(textWatcher);
But please remove the Listener (textView.removeTextChangedListener(textWatcher);)
when you're done, as there's a potential for a memory leak here.

You didnt cast the java file properly...
TextView TextView = (TextView) findViewById(R.id.textView);
try replacing with
TextView textView = (TextView) findViewById(R.id.textView);

Change your code to the following :
public class Activity extends AppCompatActivity {
EditText ed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
ed= (EditText) findViewById(R.id.editText);
TextView TextView = (TextView) findViewById(R.id.textView);
String input1 = ed.getText().toString().trim();
if (input1.length() == 0) {
TextView.setText("empty");
}
else {
TextView.setText(input1);
}
}
}
Hope it works well :)

Related

Recyclerview updates when I click EditText and removes typo input

So when I click my EditText field called Search, I get the keyboard, and for a brief second I see the vatical line you see when you are typing. But then the recyclerview is updated, and the typo input is removed, and the keyboard is still showing, but when I type nothing happens, until I click on the EditText field a second time. How can this be??
This is my Fragment where I have the Recyclerview & EditText
public class FragmentST extends Fragment {
private final static String TAG = FragmentST.class.getSimpleName();
private FloatingActionButton addP, searchP;
private FirebaseFirestore firestore;
String editName, editNumber;
EditText textN, textID, searchText;
//https://www.youtube.com/watch?v=b_tz8kbFUsU&ab_channel=TVACStudio
public RecyclerView mResultList;
public FirestoreRecyclerAdapter adapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_st, container, false);
firestore = FirebaseFirestore.getInstance();
addP = (FloatingActionButton) view.findViewById(R.id.addP);
searchP = (FloatingActionButton) view.findViewById(R.id.searchP);
mResultList = (RecyclerView) view.findViewById(R.id.patientResults);
searchText = (EditText) view.findViewById(R.id.search_field);
setPatientView();
addPatientOnClick();
search();
return view;
}
private class PViewHolder extends RecyclerView.ViewHolder {
private TextView List_name, List_cpr;
private ImageView icon;
public PViewHolder(#NonNull View itemView) {
super(itemView);
List_name = itemView.findViewById(R.id.Pname);
List_cpr = itemView.findViewById(R.id.Pcpr);
icon = itemView.findViewById(R.id.pb);
}
}
private void setPatientView() {
//Query -->https://www.youtube.com/watch?v=cBwaJYocb9I&ab_channel=TVACStudio
Query query = firestore.collection("patients");
Log.d(TAG, "setPatientView: " + query);
//RecyclerOptions
FirestoreRecyclerOptions<users> options = new FirestoreRecyclerOptions.Builder<users>()
.setQuery(query, users.class)
.build();
adapter = new FirestoreRecyclerAdapter<users, PViewHolder>(options) {
#NonNull
#Override
public PViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_patients_layout, parent, false);
return new PViewHolder(view1);
}
#Override
protected void onBindViewHolder(#NonNull PViewHolder holder, int position, #NonNull users model) {
holder.List_name.setText(model.getName());
holder.List_cpr.setText("CPR: " + model.getCpr());
System.out.println("last character: " + model.getCpr().substring(model.getCpr().length() - 1));
if ((Integer.parseInt(model.getCpr().substring(model.getCpr().length() - 1)) % 2) == 0) {
// number is even
int id = getResources().getIdentifier("com.example.wrd:drawable/female", null, null);
holder.icon.setImageResource(id);
} else {
// number is odd
int id = getResources().getIdentifier("com.example.wrd:drawable/male", null, null);
holder.icon.setImageResource(id);
}
}
};
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(getActivity()));
mResultList.setAdapter(adapter);
}
private void search() {
searchP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "HELLO "+searchText.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
}
private void addPatientOnClick() {
addP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Button Clicked", Toast.LENGTH_SHORT).show();
//https://stackoverflow.com/questions/23669296/create-a-alertdialog-in-android-with-custom-xml-view
// custom dialog
final Dialog dialog = new Dialog(getActivity(), android.R.style.Theme_Material_Light_NoActionBar_Fullscreen);
dialog.setContentView(R.layout.fragment_add_patient);
dialog.setTitle("Add patient");
// set the custom dialog components - text, button
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Name");
TextView text2 = (TextView) dialog.findViewById(R.id.text2);
text2.setText("ID");
Button dialogButtonOk = (Button) dialog.findViewById(R.id.dialogButtonOK);
Button dialogButtonCancel = (Button) dialog.findViewById(R.id.dialogButtonCancel);
// if button is clicked, close the custom dialog
dialogButtonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textN = (EditText) dialog.findViewById(R.id.editName);
textID = (EditText) dialog.findViewById(R.id.editNumber);
editName = textN.getText().toString();
editNumber = textID.getText().toString();
editNumber.length();
if (editNumber != null && editNumber.length() > 9) {
Log.d(TAG, "dialog: \ncpr: " + editNumber);
} else {
return;
}
if (editName.matches("")) {
return;
} else {
Log.d(TAG, "dialog: \n Name: " + editName);
}
DocumentReference documentReference = firestore.collection("patients").document(editNumber);
Map<String, Object> patient = new HashMap<>();
patient.put("name", editName);
patient.put("cpr", editNumber);
documentReference.set(patient).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
});
dialogButtonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
}
In the XML the EditText is set to the following
<EditText
android:id="#+id/search_field"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/search_layout"
android:ems="10"
android:hint="Search"
android:inputType="textPersonName"
android:paddingLeft="20dp"
android:paddingTop="10dp"
android:paddingRight="20dp"
android:paddingBottom="10dp"
android:textSize="16sp"
android:layout_weight="1"
app:layout_constraintBottom_toBottomOf="#+id/searchP"
app:layout_constraintEnd_toStartOf="#+id/searchP"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/searchP" />

How to implement search button to android Firebase database?

I tried so many time to implement to search my android Firebase database.
Query: query = dateRef.orderByChild("phone").equalTo(searchPhoneNumber);
I don't know how to set searchPhoneNumber in EditText value. But I know EditText and one button using to search phone numbers. But I need Java code. Eg: if I enter phone numbers in EditText and I press button, after I get a output in same page.
Here I attached my Firebase screenshot and my code.
Firebase database screenshot
java
public class ViewProduction extends AppCompatActivity {
private RecyclerView mRecyclerView;
private Adapater mAdapter;
private ProgressBar mprogress;
private DatabaseReference mDatabaseRef;
private List<Datastore> mUploads;
EditText edit;
Button btnsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_production);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
edit =(EditText)findViewById(R.id.edit);
btnsearch = (Button)findViewById(R.id.btnsearch);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Production Details");
mRecyclerView = findViewById(R.id.recyclerj);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mprogress = findViewById(R.id.progress);
mUploads = new ArrayList<>();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("Rajadriving");
btnsearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// called search() method on button click.
search();
}
});
public void search(){
edit.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference dateRef = rootRef.child("Rajadriving").child("9-6-2018");
Query query = dateRef.orderByChild("phone").equalTo(s.toString());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Datastore upload = postSnapshot.getValue(Datastore.class);
mUploads.add(upload);
}
mAdapter = new Adapater(ViewProduction.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
mprogress.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ViewProduction.this, databaseError.getMessage(),Toast.LENGTH_SHORT).show();
mprogress.setVisibility(View.INVISIBLE);
}
});
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home){
this.finish();
}
return super.onOptionsItemSelected(item);
}
}
xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.udayaj.rajadriving.ViewProduction">
<EditText
android:id="#+id/edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/progress"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/progress"
android:hint="enter phone" />
<Button
android:id="#+id/btnsearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/recyclerj"
android:layout_marginLeft="21dp"
android:layout_marginStart="21dp"
android:layout_toEndOf="#+id/edit"
android:layout_toRightOf="#+id/edit"
android:text="Search" />
<ProgressBar
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/table01"
android:scrollbars="vertical"
android:id="#+id/recyclerj">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
I hope this will work for you.
Use Textwatcher() to implement search functionality.how to implement given below.
btnsearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// called search() method on button click.
search();
}
});
public void search(){
edit.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference dateRef = rootRef.child("Rajadriving").child("9-6-2018");
Query query = dateRef.orderByChild("phone").equalTo(s.toString());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Datastore upload = postSnapshot.getValue(Datastore.class);
mUploads.add(upload);
}
mAdapter = new Adapater(ViewProduction.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
mprogress.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ViewProduction.this, databaseError.getMessage(),Toast.LENGTH_SHORT).show();
mprogress.setVisibility(View.INVISIBLE);
}
});
}
}
}
To solve this, please change the following line of code:
Query query = dateRef.orderByChild("phone").equalTo("searchPhoneNumber");
to
Query query = dateRef.orderByChild("phone").equalTo(searchPhoneNumber);
See, no quotation marks? You need to search the database after the value that your variable searchPhoneNumber holds and not after the searchPhoneNumber String which is obvious is not a phone number.

SetText from a Class to the main XML file

I'm trying to use the .setText within a java class to try to change the value of a TextView on the activity_main XML file, so far i'm getting the NullpointerExeption error and I've read that its due an error when declaring my variable. How can i achieve this? Do i need to declare it first at the mainActivity.java?
On my activity_main.xml i have a button -> it opens a custom listView -> if you press the 2 item on the list view -> it opens a custom alert dialog -> the custom alert dialog it contains 2 buttons -> if you press the second button -> it has to set the text of a TextView that is on activity_main.xml
Any help is appreciated!
MainActivity.java
final TextView KMLabel = (TextView)findViewById(R.id.KMlabel);
activity.main.xml
<TextView
android:id="#+id/KMlabel"
android:layout_alignBottom="#+id/TVKm"
android:layout_toRightOf="#+id/TVKm"
android:textSize="22sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#e6c009"
android:text="KM/H"
android:textStyle="italic"/>
custom.java
public class custom extends BaseAdapter{
Context context;
String Item[];
String SubItem[];
int flags[];
LayoutInflater inflter;
public custom(Context applicationContext, String[] Item, String[] SubItem , int[] flags) {
this.context = context;
this.Item = Item;
this.SubItem = SubItem;
this.flags = flags;
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return Item.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_items, null);
//TextView Prueba = (TextView)view.findViewById(R.id.KMlabel);
TextView item = (TextView) view.findViewById(R.id.item);
TextView subitem = (TextView) view.findViewById(R.id.subitem);
ImageView image = (ImageView) view.findViewById(R.id.image);
item.setText(Item[i]);
subitem.setText(SubItem[i]);
image.setImageResource(flags[i]);
return view;
}
viewdialog.java
public class ViewDialog {
public void showDialog(Activity activity, String msg){
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.custom_dialog);
//I'm declaring it like this
final TextView KMLabel = (TextView)activity.findViewById(R.id.KMlabel);
Button dialogButton = (Button) dialog.findViewById(R.id.btn_dialog);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button KmPerHr = (Button)dialog.findViewById(R.id.KmPerH);
KmPerHr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//and calling it this way:
KMLabel.setText("MLL/H");
}
});
dialog.show();
}
}
LOGCAT:
FATAL EXCEPTION: main
Process: com.example.dell.getspeed, PID: 3925
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.dell.getspeed.ViewDialog$2.onClick(ViewDialog.java:38)
at android.view.View.performClick(View.java:5721)
at android.widget.TextView.performClick(TextView.java:10936)
at android.view.View$PerformClick.run(View.java:22620)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7406)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
You have to move your code
Button KmPerHr = (Button)dialog.findViewById(R.id.KmPerH);
KmPerHr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//and calling it this way:
KMLabel.setText("MLL/H");
}
});
final TextView KMLabel = (TextView)dialog.findViewById(R.id.KMlabel);
Button dialogButton = (Button) dialog.findViewById(R.id.btn_dialog);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
below the dialog.show() code because code findViewById only work after you pop up dialog.
Create a Global class which extends to application class, then create a texview in Global
Textview t = null;
Then create two static methods to set and get this textview
Public static void setT(TextView p){
t = p;
}
And get it from
Public static TextView getT(){
return t;
}
Set TextView in your activity ,then access this textview from wherever you want until your activity is alive.
Try the code below:
MainActivity class:-------
public class MainActivity extends AppCompatActivity {
private TextView KMlabel;
private Button b;
private ViewDialog vd;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo2);
vd = new ViewDialog();
KMlabel = (TextView) findViewById(R.id.KMlabel);
b = (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
vd.showDialog(MainActivity.this , KMlabel , "Your Message" , "Your Text");
}
});
}
}
ViewDialog class:------
public class ViewDialog {
public void showDialog(Context context, final TextView v , String msg , final String text) {
createYesNoInfoDialog(context, msg, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
}, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
v.setText(text);
}
}).show();
}
private AlertDialog createYesNoInfoDialog(Context finalContext, String message,
DialogInterface.OnClickListener onNoListener, DialogInterface.OnClickListener onYesListener) {
AlertDialog a = new AlertDialog.Builder(finalContext).setTitle(
message)
.setNegativeButton("No", onNoListener)
.setPositiveButton("Yes", onYesListener).create();
return a;
}
}
demo2.xml:-----
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="xcxc"
android:id="#+id/KMlabel"/>
<Button
android:layout_width="match_parent"
android:text="Create Dialog"
android:layout_height="wrap_content"
android:id="#+id/b"/>
</LinearLayout>
R.id.KMlabel is on activity_main.xml so you have to initialize the TextView from MainActivity reference.
final TextView KMLabel = (TextView)activity.findViewById(R.id.KMlabel);
Edit:
You can use callback pattern for this:
ViewDialog:
public class ViewDialog {
// interface for callback
public interface OnSelectListener {
public void onOkSelect();
}
OnSelectListener mOnSelectListener;
public void showDialog(Activity activity, String msg, OnSelectListener mListener){
mOnSelectListener = mListener;
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.custom_dialog);
//I'm declaring it like this
final TextView KMLabel = (TextView)activity.findViewById(R.id.KMlabel);
Button dialogButton = (Button) dialog.findViewById(R.id.btn_dialog);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button KmPerHr = (Button)dialog.findViewById(R.id.KmPerH);
KmPerHr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//pass to the implementation if not null
if( mOnSelectListener != null){
mOnSelectListener.onOkSelect();
}
}
});
dialog.show();
}
}
In MainActivity:
// initialize interface
ViewDialog.OnSelectListener mOnSelectListener = new ViewDialog.OnSelectListener(){
public void onOkSelect(){
KMLabel.setText("MLL/H");
}
};
ViewDialog viewDialog = new ViewDialog();
viewDialog.showDialog(this, "Message", mOnSelectListener);
This happens since you are trying to call the TextView within the custom alert dialog. TextView only belongs to the MainActivity. You can call or change that only within the MainActivity class. So please try this below.
MainActivity.class
public class MainActivity extends AppCompatActivity {
private TextView KMlabel;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
KMlabel = (TextView) findViewById(R.id.KMlabel);
}
public void setTextKM(String string){
KMlabel.setText(string);
}
}
ViewDialog class
public class ViewDialog {
public void showDialog(Activity activity, String msg){
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.custom_dialog);
Button dialogButton = (Button) dialog.findViewById(R.id.btn_dialog);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button KmPerHr = (Button)dialog.findViewById(R.id.KmPerH);
KmPerHr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainActivity mainActivity = new MainActivity();
mainActivity.setTextKM("MLL/H");
}
});
dialog.show();
}
}

Crash when i try to update TextView

I'm trying to do an calculator app (school project), so i need a TextView for displaying the numbers. Because it's my first java project i wanted for the beginning to make a counter which displays how many times the button was clicked(just to learn how to work with TextViews). My problem is that after the first update of the TextView(when it is displaying "1") when i press the button for the second time it gives me a crash.
My code :
MainActivity.java
public class MainActivity extends AppCompatActivity {
public Integer number = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.no1);
ImageButton button = (ImageButton) findViewById(R.id.zeroB);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
number++;
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.no1);
tv.setText(number.toString());
}
});
}
...
content_main.xml
...
<TextView
android:layout_width="172dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/no1"
android:layout_gravity="left|top"
android:editable="true" />
...
Modify your code to this:
public class MainActivity extends AppCompatActivity {
public Integer number = 0;
//i would use this instead of the above
private int number = 0;
private TextView tv;
private ImageButton button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.no1);
button = (ImageButton) findViewById(R.id.zeroB);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
number++;
tv.setText(String.valueOf(number));
}
});
}
...

get EditText value from onclick function

How do I get the value of my EditText that the user typed in from the function that was called when the onClick was pressed. I tried this below but its not working. Thanks for the help.
<EditText android:id="#+id/myEditT" />
<Button android:text="MY BUTTON" android:onClick="GetThis" />
public void GetThis(View view) {
EditText x = (EditText)parentView.findViewById( R.id.myEditT);
// alert the x variable
}
EditText x = (EditText) findViewById(R.id.myEditT);
String your_text = x.getText().toString();
In XML,
<EditText android:id="#+id/myEditT"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
<Button android:id="#+id/myButton"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
In Java,
public void onCreate(Bundle saved){
super.onCreate(saved);
setContentView(R.layout.your_xml);
Button btn = (Button) findViewById(R.id.myButton);
EditText edtText = (EditText) findViewById(R.id.myEdit);
btn.setOnClickListener(new onClickListener(
public void onClick(View v){
String value = edtText.getText().toString();
}
));
}
public void GetThis(View view) {
EditText x = (EditText)view.findViewById(R.id.myEditT);
String edittextvalue = x.getText().toString();
}
EditText x = (EditText)findViewById(R.id.myEditT);
public void GetThis(View view) {
String getEditTextValue = x.getText().toString();
Toast.makeText(getApplicationContext(), getEditTextValue, Toast.LENGTH_LONG).show();
}
EditText x;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xml);
x = (EditText)parentView.findViewById( R.id.myEditT);
public void GetThis(View view) {
String s=x.getText().toString();
}

Categories