I have a custom dialog and when I try to get the value of an EditText it returns null.
This line returns null
EditText et = (EditText)findViewById(R.id.username_edit);
Here is the code in its entirety.
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_TEXT_ENTRY:
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
return new AlertDialog.Builder(TicTacToe.this)
//.setIconAttribute(android.R.attr.alertDialogIcon)
.setTitle(getTitleText())
.setView(textEntryView)
.setPositiveButton("JOIN GAME", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try
{
EditText et = (EditText)findViewById(R.id.username_edit);
playerName = et.getText().toString();
}
catch (Exception e)
{
}
}
})
.create();
}
return null;
}
In my case:
First I must call the
dialog.show(),
and only after it I was able to use
dialog.findviewById(R.id.myID).
If I missed to call the show(), than I got a null back with findViewByID.
Try this:
EditText et = (EditText)textEntryView.findViewById(R.id.username_edit);
You have to tell in which view to find the id. Otherwise it will try to find the id in the view from the xml layout inflated by setContentView (usually declared in onCreate)
I faced a similar problem. In my case, I had a dialog with custom layout and in this layout had a radioButton. In order to solve that, I used the follow code:
View dialogLayout = factory.inflate(R.layout.dialog_layout, null);
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setView(dialogLayout);
RadioButton radiobt = (RadioButton) dialogLayout.findViewById(R.id.radioBt);
I was having the same problem, which presented itself in the following code snippet:
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.addbank_dialog);
dialog.show();
Button btnSaveBank = (Button)dialog.findViewById(R.id.btnSaveBank);
final EditText etBankName = (EditText)dialog.findViewById(R.id.etBankName);
btnSaveBank.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try{
String bank = etBankName.getText().toString();
SharedCommonData.dbOps.saveBankInDB(bank);
}
catch(Exception e){
e.printStackTrace();
}
Toast.makeText(SharedCommonData.context, "Bank Saved", Toast.LENGTH_SHORT);
refreshBanks();
dialog.dismiss();
}
});
etBankName was returning null value, but then I used dialog.findviewbyid(R.id.etBankName) and it worked.
In my case I had this error because I was redeclaring an initialized variable
In main Activity I had:
EditText cityName;
And in onCreate:
EditText cityName = (EditText)findViewById(R.id.cityName);
Just removed EditText and smooth sailing!
None of the existing answers worked for me, so I started trying different lifecycle hooks, and the one that worked for me was onViewCreated, which seems like a good choice semantically as well.
In my case what I did was that I was passing an ID of a view which was in different fragment and in that case the compiler gave me same error.
So try checking that the ID use pass is in the same xml which is connect to the java file.
I hope it helps this is my first ever solution given in this community.
Related
I'm new to OOP, but I've had experience with C previously. I'm learning Java and working on building an app slowly. I find I learn more when I apply what I've read and learned from other sources to projects.
The problem I've been facing for a while now is in regard to returning values users have inputted into EditText fields and using those values to run some calculations. Here is my code:
public class Linmotion extends Activity {
// Creating the variables
EditText time, acc, dis, ivel, fvel;
Button solve;
int count = 0;
double time1,acc1,dis1,ivel1,fvel1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_linmotion1);
time = (EditText) findViewById(R.id.EditText01);
acc = (EditText) findViewById(R.id.EditText02);
dis = (EditText) findViewById(R.id.EditText03);
ivel = (EditText) findViewById(R.id.EditText04);
fvel = (EditText) findViewById(R.id.EditText05);
solve = (Button) findViewById(R.id.buttonSolve);
//Trying to return inputted values
/*
if (!(time.getText() == null)) {
time1=Double.parseDouble(time.getText().toString());
}
if(!(acc.getText()==null)){
acc1=Double.parseDouble(acc.getText().toString());
}
if(!(ivel.getText()==null)){
ivel1=Double.parseDouble(ivel.getText().toString());
}
if(!(fvel.getText()==null)){
fvel1=Double.parseDouble(fvel.getText().toString());
}s
if(!(dis.getText()==null)){
dis1=Double.parseDouble(dis.getText().toString());
}
/*
* Double.parseDouble(time.getText().toString());
* Double.parseDouble(acc.getText().toString());
* Double.parseDouble(ivel.getText().toString());
* Double.parseDouble(fvel.getText().toString());
* Double.parseDouble(dis.getText().toString());
*/
// add button listener
solve.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (time1 < 0) {
count++;
if (acc1 < 0) {
count++;
}
if (ivel1 < 0) {
count++;
}
if (fvel1 < 0) {
count++;
}
if (dis1 < 0) {
count++;
}
if (count > 2) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
Linmotion.this);
final AlertDialog alert = alertDialog.create();
alert.show();
alertDialog.setTitle("Error");
alertDialog
.setMessage("Please input values into at least 3 fields");
alertDialog.setPositiveButton("OK",new DialogInterface.OnClickListener() {
// function of dialog button
public void onClick(DialogInterface dialog,
int id) {
alert.cancel();
}
});
}
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.linmotion, menu);
getActionBar().setDisplayShowTitleEnabled(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The if statements and the other Double.parseDouble lines have been commented out because every time I try to debug the code the app crashes the instant Linmotion is created. I suspect its from the fact that onCreate runs the Double.parseDouble code and the values in the field are null. I tried to fix this with the if statements and it still crashes. I'm not sure where to go from here.
Again, if I wasn't clear I just want the values inputted into the EditText to return a double and then use that double in the Java code to run some equations and an alert dialog if not enough fields have been filled in.
EDIT/UPDATE:
I finally figured out what was wrong with my code. I took in advice from everyone and revised accordingly, so here it is:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_linmotion1);
time = (EditText) findViewById(R.id.eTexttime);
acc = (EditText) findViewById(R.id.eTextacc);
dis = (EditText) findViewById(R.id.eTextdis);
ivel = (EditText) findViewById(R.id.eTextivel);
fvel = (EditText) findViewById(R.id.eTextfvel);
solve = (Button) findViewById(R.id.buttonSolve);
solve.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
count=0;
if (time.getText().toString().equals("")){
count++;
}
if(dis.getText().toString().equals("")){
count++;
}
if(fvel.getText().toString().equals("")){
count++;
}
if(ivel.getText().toString().equals("")){
count++;
}
if(acc.getText().toString().equals("")){
count++;
}
if (count>2){
// TODO Auto-generated method stub
final AlertDialog alert= new AlertDialog.Builder(Linmotion.this).create();
alert.setTitle("Oops");
alert.setMessage("Please input values in at least 3 fields.");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alert.cancel();
}
});
alert.show();
count=0;
}
if(!(time.getText().toString().equals(""))){
time1=Double.parseDouble(time.getText().toString());
}
if(!(acc.getText().toString().equals(""))){
acc1=Double.parseDouble(acc.getText().toString());
}
if(!(dis.getText().toString().equals(""))){
dis1=Double.parseDouble(dis.getText().toString());
}
if(!(ivel.getText().toString().equals(""))){
ivel1=Double.parseDouble(ivel.getText().toString());
}
if(!(fvel.getText().toString().equals(""))){
fvel1=Double.parseDouble(fvel.getText().toString());
}
} });
}
In regard to the issues I had with the alertdialog I realized that my count integer would continue to increase every time the solve button was clicked. To fix this I simply equaled the integer to 0 at the beginning of the onclicklistener and at the end of the if statement regarding the dialog. Thanks everyone.
It looks to me like you're doing it right. I think the problem might be that it's in your OnCreate method.
Try making the Button Solve's OnClick method run your commented code before doing the logic!
You can get the value from an EditText using getText()..
See this link for more details
According to the docs getText() returns an Editable.
so,
time = (EditText) findViewById(R.id.EditText01);
String value = time.getText().toString();
Now, as i've said earlier, since getText() returns an Editable you need to convert it into String before you use it..
So, change
if (!(time.getText() == null)) {
to
if (!(time.getText().toString() == null)) {
Also, if you want to check if the EditText is empty or not, try like this..
if (!(time.getText().toString() .equals(""))) {
Try this answer..
Your code isn't working because you are trying to read these text fields on creation. This is not what you want to do.
You are trying to access the EditTexts before the page finishes loading. Instead, you need to do this in an event handler, like you have for the buttons. Read the values in an event handler, not in onCreate.
The simplest option would be to add an "update" button and do all those operations in the onClick handler for that button.
Most likely your EditText fields initially contain text, that cannot be parsed with Double.parseDouble (Something like the empty string). A NumberFormatException is thrown is this case. If you want to get the values at the time solve button is clicked, you have to get the text inside OnClickListener.onClick (otherwise you use the initial strings, i.e. the strings in the android:text attributes in the activity_linmotion1 layout). To handle invalid input, you can simply catch the NumberFormatException:
solve.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
double time1 = Double.parseDouble(time.getText().toString());
double acc1 = Double.parseDouble(acc.getText().toString());
double ivel1 = Double.parseDouble(ivel.getText().toString());
double fvel1 = Double.parseDouble(fvel.getText().toString());
double dis1 = Double.parseDouble(dis.getText().toString());
// ... rest of your original listener code
} catch (NumberFormatException ex) {
// show error in dialog or something
}
}
});
Oncreate is the first method called when an activity is created, so by the time the onCreate is called, the editText is having an empty string which you are giving as an input to parseDouble which will give NumberFormatException.
You can avoid this crash by putting a button and handling the button onClick event. Inside this button click you collect the values from editfield. You can handle on click by defining listeners in the following way
<Button android:id="#+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:onClick="yourHandlerName" />
Now define your onClick with getText to get text from editfield in the following way
public void yourHandlerName(View v) {
switch(v.getid()) {
case R.id.mybutton: Double.parseDouble(editField.getText().to string());
}
You have to register a Listener. Because onCreate() is called when the Actvity first start. This means that you can't get the text from your EditTexts because the Actvity is creating. But you can use your OnClickListener or other Listeners. You can easily write your commented lines to the OnClickListener. At the time you are clicking the button the method getText().toString() return the values. If you want to do it without clicking on a button use addTextOnChangedListener() on yout EditText.
I've to do a pair of fixes to an Android app although I don't really know about Android, but I'm getting problems in something that I don't think should be that difficult, I just want that when an OK button is pressed and some conditions haven't been fulfilled it displays a message and keeps on the same screen until data is correct or the user cancels, but I've tried it for some time and whatever I try it always displays the message and after that a white screen appears, even trying to search for examples on the internet.
This is my code:
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
LinearLayout layout = new LinearLayout(this);
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(parms);
layout.setGravity(Gravity.CLIP_VERTICAL);
layout.setPadding(2, 2, 2, 2);
TextView tv = new TextView(this);
tv.setText("Es necesario rellenar los datos solicitados a continuación para poder realizar su primer canje");
tv.setPadding(40, 40, 40, 40);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(20);
EditText et = new EditText(this);
String etStr = et.getText().toString();
TextView tv1 = new TextView(this);
tv1.setText("Nombre completo");
EditText et2 = new EditText(this);
String etStr2 = et2.getText().toString();
TextView tv2 = new TextView(this);
tv2.setText("Teléfono");
final EditText et3 = new EditText(this);
String etStr3 = et3.getText().toString();
TextView tv3 = new TextView(this);
tv3.setText("Correo electrónico");
LinearLayout.LayoutParams tv1Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
tv1Params.bottomMargin = 5;
layout.addView(tv1,tv1Params);
layout.addView(et, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layout.addView(tv2,tv1Params);
layout.addView(et2, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layout.addView(tv3,tv1Params);
layout.addView(et3, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
alertDialogBuilder.setView(layout);
alertDialogBuilder.setTitle("hola");
// alertDialogBuilder.setMessage("Input Student ID");
alertDialogBuilder.setCustomTitle(tv);
// alertDialogBuilder.setMessage(message);
alertDialogBuilder.setCancelable(true);
// Setting Negative "Cancel" Button
alertDialogBuilder.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
alertDialogBuilder.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
[more code here]
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
matcher = pattern.matcher(et3.getText().toString());
if (matcher.matches())
{
[more code here]
}
else
{
Toast.makeText( contexto, "Por favor, introduzca un e-mail válido", Toast.LENGTH_LONG).show();
}
Hope you can help me with this thing, as I would find pretty annoying to have to learn android from the beginning to make something that I've been able to do in another programming languages in 5 minutes or less without knowing them at all.
Create two instance variables or class varibles like this
private Toast toast;
private boolean stop = false;
Write a method called this
private void showInfiniteToast() {
stop = false;
Thread t = new Thread() {
public void run() {
try {
while (true) {
if (!stop) {
toast.show();
} else {
toast.cancel();
return;
}
sleep(1850);
}
} catch (Exception e) {
Log.e("Infinite Toast", "Error "+ e.getLocalizedMessage());
}
}
};
t.start();
}
Now in the oncreate create the toast and call this method
toast = Toast.makeText(getApplicationContext(), "Test", Toast.LENGTH_LONG);
showInfiniteToast();
Now if you want to change the toast message use this
toast.setText("message");
To stop the toast call any of these
//Call anyone of them
stop = true;
toast.cancel();
To implement your own custom view use this
View mView;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = inflater.inflate(R.layout.mylayout, null);
toast.setView(mView);
Here is the complete file
public class MainActivity extends Activity implements OnClickListener {
Button btnChange, btnStop, btnShow;
private Toast toast;
private boolean stop = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShow = (Button) findViewById(R.id.btnShow);
btnShow.setOnClickListener(this);
btnChange = (Button) findViewById(R.id.btnChange);
btnChange.setOnClickListener(this);
btnStop = (Button) findViewById(R.id.btnStop);
btnStop.setOnClickListener(this);
toast = Toast.makeText(getApplicationContext(), "Test",
Toast.LENGTH_LONG);
showInfiniteToast();
}
private void showInfiniteToast() {
stop = false;
Thread t = new Thread() {
public void run() {
try {
while (true) {
if (!stop) {
toast.show();
} else {
toast.cancel();
return;
}
sleep(1850);
}
} catch (Exception e) {
Log.e("Infinite Toast", "Error "+ e.getLocalizedMessage());
}
}
};
t.start();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnShow:
showInfiniteToast();
break;
case R.id.btnChange:
toast.setText("Added");
break;
case R.id.btnStop:
stop = true;
toast.cancel();
break;
default:
break;
}
}
}
First of all create your layouts using xml and inflate the view like this:
LayoutInflater li = (LayoutInflater) <ACTIVITY_NAME>.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = li.inflate(R.layout.<LAYOUT_NAME>, parent, false);
or
View view = li.inflate(R.layout.<LAYOUT_NAME>, null);
If there is no parent view to attach the inflated view to. Then you can edit objects in your view by doing:
EditText edit = (EditText) findViewById(R.id.edit1);
edit.setText("example");
Doing so just makes your code much more cleaner.
The methods: setPositiveButton, setNeutralButton and setNegativeButton are coded so that when they are pressed, the dialog will close after it has finished executing the code in the listener.
If your Android app is running on the main thread for over 5 seconds then the app will throw an error saying that the app is no longer responding. If you wished to do a long action then you should use an AsyncTask or a Service.
I believe you are wanting to have a progress bar of some kind. I will link you to a
tutorial that will show you how to acheive that side of things. Check here
Hopefully this points you in the right direction.
create a dialogBuilder, and override the negative and positive buttons, and on the click listeners do whatever you want. This will prevent the dialog from closing.
Like this:
Create the builder, intialize it, set it for eg:
builder.setView(view);
builder.setCancelable(false);
override the ondismiss listener, and onshow listener like:
builder.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if(!errorFlag) {
dialog.dismiss();
}
}
});
builder.setOnShowListener(new OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button b = builder.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// write the logic here, and maintain a flag.
// if the flag is true then only dismiss the dialog else show another one
}
Override the negative button also.
show the builder using builder.show()
In my Android application, when the users click on Sales button, it will show another view to perform the sales.
My application is working without having any problems before I have implemented an alert dialog to display a warning message to users if GST License expiry date of selected customer is less than 7 days and going to expire soon. Now I am getting the following error message if I don't declare final to these two variables, customer and v.
Cannot refer to a non-final variable customer inside an inner class defined in a different method
Cannot refer to a non-final variable v inside an inner class defined in a different method
I understand that
The reference declared as final cannot be modified once it is
initialized.
So, what will happen if I assign these two variables as final? It always contain the same value? Can someone please explain to me why the compiler giving me these errors and why I should declare final to these two variables?
Here is my source code:
private OnClickListener salesBtnClick = new OnClickListener() {
#Override
public void onClick(View v) {
Customer customer = salesCustAdpt.getSelectedCustomer();
if (customer != null) {
Date expiryDate = customer.getGSTLicenseExpiryDate();
if (checkCustomerGSTLicenseExpiryDate(expiryDate)) {
AlertDialog.Builder builder = new AlertDialog.Builder(SalesCustomerActivity.this);
builder.setCancelable(false)
.setPositiveButton(
"OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
//Perform sales here!
Intent intent = null;
intent = new Intent(v.getContext(), SalesActivity.class);//Error msg here!
Bundle bundle = new Bundle();
bundle.putSerializable("selCustomer", customer);//Error msg here!
intent.putExtra("bundle", bundle);
startActivity(intent);
finish();
} catch (Exception ex) {
AddPlusUtil.displayErrorMsg(
SalesCustomerActivity.this,
ex);
}
}
});
AlertDialog alert = builder.create();
alert.setTitle("Warning Message");
String errMsg = "GST License Expiry Date of selected customer is \n" + expiryDate + " and going to expire soon.";
alert.setMessage(errMsg);
alert.setIcon(android.R.drawable.stat_notify_error);
alert.show();
} else {
//Perform Sales
}
}
}
}
When defining Customer, use final:
final Customer customer = salesCustAdpt.getSelectedCustomer();
Also, in your onClick method, set the View as final:
public void onClick(final View v) {
Hope this helps :)
Define that customer and v globally in your class. It will resolve the issue.
Create one global view object than assign it with your v
globalView = v;
and use that globalView for calling intent.
and by the way you can use yourClass.this as context instead of your view context.
I have the following code:
AlertDialog.Builder b = new AlertDialog.Builder(getActivity());
View view = LayoutInflater.from(getActivity()).inflate(R.layout.displayfilecontents, null);
EditText text = (EditText) view.findViewById(R.id.etFileContents);
if (text != null) {
text.setFocusable(false);
text.setLongClickable(false);
text.setTextIsSelectable(false);
}
text.setText(builder);
b.setView(view);
b.setTitle("Trip Name: " + FilesInFolder.get(position).toString().substring(0, FilesInFolder.get(position).toString().lastIndexOf(".")));
Button btnCloseIt = (Button) view.findViewById(R.id.btnClose);
btnCloseIt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
b.dismiss();
}
});
AlertDialog dl = b.create();
dl.show();
I am trying to dismiss the dialog once the btnCloseIt is pressed. I am receiving an error on this line:
b.dismiss(); //giving an error
Error: The method dismiss() is undefined for the type AlertDialog.Builder
Update: [RESOLVED]
// custom dialog
final Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.displayfilecontents);
dialog.setTitle("Trip Name: " + FilesInFolder.get(position).toString().substring(0, FilesInFolder.get(position).toString().lastIndexOf(".")));
EditText text = (EditText) dialog.findViewById(R.id.etFileContents);
if (text != null) {
text.setFocusable(false);
text.setLongClickable(false);
text.setTextIsSelectable(false);
}
text.setText(builder);
Button btnCloseIt = (Button) dialog.findViewById(R.id.btnClose);
// if button is clicked, close the custom dialog
btnCloseIt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
As others have already pointed out, b is a reference to AlertDialog.Builder and not to the Dialog itself. AlertDialog.Builder class doesn't have any method named dismiss(). Save a reference to the Dialog which is returned to you when you call create() or show() method from AlertDialog.Builder class.
One more thing, since you are calling create() and show() methods at the same time, do you really want to call both the methods? I believe calling only show() method would suffice for you here. From Developer Reference public AlertDialog show () : Creates a AlertDialog with the arguments supplied to this builder and show()'s the dialog.
You need to store the result of calling b.create(); that's what you need to call dismiss() on.
I FIGURED OUT WHAT I WAS DOING. I HAD THE VARIABLE NAME IN QUOTES WITH THE REST OF THE URL STRING.
How do you save the value of a Radio button into a variable and use that variable later.
I can see the variable Day_Item in my LogCat and the value is in there but when try using Day_Item later it does not show the valuable.
Below is a section of my code that shows the buttons.
String Day_Item = null;
public class SearchDB extends Activity {
private static final String TAG = "MyApp";
String start_log = "STARTED";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);
final RadioButton radio_monday = (RadioButton) findViewById(R.id.monday);
radio_monday.setOnClickListener(radio_listener);
cityspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long arg3)
{
int id = parent.getId();
if (spinner2_count2 < spinner2_count1 ) {
spinner2_count2++; }
else
{
String city_spinner_log = "CITY SPINNER";
Log.d(TAG, city_spinner_log);
String item = cityspinner.getSelectedItem().toString();
String nameContentType = "name";
String cityURL = "GetRestaurant.php?day=Day_Item&city=" + item;
Log.d(TAG, cityURL);
String shop_data = DataCall.getJSON(cityURL,nameContentType);
Log.d(TAG, shop_data);
Bundle bundle = new Bundle();
bundle.putString("shopData", shop_data);
Intent myIntent = new Intent(SearchDB.this, ShowRestaurant.class);
myIntent.putExtras(bundle);
startActivityForResult(myIntent, 0);
}
}
}
//ONCLICKLISTENER that saves RADIO value into a variable.
public OnClickListener radio_listener = new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
RadioButton rb = (RadioButton) v;
Day_Item = (String) rb.getText();
Log.d(TAG,Day_Item);
Toast.makeText(SearchDB.this, Day_Item, Toast.LENGTH_SHORT).show();
}
};
}
You would need a bit more code to get a good solid answer. Such as how is Day_Item allocated? And is it's scope global? Are you calling it from another activity or the one it's allocated within? These are just guesses at this point:
1) Are you sure your onClickListener isn't firing multiple times? Thus setting Day_Item to an undesired text or nothing at all?
2) Rather a question/answer,
"but when try using Day_Item later it does not show the valuable"
I'm assuming this means that it is null? Well if it's being set properly, and then it is being null'd... it either is being explicitly null'd by you somewhere (such as (1)) or else the allocation and scope are the issue area I believe...