When creating a button from a Dialog Box - android

The original code has been deleted, the new working code is shown. The idea behind the code is to create a new textView within a layout that has a custom name to it that the user provides. Previously, a NPE error was happening. This is a fix. Any questions, please feel free to ask.
EDIT: Found the solution
The fix needs to be as followed:
accountEdit = new EditText(this); // accountEdit needs to be a global variable
then within the builder.setPositiveButton
builder.setPositiveButton(R.string.btn_save, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dInterface, int whichButton)
{
LinearLayout lineLayout = (LinearLayout)findViewById(R.id.linear_layout);
String newAccountName = accountEdit.getText().toString();
newTextView = new TextView( getBaseContext() );
newTextView.setVisibility(View.VISIBLE);
newTextView.setText( newAccountName );
newTextView.setId(id);
newTextView.setTextSize(35);
newTextView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickNew(view);
}
});
newTextView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Toast.makeText(getBaseContext(), "Testing" , Toast.LENGTH_LONG).show();
return true;
}
});
This will create the button, as well as set the name of the button to the information that is in the EditText within the Dialog Box. Previously, the EditText was from another activity, and was being called wrong, which caused the NPE. Thank you for all the help.

As Wenhui metioned, you call the finViewById inside the onclick listener of the button, so the wrong context is used. Do it like in the following example:
final EditText accountEdit = (EditText)findViewById(R.id.newAccountButton);
final String newAccountName = accountEdit.getText().toString();
final LinearLayout lineLayout = (LinearLayout)findViewById(R.id.linear_layout);
builder.setPositiveButton(R.string.btn_save, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dInterface, int whichButton)
{
newTextView = new TextView(getBaseContext());
newTextView.setVisibility(View.VISIBLE);
newTextView.setText("Test");
newTextView.setId(id);
newTextView.setTextSize(35);
newTextView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickNew(view);
}
});
lineLayout.addView(newTextView);
id++;
}
});

Related

How to call button or cast onItemClickListener in a different fragment?

I have been searching for this for days and to no avail whatsoever. I have the following problem: I have a MainActivity which is mostly indiferent to this problem. Inside this main activity I have a fragment. This fragment holds a viewpager whose element is also a fragment. Now, I have a button declared in the viewpager fragment layout, which I would like to call in the "parent" fragment. Any ideas???
Now, moving on to what I have already tried. I have tried to call directly, then I tried to declare an OnClickListener inside either fragment, and I also tried to use callbaciks. However none of these solutions worked...
I have tons of code useless to you, so I will only highlight the important parts
Parent Fragment (ScheduleFragment)
button_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Are you Sure?")
.setMessage("There's no coming back!")
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
deleteThis(viewPager2.getCurrentItem());
SharedPreferences preferences = getActivity().getSharedPreferences("Settings", Context.MODE_PRIVATE);
SharedPreferences.Editor sEditor = preferences.edit();
Integer position = preferences.getInt("Number of Days", 3) + 1;
sEditor.putInt("Number of Days", position);
sEditor.apply();
}
});
builder.show();
}
});
My Child Fragment (ViewPager_ScheduleObject
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Bundle args = getArguments();
((TextView) view.findViewById(R.id.textview_viewpager_schedule))
.setText("Day " + args.getInt(ARG_OBJECT));
ViewPager2_Schedule_Adapter viewPager2_schedule_adapter= new ViewPager2_Schedule_Adapter(this);
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("Settings", Context.MODE_PRIVATE);
Button button_cancel = view.findViewById(R.id.button_cancel_day);
button_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
If you need any more code, be sure to let me know! Any help is apprecciated!
Use Interface, Make Something Like this
public interface OurClient {
public void myButton(View view);
}
then Implement the interface in your main class

DialogFragment - Where to access layout components [i.e. editText.setText("")]

after doing a lot of research and trying (i think) every lifecycle method i could find, i´m really stuck:
What i want: Basically i have this DialogFragment ("ProfileUsernameDialogFragment")which should present my layout file ("fragment_profile_header_username_dialog").
in this layout file i have some TextViews and some EditTexts. I want to set the text of these EditTexts to some value i obtain in my programm, so setting it beforehand is not possible.
What i have:
public class ProfileUsernameDialogFragment extends DialogFragment {
...
#Override
public void onActivityCreated(Bundle savedInstanceState) {
EditText usernameText = (EditText) this.getView().findViewById(R.id.username_field);
usernameText.setText("TEST");
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Log.d(AppController.LOG_STRING, this.getClass().toString() + " - onCreateDialog - START");
AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
View view = this.getActivity().getLayoutInflater().inflate(R.layout.fragment_profile_header_username_dialog, null);
builder.setView(view);
builder.setPositiveButton(SAVE_SETTINGS, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
// Tried this too:
// EditText usernameText = (EditText)
// ProfileUsernameDialogFragment.this.getView().findViewById(R.id.forename_label);
// usernameText.setText("TEST");
}
});
builder.setNegativeButton(ABORT_ACTION, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
builder.setTitle(CHANGE_NAME_SETTINGS);
Dialog dialog = builder.create();
return dialog;
}
}
What i get: is a NullPointerException, no matter which position for the findViewById(R.id.username_field) i tried.
(I also tried onCreate and some other methods, i start thinking i might have another problem than the code location, but i really hav no clue) I tried to follow at least 6 similar questions about NullPointers in DialogFragments so i guess i need advanced help ^^
i should add i´m completely new to android so please be nice, but convention tipps etc. are very welcome! thx in advance :)
Following is what you need:
mAlertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(final DialogInterface dialog) {
final Button b = mAlertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
v.findViewById(R.id...)
}
});
}
});
});
}
});
Another option in addition to #David's answer is to use the onStart() method.
It looks like you were thinking along these lines in your question, except you used the onActivityCreated() method.
So for example:
#Override
public void onStart()
{
super.onStart();
EditText usernameText = (EditText) this.getDialog().findViewById(R.id.username_field);
usernameText.setText("TEST");
}
Android documentation has good example
So, if You wont set text in Your layout You need set it in onCreateView() method, for example:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup cont,
Bundle savedInstanceState) {
// Inflate the layout to use as dialog or embedded fragment
View view = inflater.inflate(R.layout.app_info, cont, false);
TextView title = (TextView)view.findViewById(R.id.dialog_header);
TextView content = (TextView)view.findViewById(R.id.dialog_content);
Button button = (Button)view.findViewById(R.id.dialog_button);
title.setText(this.dialogTitle);
content.setText(this.dialogContent);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
getDialog().dismiss();
}
});
return view;
}

