w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » JAVA » Page 2
How to avoid creating custom exception classes whilst still throwing exceptions at an appropriate level of abstraction?
It's quite philosophical question. But in general it means that you should create your own exception with considering of existing ones. Example : In case of usage some external service and this service is unavailable , in this case I wouldn't recommend you to throw your own exception, because "Connection Refused" or "Connection timed out" will understand on the spot every programmer a

Categories : Java

Need of page factory in page object model
You can, in fact, use the page object pattern without using the PageFactory class. The page object pattern simply abstracts your business logic away from the physical structure of your pages. What the PageFactory class gives you is the ability to use annotations to automatically find the elements on the page without resorting to explicit findElement calls. It lets you write code like this: public

Categories : Java

Eclipse ASTVisitor ImportDeclaration from Package or JAR?
Ok, the solution is resolving the node to IBinding and then ITypeBinding and calling isFromSource(): IBinding b = node.resolveBinding(); if (b instanceof ITypeBinding && !((ITypeBinding) b).isFromSource()) { //do stuff }

Categories : Java

Bitwise shift to get max unsigned value
One first thing: (1 << (bitsCount)) - 1 This is a mistake because you are only performing integer arithmetic. You needed: (1L << (bitsCount)) - 1 But anyway I assume bitsCount is 64. In Java you cannot shift by a number larger than 63 for a long and 31 for an int (JLS 15.19): If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-ha

Categories : Java

Difference between finish() and super.finish() in Java?
finish() will call the finish() method on your class. super.finish() will call the finish() method on your parent class. Unless your are overriding the finish() method in your Activities (which you shouldn't), the two will do the exact same thing.

Categories : Java

replace a string which already contains double quotes with blank
You have to escape double quotes " with a backslash " public static void main(String[] args) { String s = ""welcome "to" the world""; s = s.replace(""welcome "to" the world"", ""); System.out.println(s); } or you can use s = s.replaceAll(""welcome "to" the world"", ""); Output

Categories : Java

WELD-001408 Unsatisfied dependencies for type [LdapService] with qualifiers [@Named] at injection point
The solution for my first error was: -Removing the @Stateless and @Inject from LdapService and the default constructor public class LdapService { }... -Create an Interface for LdapService and @Inject this interface to UserService public class UserService { private static final Logger logger = LoggerFactory.getLogger(UserService.class.getCanonicalName()); @Inject private LdapServiceInterface

Categories : Java

How to copy a tree where each node has more that two leaves?
How about using this pattern: class Item { //.... } TreeItem<Item> deepcopy(TreeItem<Item> item) { TreeItem<Item> copy = new TreeItem<Item>(item.getValue()); for (TreeItem<Item> child : item.getChildren()) { copy.getChildren().add(deepcopy(child)); } return copy; }

Categories : Java

Fatal Exception: java.lang.IllegalStateException GoogleApiClient is not connected yet
There's an issue with your code here: @Override public void onDestroy() { Log.d(TAG, "onDestroy"); if (googleApiClient != null) { if (googleApiClient.isConnected()) { LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, highAccuracyListener); googleApiClient.disconnect(); } Simply clean it up a bit: @Override public void onDestroy() { Log.d(TAG, "onDes

Categories : Java

Unable to click on the drop down link
This is not a dropdown, this is some fancy AJAX that looks like a dropdown. You need to use discrete clicks. Start with something like the following, but you will need to experiment (or post a link to your site) to get it to work the way you need. driver.findElement(By.className("dropdown")).click(); driver.findElement(By.className("dd_txt")).click();

Categories : Java

Java remove duplicates from array using loops
Try this: public static void duplicate(int numbers[], int size) { for (int i = 0; i < size; i++){ boolean duplicate = false; int b = 0; while (b < i){ if (numbers[i] == numbers[b]) duplicate = true; b++;} if (duplicate == false) System.out.print(numbers[i] + " ");} } You need to use == not = in your if statement.

Categories : Java

Java Struts call another action after executed action finsihed
You can use this <result type="redirectAction"></result> <action name="copyTestSuite" class="testSuiteAction" method="copyTestSuite"> <result type="redirectAction">/newAction.action</result> </action>

Categories : Java

Shared Preferences Null Pointer Exception
Try use 'apply' instead of 'commit' , the justification is here -> What's the difference between commit() and apply() in Shared Preference by Lukas Knuth. But basically, apply() will commits its changes to the in-memory SharedPreferences immediately. It's strong recommended use a class to manager your preferences, like 'MyPreferencesManager'.

Categories : Java

non build files of eclipse project in git repository
If there are files/directories that you do not want to push to the repository, you should use the .gitignore file. Create a .gitgnore file in the root directory of the git project. This is what a typical .gitignore file looks like in case of android. # Built application files *.apk *.ap_ # Files for the Dalvik VM *.dex # Java class files *.class # Generated files bin/ gen/ # Gradle files .grad

Categories : Java

How can I make fields in nested class real private?
If the class must not be moved to outside of Outer, you should define an interface for Inner and use only that. If you have only few instances and this is not a performance critical point of your application, you could just create anonymous implementations of that interface. The class isn't static anymore but at least it's a short and readable solution. private static interface Inner { void s

Categories : Java

Java: how to relaunch the class extended application from JButton?
I actually find this code from oracle which helped me a lot. I will share it here just in case if anyone needs https://docs.oracle.com/javafx/2/swing/SimpleSwingBrowser.java.htm explanation can be found here https://docs.oracle.com/javafx/2/swing/swing-fx-interoperability.htm#CHDIEEJE Thank you for trying to help me

Categories : Java

Is native platforms: junit-4.11.jar, junit-LICENSE.html normal in Play Store?
junit-4.11.jar and junit-License.html causes problem of supporting 0 devices on playstore. Please check which library or jar file in your is using this. Then you have to remove them and then upload your app. In my case, core.jar had these files, just open the jar file using winrar, go to lib folder and delete these 2 files. There will be no problem in functioning of jar file by doing this.

Categories : Java

How do you print the value of an int inside square brackets in Java?
If I am understanding the question. Say you have an int int number = 0; and you have a print statement. System.out.println("This is the number : [" + number + "]"); That is how you do it.

Categories : Java

Making a triangle with stars
public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("How many rows: "); int rows = input.nextInt(); for (int i = 0 ; i < rows ; i++) { for (int x = 0 ; x < rows - i ; x++) { System.out.print(" "); } for (int x = 0 ; x < i + 1 ; x++) { System.out.print("*"); } Syste

Categories : Java

Autowiring in spring (property name and bean name must be same)
It says property name, not field name. Property name in this case is inferred from the setter method name as defined by the JavaBeans naming convention (setB -> b), thus property name and bean name are the same.

Categories : Java

Android SDK not working issues with 'find_java.exe'
It seems that you have not set your java home path in your machine properly. set your JAVA_HOME AND JRE_HOME variables to the appropriate paths. Add the environment variable JAVA_HOME which points to your java installation directory and then try running eclipse. Refer this link to set environmental variables. :)

Categories : Java

Reading from a file in Java
Provided your text file is actually a good text file, it could be a character encoding thing. You need to provide the correct character set to your scanner in its constructor. So change the line: input = new Scanner(file); Into something like: String charset = "UTF-8"; input = new Scanner(file, charset); Ofcourse, you need to figure out which character set your file is actually stored as and

Categories : Java

How To Constrains Google OAuth To A Specific Google Apps Domain
send users off to Google with a parameter hd=<domain.com> in the authorization request (by modifying buildLoginUrl) to skip the account chooser screen and upon return, check that the claims returned from Google contain the hd claim with a value <domain.com> in getUserInfoJson to enforce the access requirement

Categories : Java

FATAL EXCEPTION: main java.lang.NullPointerException list=(ListView)
Try using this code in your MainActivity.java, it may help: private static { extract boolean Activity="MainActivity"; void overflow, @ActivityMain.stringResources/res { reorder(system.file.PrintOut"widgetResource"(); relate stringToRecipient.class; } return true } should do the job. No prob :)

Categories : Java

Java: count number of objects created - contsructor (call to this)
This looks like a homework assignment, so I will answer it based on this. If I am wrong, please comment and I will update my answer: Look at the places that actually increase the counter (there is only one) and then look at how the signature of this method/constructor is different from the others. That should help you understand what is going on. If that still does not help, use a debugger star

Categories : Java

Usage of final in java
A final field MUST be set before the constructor exits. Once set, the reference cannot be modified (the value cannot be reassigned). Emphasis on the cannot be reassigned. This means that while the reference cannot change, the value itself can change. This is legal: final List<Integer> list = new List<Integer>(); list.add(5); // the value of list changes, but the reference doesn't T

Categories : Java

what's the sequnce of channelhandler in netty?
When creating the pipeline I allways put "addLast(decoder, encoder, handler)". Check this out: http://netty.io/4.0/api/io/netty/channel/ChannelPipeline.html in "Building a pipeline" section.

Categories : Java

String Tokenizer code not Reading File Correctly
List all delimiters in StringTokenizer, or drop this parameter for the default: " f". new StringTokenizer(line, " f,;.?!"); After comments: Do it without StringTokenizer, using String.split: line = inputFile.nextLine(); String[] lineWords = line.split("( |\s\s+)", 3); Collection.addAll(list, lineWords); As you see I too mistrust whether the "tab" chars are real tabs, and

Categories : Java

Login error from android page to database (Codeigniter)
It's because of this part of your code: public String login(){ EditText edittext_user = (EditText)findViewById(R.id.editText); EditText edittext_pass = (EditText)findViewById(R.id.editText2); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("std_id", edittext_user.getText().toString())); na

Categories : Java

java.io.FileNotFoundException: File configuration.yml not found
Try executing the command with absolute paths instead, apparently configuration.yml isn't in the run folder. Example when configuration.yml is in /tmp java -jar target/drop-wizard-0.0.1-SNAPSHOT.jar server /tmp/configuration.yml

Categories : Java

JAX-WS: XmlElementWrapper produces extra client code
@XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Root", propOrder = { "detailList" }) public class Foo { @XmlElementWrapper(name = "detailList", required = true) @XmlElement(name = "detail") private List<Detail> detailList; public List<Detail> getDetailList() { return detailList; } public void setDetailList(List<Detail> value) {

Categories : Java

Open a local PDF document at an arbitrary page using java
What about using http://tika.apache.org/ and read the whole file, convert it and use the part of the pdf File that you want. You can read in any File you want with Apache Tika. With this Lib you can open any kind of files, also pdf-Files and proceed them. Take my Answer just as a first guess.

Categories : Java

Spring MVC @Valid annotation for all controllers?
you cannot omit @Valid annotation, since this is the way to tell spring which dto to validate, that is just the way the spring validation works. But having a BindingResult result to each of your methods is not necessary. You may omit it completely. If you want to do something when validation fails, you can catch the MethodArgumentNotValidException that is thrown in that case from an exception hand

Categories : Java

Parsing json object in java code
You can use com.google.gson for it: @RequestMapping(value = "/request", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody ResponseClass addDeparturePoint(@RequestBody String request) { Gson gson = new Gson(); RequestClass request = gson.fromJson(request, RequestClass.class); ResponseClass respons

Categories : Java

Do terminal operations close the stream?
No forEach does not close the stream (created by Files.list or Files.lines). It is documented in the javadoc, for example for Files.list: The returned stream encapsulates a Reader. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed.

Categories : Java

Android Lollipop Material Design Overflow Menu Icon color
Just add the secondary text color for the options menu, i.e.: <item name="android:textColorSecondary">@color/text_color</item> In some circumstances the secondary color is set to the primary color. I don't know yet why.

Categories : Java

Within Android, how do I start an activity or bring to front that activity if already on stack?
Use a flag in your intent when you want to start new Activity http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_REORDER_TO_FRONT Intent intent = new Intent(myActivity.this, myActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivity(intent);

Categories : Java

Is there a cross platform command that will print something to console?
You have to use Runtime for this: public static String runCommand(String command) throws IOException { String output=""; Process p=Runtime.getRuntime().exec(command); // Execute the command InputStream is=p.getInputStream(); // Get InputStream byte[] buf=new byte[1024]; // Increase if you expect output above 1024 characters is.read(buf); // Read the input and write to buf

Categories : Java

Is static variable loaded along with Class class object
A class can be loaded without being initialised. It is the static initialisation phase which sets static fields. However, usually when you use a class instance, method of a class, or instance of a class, it is already initialised.

Categories : Java




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.