Is this jQuery like syntax valid in Java? - java

In c++, this chain-able syntax is invalid.
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
act.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});

As long as your methods return the same object, that will work fine.
It will work in C++ too, except for the anonymous inner classes. (which C++ doesn't support until C++0x)
However, in C++, it would be more performant to return pointers and use the -> operator.

It is question what your setters return. If they return void you can't obviously call anything on it again. If they return the changed object it will be valid.

Related

How to determine in Android how to get if statement working using ListView,Hashmap, & item.get(...)?

I am somewhat of a beginner to Android (somewhat), and I am having a problem adapting code to my use. I've gotten everything except the if statement. Which is sad, because that's a rather basic thing.
I'm parsing a JSON file, and outputting it's results into a ListView using a Hashmap. So far, so good. I want to put an AlertDialog as one of the String "put"s of the Hashmap. Fine.
However, I now want to check that if the title (which is in the map) ends in ".pdf", to do a different action rather than displaying the AlertDialog.
Code:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { HashMap<String, String> item = (HashMap<String, String>)
parent.getItemAtPosition(position);
String theTitle = item.get("title");
String theDesc = item.get("description");
String theLink = item.get("link");
if (???condition???) {
//code I already have
} else {
final AlertDialog.Builder hope = new AlertDialog.Builder(MainActivity.this);
hope.setTitle("Description");
hope.setMessage(theDesc);
hope.setPositiveButton("DISMISS",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}});
hope.setNegativeButton("",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}});
hope.show();
}
Any, and all, help would be most appreciated!
You can use .contains method if your title have the full path like this.
if(theTitle.contains(".pdf")){
//Do something
}
I hope this answer your query.

How to call anonymous inner class in java

In the code, there is an alert box(for logout functionality).
This alert box is created inside a method (i.e. logout method) and then two onClickListener are anonymously added to it.
How can I call these anonymous listeners from outside?
Code:
AlertDialog.Builder builder
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id) {
//some logic
}
}
What I need is to somehow call this onClick method and pass the instance of same dialog box.
I have read examples of doing this with reflection, but in those examples anonymous class was a subclass i.e. return value of 'new' was catched
You could make the listener into a field variable.
private final DialogInterface.OnClickListener dialogYesListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//some logic
}
};
AlertDialog.Builder builder
builder.setPositiveButton("Yes", dialogYesListener);
You have two options:
1) Refactor your code to have a reference to an instance of an DialogInterfact.OnClickListener like this:
AlertDialog.Builder builder;
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//some logic
}
}
builder.setPositiveButton("Yes", listener);
2) I don't know whether there is such an API, but if yes, you can try to extract listener implementation from a builder. Pseudocode should look like this:
DialogInterface.OnClickListener listener =
builder.getPositiveButton().getListener(); //adjust this to a real API

AlertDialog example giving errors

I'm new to Java/ Android development (I started learning last night) so it is entirely possible I'm doing something horrendously stupid. However, after more than an hour Googling I've come up with nothing. I'm using Eclipse as my editor.
I'm reading the docs here for AlertDialog, which gives an example:
public static class MyAlertDialogFragment extends DialogFragment {
public static MyAlertDialogFragment newInstance(int title) {
MyAlertDialogFragment frag = new MyAlertDialogFragment();
Bundle args = new Bundle();
args.putInt("title", title);
frag.setArguments(args);
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = getArguments().getInt("title");
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(title)
.setPositiveButton(R.string.alert_dialog_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
((FragmentAlertDialog)getActivity()).doPositiveClick();
}
}
)
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
((FragmentAlertDialog)getActivity()).doNegativeClick();
}
}
)
.create();
}
}
I originally re-wrote it so I can start committing some of the methods to memory, but got an error "FragmentAlertDialog cannot be resolved to a type". I hit Ctrl+Shift+O to make sure I had the proper imports, but still it didn't go away.
So I copied/ pasted the example code and did the following, in this order:
Hit Ctrl+Shift+O to get the imports right (using android.app.DialogFragment, not android.support.v4.app.DialogFragment)
Declared my package at the top
Replaced R.string.alert_dialog_ok and R.string.alert_dialog_cancel with android.R.string.ok and android.R.string.cancel respectively
Removed setIcon(), as I don't have an icon to put in yet
I'm still getting errors:
FragmentAlertDialog cannot be resolved to a type (x4)
Illegal modifier for the class MyAlertDialogFragment; only public, abstract & final are permitted
Am I doing something wrong, or is there something wrong with the example code?
1.FragmentAlertDialog
Make sure the Activity you want to cast to is named FragmentAlertDialog. Make sure to also save everything - sometimes Eclipse won't make the connection until everything is saved.
2.Illegal modifier for the class MyAlertDialogFragment; only public, abstract & final are permitted
Take out the static modifier:
public class MyAlertDialogFragment extends DialogFragment {
or keep static and move this Fragment so it is enclosed within the Activity you want. This means that MyAlertDialogFragment should be inside your Activity, before that Activity's closing brace.
I'm new to Java/Android development
Don't start off with something so complicated. Learn Java then move to Android.
Hi try these code to implement alert dialog
AlertDialog.Builder alert2 = new AlertDialog.Builder(this);
alert2.setTitle("Your Title");
alert2.setMessage("Your Messages");
final EditText input2 = new EditText(this);
input2.setInputType(InputType.TYPE_CLASS_PHONE);
alert2.setView(input2);
alert2.setPositiveButton(GButton, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do something with value!
try
{
// do your stuff here
}
catch(Exception e)
{
}
}
});
alert2.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert2.show();