Android Call Intent Null pointer exception

Im at my wits end here. I have a Class which Implements the OnClickListener cous i need the same action on Buttons accros my Application. This used to work just fine. But since I added some functionality by getting some needed data from the app preferences. startActivity throws a null pointer exception.Here is the class:
//Imports
public class CallClickListener extends Activity implements View.OnClickListener {
protected AppPreferences appPrefs;
String contactPersonName;
String contactPersonTelephone;
String name;
public CallClickListener(Context context){
Log.d("TRACE", "init CallClick");
appPrefs = new AppPreferences(context);
try {
JSONObject object = appPrefs.getConsultantObject();
contactPersonName = object.getString("contactPersonName");
contactPersonTelephone = object.getString("contactPersonTelephone");
name = object.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View view) {
final View v = view;
AlertDialog.Builder alert = new AlertDialog.Builder(view.getContext());
alert.setTitle("Anrufen");
alert.setMessage("Kontakt für " + name + ", " + contactPersonName + " anrufen");
alert.setPositiveButton("Anrufen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+contactPersonTelephone));
startActivity(callIntent);// this line throws the exception
}
});
alert.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(v.getContext(), "Abbruch", Toast.LENGTH_SHORT).show();
}
});
alert.show();
}
}
The Strings are all there from appPrefs, i also tried with hardcoding a phonenumber just incase. the Alert works fine, but as soon as i hit the positive Button, the app crashes
I add the Listener like this:
bCall.setOnClickListener(new CallClickListener(getApplicationContext()));
I added the necessary Call permissions.
I'm fairly new to Android dev, what am I missing?
Do this.... make the context object that you passed in the constructor into a field variable. and change startActivity to context.startActivity. It will work then.
EDIT: Highlighting the full solution.
bCall.setOnClickListener(new CallClickListener(getApplicationContext()));
should be changed to YourActivityClass.this instead of getApplicationContext.
Start Activity in the same task does not work with a context object that is not an Activity. So you need to either change the context to Activity or you start the activity in a new task. Also without calling startActivity on the context provided to your constructor you were getting the NPE because your CallClickListerner has no context.
Use activity context. Also check if you have initialized bCall. If you have not you will get NullPointerException.
bCall.setOnClickListener(ActivityName.this);
Also check this link to know when to use activity context and when to use application context
When to call activity context OR application context?
Edit:
Make sure you have added permission in manifest file
<uses-permission android:name="android.permission.CALL_PHONE" />
For reference use the below. My Class extends Activity
Button b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v1) {
// TODO Auto-generated method stub
final View v = v1;
AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());
alert.setTitle("Anrufen");
alert.setMessage("Kontakt für " );
alert.setPositiveButton("Anrufen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:8095992052"));
startActivity(callIntent);// this line throws the exception
}
});
alert.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(v.getContext(), "Abbruch", Toast.LENGTH_SHORT).show();
}
});
alert.show();
}
});

Changing button text from AlertDialog

i am new to developing apps for android and i want to create a simple Conterter app, just for the start. In my view i have a edittext and a Button. If i click the button, it will open a AlertDialog with list of strings. I cant figure out how to manage this: When i click on one item in the AlertView i want to set the text of the button to the selected string and dismiss the AlertDialog. Can somebody please help me ?
public class VypocetDlzkyActivity extends Activity {
EditText HodnotaDlzka;
Button prevodDlzkaZtlacidlo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vypocet_dlzky);
}
public void zmenPrevodZ(View view){
final String[] jednotkyDlzky = {"milimeter", "centimeter", "decimeter", "meter", "kilometer", "svetelny rok"};
AlertDialog.Builder builder = new AlertDialog.Builder(VypocetDlzkyActivity.this);
builder.setTitle("Vyberte jednotku");
builder.setItems(jednotkyDlzky,null);
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String value = jednotkyDlzky[item].toString();
prevodDlzkaZtlacidlo.setText(value);
dialog.cancel();
}
};
final AlertDialog alert = builder.create();
alert.show();
}
You need to set the values of these 2 member variables in your onCreate() method, like this:
HodnotaDlzka = (EditText)findViewById(R.id.xxxx);
prevodDlzkaZtlacidlo = (Button)findViewById(R.id.yyyy);
xxxx is the ID you gave the EditText in activity_vypocet_dlzky.xml and yyyy is the ID you gave to the Button.
Also, after a button is clicked in the AlertDialog, the dialog is automatically dismissed, so you don't need to call dialog.cancel().
Problem is you didnt add any onClick listnerz.On clicking on button you need to call the required method.
public class MainActivity extends Activity implements OnClickListener {
EditText HodnotaDlzka;
Button prevodDlzkaZtlacidlo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HodnotaDlzka = (EditText) findViewById(R.id.e1);
prevodDlzkaZtlacidlo = (Button) findViewById(R.id.b1);
prevodDlzkaZtlacidlo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String[] jednotkyDlzky = {"milimeter", "centimeter", "decimeter", "meter", "kilometer", "svetelny rok"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Vyberte jednotku");
builder.setItems(jednotkyDlzky,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String value = jednotkyDlzky[item].toString();
prevodDlzkaZtlacidlo.setText(value);
}
});
enter code here
final AlertDialog alert = builder.create();
alert.show();
}
}

Cannot refer to a non-final variable db inside an inner class defined in a different method

I'm developing an app for Android but I got stuck on deleting things from my database!
I'm getting an "Cannot refer to a non-final variable db inside an inner class defined in a different method" error! I know what this error means but I can't seem to find a solution to this.
Here is my code
package iwt.ehb.be.capita_selecta;
//my imports
public class RemoveActivity extends Activity {
Context context = this;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.remove_activity);
DBAdapter db = new DBAdapter(this);
db.open();
Cursor c = db.getAllTrips();
if(c.moveToFirst())
{
LinearLayout layout = (LinearLayout) findViewById(R.id.layout_removeTrips);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(5, 5, 5, 5);
do {
Button buttonView = new Button(this);
buttonView.setBackgroundResource(R.layout.btn_blue);
buttonView.setLayoutParams(lp);
buttonView.setText(c.getString(1) + " # " + c.getString(2));
final int id_trip = c.getInt(0);
buttonView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println(id_trip);
AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle("Attention");
alert.setMessage("Do you wish to delete this trip?");
alert.setIcon(R.drawable.icon);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
db.deleteSpecificRecord(id_trip);
}
});
alert.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
alert.show();
}
});
layout.addView(buttonView);
} while (c.moveToNext());
}
db.close();
//*******************
//BACK-button
//*******************
Button back = (Button) findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
}
}
And I'm getting the error at this line of code db.deleteSpecificRecord(id_trip);
If you have any idea on how I can resolve this that would be awsome ;)
Thx
Kevin
The problem is this line:
AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle("Attention");
context is a variable from the outer class. Variables like these can only be accessed if they are final.
There are a few possible fixes.
The first one is let your activity implement the onclicklistner
Public class RemoveActivity extends Activity implements OnClickListener { ...
buttonView.setOnClickListener(this);
imho the best solution
Another fix is make the variable context make a constructor with the following code:
Public RemoveActivity (){ this.context = this;}
but this is ugly code
i also think changing the line to
AlertDialog.Builder alert = new AlertDialog.Builder(RemoveActivity.this).setTitle("Attention");
would work.
I had the same error . The thing with this is that java treats each function with an independent scope . I see that you have declared the db Adapter object inside the on Create function . Take the declaration and declare it before the on create function ( rather extending the scope ) this should solve the problem . Your code should look like this :)
public class RemoteActivity extends Activity{
DBAdapter db = new DBAdapter(this);
Context context = this;
onCreate () ...

Categories

Resources