Is it possible to speed up initializing AlertDialogs in an Activity subclass?

I know that creating static methods to create AlertDialogs is not a good sign. But, whenever I felt like creating some AlertDialogs, I always have to place them inside an Activity subclass. I've been looking around in SO, trying to find a good way to factor the code, so that I don't have to initialize and create AlertDialogs from an Activity subclass.
Here is an example of my code, designed in such a way that I have to sacrifice performance speed for AlertDialogs, which is very necessary in my project plans.
public void onCreate(Bundle b) {
super.onCreate(b);
accelerometer = new Accelero();
leaderboard = new Score(this);
renderView = new RenderView(this);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(renderView);
// TODO: Refactor this, to speed things up.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
input = new EditText(this);
builder.setView(input);
builder.setTitle("Enter Name for High Score!");
builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO: Polish the dialog.
// TODO: Add a method of obtaining the score from RenderView.
renderView.getStage().reset();
renderView.setDialogFlag(false);
}
});
builder.setNegativeButton("Back", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
PlayActivity.this.onBackPressed();
}
});
renderView.setLosingDialog(builder.create());
builder = new AlertDialog.Builder(this);
builder.setTitle("You win!");
builder.setPositiveButton("Next Stage", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
renderView.createStage(getAssets(), stageNumber);
renderView.pauseGame();
}
});
renderView.setWinningDialog(builder.create());
builder = new AlertDialog.Builder(this);
builder.setTitle("Game Paused!");
builder.setPositiveButton("Back to Game", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
renderView.unpauseGame();
}
});
builder.setNeutralButton("Restart", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
renderView.resetGame();
}
});
builder.setNegativeButton("Main Menu", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO: Will probably improve some more on this.
PlayActivity.this.finish();
}
});
renderView.setPausingDialog(builder.create());
}
This isn't what I wanted. I tried placing them in a new thread to run, but it leaks memory, so it didn't work. Also, due to issues (Static AlertDialog methods will leak memory, etc.), I just don't have any other ideas on fixing this.
I don't know what to do next. So, may I ask, who else have a better way of initializing AlertDialogs without sacrificing performance speeds? Thanks in advance.
First thing I would do is to add some performance analysis instrumentation (measurements) to determine where the code is spending its time. Nothing is more painful than spending time trying to optimize something that doesn't need optimization ;-)
From looking at this I can see at least one simple optimization: This code creates 6 instances of 6 different anonymous classes just to handle the onClick() callbacks. IMHO that isn't necessary. You could just use this as the callback interface and make sure that your activity implements DialogInterface.OnClickListener. Then write a single method in your activity that handles all the click events:
public void onClick(DialogInterface dialog, int which) {
if (dialog == renderView.getLosingDialog()) {
if (which == DialogInterface.BUTTON_POSITIVE) {
// TODO: Polish the dialog.
// TODO: Add a method of obtaining the score from RenderView.
renderView.getStage().reset();
renderView.setDialogFlag(false);
} else if (which == DialogInterface.BUTTON_NEGATIVE) {
PlayActivity.this.onBackPressed();
}
} else if dialog == renderView.getWinningDialog()) {
// etc...
} else if dialog == renderView.getPausingDialog()) {
// etc...
}
}
I can't guarantee that this will improve performance, but it will definitely make the garbage collector very happy :-)

Break out of a method from anonymous inner class

I have a method:
void someMethod(String someString)
final String[] testAgainst = {...};
....
for(int i = 0; i < testAgainst.length; i++) {
if (someString.equals(testAgainst[i])) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Strings are the same! Overwrite?")
.setTitle("Blah Blah Blah")
.setCancelable(false)
.setPositiveButton("Overwrite", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int which) {
someAction()
}
})
.setNegativeButton("Nah", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int which) {
ESCAPE
}
});
AlertDialog dialog = builder.create();
}
}
doSomeOtherStuff();
}
Here's the thing, if my code reaches ESCAPE (that is, the user decides not to overwrite), I want to exit the method completely. I have tried...
changing someMethod() to return a boolean, then returning it from the negative button, but it won't let me because it's within a void internal method.
throwing an exception from ESCAPE to be caught externally, but the compiler won't let me because DialogInterface.OnClickListener doesn't throw.
using a break statement to leave the for loop, but that doesn't work either.
It would also be acceptable to simply leave the for loop. I can account for that. I've tried everything I can find and I'm at my wit's end.
You can throw a RuntimeException or one of its subclasses. The compiler won't complain about it.
You are not in the loop when that method executes. It may have access to the variables declared there (if they are final), but the OnClickListener is executed once they click, completely outside of/removed from that loop.
You could enhance your code with:
// Static class that contains nothing but a trigger to exit the loop
static class Cancel { boolean shouldCancel = false; }
void someMethod(String someString)
final String[] testAgainst = {...};
....
// Initialize it `final`, else it won't be accessible inside
final Cancel trigger = new Cancel();
// Add the check as additional condition for the `for` condition
for(int i = 0; i < testAgainst.length && !trigger.shouldCancel; i++) {
if (someString.equals(testAgainst[i])) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Strings are the same! Overwrite?")
.setTitle("Blah Blah Blah")
.setCancelable(false)
.setPositiveButton("Overwrite", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int which) {
someAction()
}
.setNegativeButton("Nah", new DialongInterface.OnClickListener() {
public void onClick(DialogInterface di, int which) {
// Use the trigger to communicate back that it's time to finish
trigger.shouldCancel = true;
}
AlertDialog dialog = builder.create();
}
}
doSomeOtherStuff();
}
Android has other methods of doing that too, like Handlers etc.

Categories

Resources