dimanche 31 juillet 2016

Assign The first element in 3D array to 2x2 matrix

I have an array wich is 3D ( int [][][] A) and i would like assign ( initialize the first value of the A array to (int [][] B) which 2D array 2x2 matrix.

I used the code bellow :

    int ces =2;
    double [100][2][20]smp ; 
    double KMC [2][2];
      for(int ii = 0; ii <ces ; ii++){
         smp[0][ii]=  KMC[ii]; 
        }

The code is duplicating KMC.

How to iterate through range of Dates in Java?

In my script I need to perform a set of actions through range of dates given the start date and end date. Please provide me guidance to achieve this using Java.

for ( currentDate = starDate; currentDate < endDate; currentDate++) {



     }

I know the above code is simply imposible , but I do it in order to show you what I'd like to achieve

Security alert about libpng in my google play console

I received a security alert in my google play console about 2 applications ( games made by buildbox ) , the alert said that my application uses a version of libpng which presents a security flaw , I can't find this lib in my project , any solution please ? they gives me this link also https://support.google.com/faqs/answer/7011127

How can I Pan the views in an activity when a popupWindow shows at the bottom

I Have a popup that I displays at the bottom. My requirement is to close the soft keyboard before showing the popup. However, the views loose panning when i closes the key board to show the popup. Is there anyway to enable the views to pan without opening the soft key-board? I mean with the popup showing. Been working on this for hrs. Need help please..

I am trying to get single digit precision using Math.round [duplicate]

This question already has an answer here:

My code:

double protein = ap.nextDouble("The number of grams of protein in this food");      
double proteinCalorie = (double) Math.round(protein * 4);

Java Regex match and replace

I have set of some characters as below :

[A-Za-z0-9/-?:().,’+#=! ” %& * <>; {@rn] 

I have to write a program in java to make sure input is not having any character out of this set and if they do, I have to replace them with spaces.

How can I achieve this ? Only Java 6 please.

Geofences shapes, API v2 android

reading the android and google maps Api v2, I've just found geofences defined by radius/circles.

I was wondering if there is a way to create custom shapes i.e. rectangles or any other irregular shapes.

I was planing to geofence the are of a park.

If custom shape geofencing is possible, please let me know the topics to study.

Android studio grid of buttons auto align

Say I want 3 rows and 3 columns of buttons so 9 buttons in total. If one button in any position is removed, how would I go about shifting them so there isn't a gap where the button once was? I can think of some lengthy and possibly unnecessarily complicated ways to achieve this in an activity. Is there a simpler way to do this through the layout file?

Wallpaper change code not working

The line wallpaperManager.setResource(R.drawable.wall1); gives error (red line on R.drawable.wall1)

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.wallpaper_set);

    bSet = (Button) findViewById(R.id.bSetWall);

    bSet.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            WallpaperManager wallpaperManager = WallpaperManager.getInstance(WallpaperSet.this);
            try {
                wallpaperManager.setResource(R.drawable.wall1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
}

How does the String class work internally in Java?

How does the String class work? I have gone through many posts and I have not found an answer.

String str="ABC";

Does the above statement call the constructor?

public String(char[] paramArrayOfChar)

if yes ,how does it call it? We are using the assignment operator. How does it call the String class constructor.

How to modify the object of a javafx object property calling change listeners?

I have a javafx.beans.property.ObjectProperty<Calendar>. How can I modify the Calendar, so that javafx is registering it and the change listeners are invoked?

So, when I try to set the calendar field Calendar.YEAR is there a better solution than

Calendar c = duedateCalendar.get();
c.set(Calendar.YEAR,2017);
duedateCalendar.set(c);

Alternative for deprecated AudioManger.setStreamMute?

AudioManger.setStreamMute is now deprecated with api 23 and it is preferred to use AudioManager.adjustStreamVolume with AudioManager.ADJUST_MUTE.

My problem is that this kind of flag is only supported with api 23 while my app is minimum api 16.

Is there an other way of muting the whole system?

If not, why would google deprecate this method?

Android Java Editor

I searched internet for my question but i did not find any clue.

I want to make an educational app about java, and I want to put java editor(IDE)

inside the app for user to code java and practice.

How can I do that? How can i make this kind of an editor in my app?

Thank you.

Decrement on While loops

This is the complete code

Why is there a decrement on the while loop, but when running the program it give the impression as it is incrementing. Its very confusing to me please may somebody explain how operates this While loop?

output

Ternary Operator use to increase variable

Is it a good practice to use the ternary operator for this:

answersCounter = answer.length != 0 ? ++answersCounter : answersCounter;

This is a question that I always asked myself as it happens quite often. Or is it better to use a normal if statement. For me this looks much cleaner in one line.

Method to calculate sum and display the minimum of user inputs.

I am a noob

I have to write a method to calculate sum of user inputs (integers) and then output the minimum value user entered, also the user have to input -999 to exit the program, I am asked to use a while loop. please help. Also there is no set number of user inputs it can vary each time the program is run.

Android SYSTEM_ALERT_WINDOW permission

I read that with Android 6.0, users need to manually allow apps to hold this permission by going to app advanced settings and enabling "Draw over other apps". I have a Nexus 5 with Android 6.0 but I don't seem to be prompted to enable this setting. When I install apps from the Play Store that require this permission, such as LastPass, it gets granted automatically.

Why is this so?

Is there any way to rotate only a few elements on screen rotation (instead of whole screen)?

Currently i'm trying to show image/video properly (How can i rotate image and video if it was captured in landscape mode?) and as 1 of solution i see this one (overriding screen rotation method and prevent it for some elements).

Is it possible to do?

May be i can call rotation for elements whenever i want somehow?

Android studio error

IncrementalVisitor parseParents could not locate com/squareup/okhttp/RequestBody which is an ancestor of project class com/baasbox/android/net/OkClient$InputRequestBody. Error:Execution failed for task ':app:transformClassesWithInstantRunForDebug'. java.lang.ClassNotFoundException: com.squareup.okhttp.RequestBody

Some web pages say its a configuration error, others a compile time error.

Building the project works! But when running it the project this error occurs

In java, I want to enter a string in a scanner but it will only take the string until a space

My example input: Welcome to Java

My output with this code: Welcome

Expected output: Welcome to java

What is wrong with the following code where it accepts multiple characters with spaces?

import java.util.Scanner;
public class Example {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.next();
        System.out.print("String: " + s);
    }
}

X509 Extensions

How to set Extensions for an x509 certificate, in java, using bouncycastle API?

I managed to do the "Basic Constrains" like this:

...
X509V3CertificateGenerator gen = new X509V3CertificateGenerator();
...
boolean crit;
boolean isCa;
gen.addExtension(X509Extensions.BasicConstraints, crit, new BasicConstraints(isCa));

However, I can't figure out how to do the same for IssuerAlternativeName or KeyUsage.

Android: Info Window input

In my application I have an Info Window on marker in the map, like the one in the image below. example I would add a button or a checkbox inside the Info Window.

There's a way to add an input object inside the Info Window?

pls help me, thx.

how integer can return null value or throw NullPointerException [duplicate]

This question already has an answer here:

Why following snippet throw NullPointerException

package com.practice.test;

public class Test {

    int getValue(){
        return (true?null:0);
    }
    public static void main(String[] args) {
        Test t = new Test();
        t.getValue();
    }

}

How to disable keyboard popup?

The keyboard pops up wherever there's an EditText item. I wan't to disable this popup from occurring automatically and only want the keyboard to appear when the user manually sets focus on the EditText field. I have added the following in my Manifest file but it doesn't appear to work:

<activity android:name=".AccountActivity" android:label="yourtime" android:windowSoftInputMode="adjustResize|stateHidden"></activity>

samedi 30 juillet 2016

Android 6.0 Permission Error

I'm getting this error:

getDeviceId: Neither user 10111 nor current process has android.permission.READ_PHONE_STATE.
   at android.os.Parcel.readException(Parcel.java:1599)
   at android.os.Parcel.readException(Parcel.java:1552)

I had given it in manifest though. Is there any changes regarding Android 6.XX Marshmallow devices? I need to give READ_PHONE_STATE permission for getting device's IMEI. Pls. Help.

How to put this effect on an imageview in android

I'm using Glide for loading an image by an url and I want to reproduce the same effect on my imageview. How can I put this effect on an imageview like this one?

Tv Series Android App UI by Goutham

Required minimum for creating custom exception

I want to create a custom exception to use in my code. Defining it like this

public class MyException extends Exception {}

provides only empty constructor, which is still usable. So I need to define all the constructors manually. Is there a list of constructors that I should override and should I do it like that?

MyException(/* args */) {
    super(/* same args */);
}

difference between (double)(1/2) and (double)1/2 in java [duplicate]

This question already has an answer here:

I want to know the difference between

System.out.print((double)1/2);
System.out.print((double)(1/2));

The first answer I got was 0.5, but the second one gives 0.0 . Thanks in advance.

Signing every file created in a folder

I wrote a program in java that creates a JPG file and for every image it drops in a folder. I need assistance to determine when a new image is dropped in the folder. For every new image dropped in the folder it should be signed and hashed. I am a beginner i would really appreciate a script that i can embed with my program to carry out the process thanks.

Generate mock service as HTTP endpoint

I am using this example login to build the RESTful part in my application. However, I do not have a server connected. What I want to do is to create a mock service, using an HTTP generator as Mocky (check it). Does anyone know how can this be achieved? Thanks a lot!

getting gradle dependencies in intellij IDEA using gradle build

Grade build, even from inside Intellij IDEA does not put the dependencies into the External Libraries folder, so these classes don't show up as suggestions in the editor and when i manually add them as an import there is a compile error.

How can I get IntelliJ to automatically incorporate the dependenciers in my build.gradle file, for instance

compile 'com.google.code.gson:gson:1.7.2

Java code doesn't work [on hold]

Hey guys i am have a problem in java coding. I am using eclipse and my code is as following:

public class Application {
  public static void main(String[] args){
    int loop = 100;
    int looop = 90;
    while(loop > looop)
      System.out.println(looop);
    looop = looop + 1;
  }
}

The output should be like this:

90 
91
92
93
94
95
96
97
98
99

But it keeps on printing 90 and doesn't stop the loop.

Finding perimeter of figure in matrix in Java

Iv'e been trying to code a program that takes a few coordinates and find the perimeter of the figure from a matrix like, which should output 14:

XX
X XX
XXX

The perimeter would be the sum of the outer unit sides. I've tried finding the outer square perimeter of the figure, but it only works with very little cases. Any suggestions?

JSF: Update data from CDI-Bean for all clients

Is there a way in a jsf application to update a table which simply displays the datafields of a cdi-bean so it always shows "fresh" data to all clients?

E.g. i have the property: "String someInfo;" in my cdi-managed-bean and now one of my clients modifies is through an action. Now i want that the new value is displayed for all clients. How can i trigger that most efficient?

Java Applications embedded/Added to website

I have made a java application and want to add it to my website. Is that possible at this current age? I heard about the Applet tag but some browsers has stopped supporting that.

Is there another way for me to add my java application to my html pages in a way that every browser can run the java application on their machine when visiting my website?

Thanks

Making a String from KeyTyped in Java

I must make a nickname, and I do everything, using KeyListener. I want to write nickname using keyTyped, but I have no idea, how to save each letter. For exaple:

keyTyped(KeyEvent e){           
        char key = e.getKeyChar();
        nick = new String[10];
        for(int i = 0; i<10; i++){
            nick[i] = Character.toString(key);
            key = e.getKeyChar();
        }
 }

Unfortunately, every letter is the last one typed. How to do it?

Transaparent black gradient shape drawable color code

gradient for view pager indicator

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient 
        android:startColor="#000"
        android:centerColor="#00000000"
        android:endColor="#000"
        android:angle="270"
        android:dither="true"
     />
</shape>

This is the code i tried.But it ends up as pure black

Is it allowed for apps to connect to desktop via TCP

Having read Google Policy we find no reason why an app cannot establish a connection to a desktop server via TCP.

Is this correct?

If it is are there any limitations on what can be done with that connection?

One example can the app open a program on the pc remotely?

Last question what is the best responsive forum for app developers (multi platform)?

Can't install chromecast companionlibrary

I'm building a library for react native by using the chromecast companionlibrary.

When I add compile 'com.google.android.libraries.cast.companionlibrary:ccl:2.8.4', gradle sync fails with:

Failed to resolve: com.google.android.libraries.cast.companionlibrary:ccl:2.8.4

Weird thing is that i have other project that is not a library, and i don't receive any error messages.

Any idea?

Unable to connect websocket java client on Heroku Node.js server

I'm trying to connect my Java client to Node.js server on Heroku via Jetty websockets, but there is no connection. @OnWebSocketConnect method doesn't execute.

    WebSocketClient client = new WebSocketClient();
    SimpleEchoSocket socket = new SimpleEchoSocket();

    try {
        client.start();
        URI echoUri = new URI(destUri);
        ClientUpgradeRequest request = new ClientUpgradeRequest();
        client.connect(socket, echoUri, request);
        socket.awaitClose(50, TimeUnit.SECONDS);
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        try {
            client.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

How do I get network images with authentication in React Native?

The current supported way to get image is by inserting the {uri:link} object to the source props of Image, however, this does not have authentication enabled. Is there a way to insert an authentication token into the url call or other ways to have authentication for retrieving images? Thanks a lot!

  < Image
    style={styles.logo}
    source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}}
  />

How to properly use Std libraries in eclipse using java

I've added the external jar file which contains the StdDraw.class file and also I have the StdDraw.java file in my working directory but I am still unable to successfully run any code using the std libraries. Thank you!

my eclipse with .class and .java files

Can we use facebook "game service" for android non gaming applications?

Can we use facebook "game service" for android non gaming applications ? I want to reward my users for sending app install invite, FB page invite request and post share from my android non gaming application(Native android app). Can someone point me to achieve these ? Are there any FB policy violations to achieve these for non gaming applications ? Also I want to know the number of invites sent i.e., just invites count.

How to find a mid point of an android textview

I have a sub-class of TextView and want to draw a horizontal line by making its height to be 1px. It is ok but i also want to make it center vertically by setting the top margin as half of the height. However it turns out to be failed. Any solution to it? thank you

        LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1);
        int h = getHeight();
        lp.setMargins(0, h/2, 0, 0);

RatingCompat.newUnratedRating() causes System UI to crash

When I set MediaMetadataCompat rating as unrated, then turn screen off and back on, on some systems UI can't handle it and continuously restarts (obviously, crashes). My code:

new MediaMetadataCompat.Builder().putRating(MediaMetadataCompat.METADATA_KEY_RATING, RatingCompat.newUnratedRating(RatingCompat.RATING_5_STARS));

My environment: OS: Android 4.4 x86 (with Google APIs) Emulator version: 25.1.7

Is it a bug in the support library?

java okhttp manually close connection issues

When I try to use okhttp to get content from web sites, I found that I am unavailable to manually close the established sessions (using netstat to check), of course I know this is one of feature that natively support by okhttp, but in my case, the project should require to release sessions same as using HTTPURLConnection.close() methods, and I cannot find in okhttpclient.

How can I do it? thanks.

Spring Boot Example Understanding

I am using Spring Boot for reading and writing into CSV file but I uanble to understand @Bean tag. Why we are using this tag for processing or writing.

For example :

@Bean
    public Step step1() {
        return stepBuilderFactory.get("step1")
                .<Person, Person> chunk(10)
                .reader(reader())
                .processor(processor())
                .writer(writer())
                .build();
    }

I also have another question why we are passing step1 within get method?

Get rid of "The value for annotation attribute must be a constant expression" message

I use annotation in my code, and I try to use value which determine in run time.

I define my list as static final (lst), and I add to this list some elements.

When I use lst.get(i), I get compilation error:

The value for annotation attribute must be a constant expression

What is the solution for this issue?

vendredi 29 juillet 2016

Android double not working

I'm having this strange issue with android studio when i print a double value such as 1/4 like :

double test = 1/4
System.out.println(test);

//the output is 0.0

When i am calculating score which is ((correct_ans/MAXIMUM_CHANCE)*RANGE) it also calculates answer as 0.0, where correct_ans, MAXIMUM_CHANCE and RANGE are all integers. This is then shown on my Text View using ""+score. What am i doing wrong ?

Is it possible to launch a dialogfragment from a dialogfragment in android

I have a scenario where I'd like to open a dialogfragment from a button click in an already open dialog fragment. I'd like the original to either stay open and the new one open on top of it or hide the original and then reopen it when the second dialogfragment is dismissed. Just wondering if this is feasible before I go about trying to do it and possibly waste my time. Can anyone advise?

Element must be declared error for tag shape

I'm using Android Studio I/O(Preview) 0.3.2

I'm using this example to define background gradient in my app. I get Element must be declared error. enter image description here

I've checked and I'm not find any solutions. Can anyone help me how can I declare that tag in the xml

what is the use of having constructor in abstract class in java when we can't create objects with it [duplicate]

This question already has an answer here:

In java it is observed that we can't create objects with a class declared as abstract but we can declare a constructor in that class. Then what is the use of having a constructor in abstract class?

WebView on Lollipop won't work but it works on Kitkat

My WebView works fine on Kitkat and lower API levels, but on Lollipop my WebView is in an infinite loading state. How to fix it to work on Lollipop too?

This is error that is showing:

E/SysUtils: ApplicationContext is null in ApplicationStatus...
E/chromium: [ERROR:browser_gpu_channel_host_factory.cc(258)] Failed to init browser shader disk cache...
E/libEGL: validate_display:255 error 3008 (EGL_BAD_DISPLAY)

Android Studio SDK is not compatible with Windows

I've installed Android Studio in Windows 10. When I open Android SDK Manager and try to install 2.2 SDK platform I have the problem. It's not compatible with Windows and I can't install it. I've attached a screen shot of the problem. I can't install any version below 4.0 (API 14).

Screen shot

How to ensure that finish() destroy activity and clear all variables?

I'm working in a project with two activities, one shows list of rows from a database, when you click one it opens other activity with a form containing elements you can edit;

The problem is that when i close the second activity and reopen it (even if I call finish()) some variables keep data from last "session".

So may question is: How can I clear all variables/destroy activity?

Eclipse GC overhead limit exceeded

I saw there are more topics about this problem, but I don't found any solution for my case.

I tried :

-> Clean Project / Restart Eclipse (and Mac too)
-> Change XMS size in eclipse.ini
-> Delete JAR and add again

I saw this "crash" doesn't appear if I uncheck "android privates libraries" in my project's properties..... Why ? What am I supposed to do ?

Android draw parallel lines and join

I am looking for a way to join two parallel lines together. I'm making a timeline and use canvas.drawRect to draw two parallel lines. What i'm looking for is to join then together like in the below screenshot. I honestly don't know where to start on how to make a "U" shape with line at the bottom.

screenshot here

Telegram Bot — handle bot removing from contact list

I am using Java library for Telegram Bots Api: https://github.com/rubenlagus/TelegramBots

Is it possible to detect when bot is removed from user contact list?
I would like to handle this event to delete user settings (such as language) from database, so next time user adds my bot, he can specify settings from scratch and not stucking on selected previously.

Wifi Direct scan for group owners only

Is there way in android's Wifi Direct api to scan for all the group owners? I know I can determine if device requesting to connect is a group owner or not in onConnectionInfoAvailable(WifiP2pInfo p2pInfo) with if(p2pInfo.isGroupOwner), when one tries to connect to the peer. But can I specifically scan for group owners only, i.e. detect for all group owner prior to the connect intent?

'android-24' requires JDK 1.8 or later to compile

I use Android Studio and recently got the error:

Error:Execution failed for task ':app:compileDebugJavaWithJavac'. compileSdkVersion 'android-24' requires JDK 1.8 or later to compile.

But I have it installed already:

:Users..>java -version
java version "1.8.0_91" Java(TM) SE Runtime
Environment (build 1.8.0_91-b15) Java HotSpot(TM) 64-Bit Server VM
(build 25.91-b15, mixed mode)

How to fix it? Thanks

Android: Coloring part of a string using TextView.setText()?

I am looking to change the text of a TextView view via the .setText("") method while also coloring a part of the text (or making it bold, italic, transparent, etc.)and not the rest. For example:

title.setText("Your big island <b>ADVENTURE!</b>";

I know the above code is incorrect but it helps illustrate what I would like to achieve. How would I do this?

recyclerView.scrollToPosition doesn't fully shoe its last item

I use scrollToPosition(recycler.getAdapter().getItemCount() -1) in order to scroll my recyclerView to the last recyclerView item.

The problem is that all the recyclerView items are fully visible on screen except for the last item which is partially visible on the bottom of the screen. So, when I call scrollToPosition no scrolling occurs. How can I scroll the recyclerView to the last item so it will fully be display on the device screen?

How to add commons-math library in Android Studio

I am trying to import common-math library to my Android Studio project. I placed the file commons-math3-3.6.1.jar file in libs folder and in the gradle file I have this line:

compile 'commons-math3-3.6.1.jar' but I get this error: `

Error:(32, 0) Supplied String module notation 'commons-math3-3.6.1.jar' is invalid. Example notations: 'org.gradle:gradle-core:2.2', 'org.mockito:mockito-core:1.9.5:javadoc'.

Can anyone tell me what I have to do?

Java 8 volatile primitive class members should be initialized explicitlyin the constructor? [on hold]

I have following code:

class A{}

class B extends A {
    volatile boolean flag=false;
    B(){}
}

When I create a new instance of B using new B(), the flag value is set to true. But if I explicitly set flag = false in the constructor, then the flag value is set properly to false. Is this a bug in Java 8 ?

Android proguard, keep inner class

My android program has a class A, which has two static inner class. They are found to be stripped from .dex after applying proguard.

public class A{

  ...
  static class B{
    ...
  }

  static class C{
    ...
  }
}

I have put the following lines in proguard.flags, but seem no luck.

-keep class com.xxx.A
-keep class com.xxx.A$*

Any hint?

how to build project after code changes without mvn clean install?

I have a project in eclipse, a java app with appengine sdk and maven as my builder.

The .class files are not refreshed until i launch clean install, so every change i do in code i have to run:

  • mvn clean install
  • mvn eclipse:clean
  • mvn eclipse:eclipse

and then try to launch my app.

Help me please it's really annoying. Thanks

How to run a jnlp file with Java?

I have a jnlp file, normally i will execute with console (Linux) and works perfect.

javaws launch.jnlp 

But now I have to run from Java code, i tried this...

Process p = Runtime.getRuntime().exec(new String[]{"path/to/.jnlp"});

p.waitFor();

not working. as it should run ???

I hope you can help me, sorry for my English.

Android SurfaceTexture updateTexImage takes long time?

I am using Android MediaCodec class to play video on a Surface that uses a SurfaceTexture. Now on some of the devices the call to updateTexImage takes a very long time ~20ms on average? Any idea why that could happen? If I use Android MediaPlayer to play on the same surface the same call take very short time (0-1ms on average). Could it be related to the data size that I am passing to codec?

@NonNull not throwing compile error

import org.eclipse.jdt.annotation.NonNull;

  public class NullAnnotationTest {

        public void meth1(@NonNull String in) {
            System.out.println(in.length());
        }

        public static void main(String[] args) {
            NullAnnotationTest test = new NullAnnotationTest();

            test.meth1(null);
        }
    }

If we have @NonNull annotation, i thought we will get compile time error if we call meth1 with a null argument. But i am not seeing any sort of errors or warning in the above program. Can some correct me?

I'm trying to run my first android studio project but I get this error message

Warning: requested ram_size 1536M too big, reduced to 1024M

emulator: WARNING: VM heap size set below hardware specified minimum of 
96MB
emulator: WARNING: Setting VM heap size to 384MB
Hax is enabled
Hax ram_size 0x40000000
HAX is working and emulator runs in fast virt mode.
console on port 5554, ADB on port 5555
emulator: WARNING: UpdateCheck: Failure: Error
emulator: WARNING: UpdateCheck: failed to get the latest version,
skipping  check (current version '25.1.7'

Formatting Calendar

I need to formatt Calendar to get just the Date DD/MM/YY but no converted into String, i need it into Date dataType.

SimpleDateFormat simpleDate = new SimpleDateFormat("dd/M/yy");
Calendar cal2 = new GregorianCalendar(simpleDate);
 dateFormat.format(date); //Here i need to store the Date (dd/M/yy) into a Date kin of variable. (NO STRING)

Thus, when i need to update Calendar, into the Date result will reflect the changes.

Manually install Gradle and use it in Android Studio

I'm using Android Studio. How can I manually install and use Gradle within Android Studio.

I've downloaded Gradle from http://www.gradle.org/downloads version gradle-2.1-all.zip.

When I open the zipped file I can see bin, docs etc, but I don't know where to copy it. And even after copying how to use it within Android..

jeudi 28 juillet 2016

Greenfoot query

I have declared and initialized an object of the class 'Car' in 'MyWorld' class('Car' is a sub-class of 'Actor' class and 'MyWorld' class is the sub-class of 'World' class, and both 'Actor' and 'World' class belong to the same package):-

Car c1 = new Car();

I am not able to use the above object reference variable c1 in the 'Car' class. Can anyone explain the concept behind this phenomenon?

allow specif regex only in a block

I have a regex that matches every arabic(persian) sentence along with numbers and some symbols. The regex is:
[u0600-u06FFuFB8Au067Eu0686u06AF .!?:)(,;1234567890%-_#]+$
This works fine for arabic string.

Furthermore there is another requirement that string should not only match previous regex but also match words which start with @ followed by [a-zA-Z0-9-]^ followed by a string. How to match this?

After add images to drawable "Cannot resolve symbol R" issue not going away after clean, rebuild etc

I can't find a way to add images to drawable folder without getting "Cannot resolve symbol R" issue.

And once i get "Cannot resolve symbol R", I can't get rid of it by either clean, rebuild, sync, invalidate cache & restart solutions for the error. Only if i delete the files can I get the build to pass.

I am not sure what is wrong here.

Note: I am on Android Studio 2.1.1

Delphi - ListView onItemClick is not being fired

I'm working with a ListView component for both Android and iOS.

The onClick event is fired when the user hits the list, however the onItemClick event never occurs (yes, I did test them separately).

I'm also generating the ListItems dynamically, in the simplest way:

listview_available_gen.Items.Add.Text := 'whythehellyoudontitemclick';

Am I missing something silly?

Android Studio ERROR: 9-patch image

my english is not so god and my android studio skill :(

I become this error :

AAPT err(Facade for 1793161072): ERROR: 9-patch image C:PiewChatappsrcmainresdrawableleft.9.png malformed. AAPT err(Facade for 1793161072): No marked region found along edge. AAPT err(Facade for 1793161072): Found along left edge. Error:Execution failed for task ':mergeDebugResources'.

Some file crunching failed, see logs for details

What is this?

howto set specific amounts of COLUMNS with POI

For purpose of reading Excels by using Apache POI XSSFWorkbook (XSSFSheet and XSSFRow), codes like this:

FileInputStream fileInputStream = new FileInputStream(path);
XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
XSSFSheet sheet = workbook.getSheet(sheetName);
XSSFRow row = sheet.getRow(i);

i indicates difference rows, where the columns of each row are different.

My question is: how can I assign the columns of the row, even some of the cells are blank.

Detected JDK Version: 1.6.0-24 is not in the allowed range 1.7

When I ran the command

mvn clean package

I am getting error:

Detected JDK Version: 1.6.0-24 is not in the allowed range 1.7.

How to fix the above error? I tried to check jdk version isntalled and got this

java version "1.7.0_03"
Java(TM) SE Runtime Environment (build 1.7.0_03-b04)
Java HotSpot(TM) 64-Bit Server VM (build 22.1-b02, mixed mode)

how to fix this?

How to dim the area around a view in android?

I am trying to make an activity that needs to show square area as focused. So far I have done this.

enter image description here

Now what I want is to dim the area outside the square. Using framelayout dims the whole view. I only want to dim the region outside the square.

Overlap a transparent foreground of a Relative layout to make text views color gray transparent inside Relative layout

I tried following:

Created a frame layout containing that relative layout and made foreground /background color transparent. But I got transparent layout above my Relative Layout But Cannot see the textviews of Relatives layout which was initially of dark black color.

Also tried dynamically by creating a drawable with transparent color setting it to foreground of frame layout containing that relative layout. getting still the same result.

Any help would be greatly appreciated ?

How to chose an Executor for CompletableFuture::supplyAsync

CompletableFuture::supplyAsync(() -> IO bound queries)

How do I chose an Executor for CompletableFuture::supplyAsync to avoid polluting the ForkJoinPool.commonPool().

There are many options in Executors (newCachedThreadPool, newWorkStealingPool, newFixedThreadPool etc)

And I read about new ForkJoinPool here

How do I chose the right one for my use case ?

Can't add markers on real time on Google maps API for Android

I know how to add markers before the program runs, but I do not know how to let the user insert his own markers while the program is already running, and how to keep it stored.

Do you have an idea if gmaps API for Android has this functionality and if it really works?

I'm walking in circles and I can't find it anyway, I would really appreciate if you could help me with it.

Why is accessing an item by index slower in a linked list than an array?

I think I am missing a very obvious point but could not find it in my Java textbook.

I understand that node storage does not necessarily have to be contiguous in memory for linked list. Does this also mean that a linked list is not indexable? If so, then the only way to find an item in a linked list is to traverse the list, right, whereas you can get from an array by index?

Retrofit: How to send a POST request with constant fields?

I want to sent a simple POST request with one actual parameter:

@POST("/token")
@FormUrlEncoded
void extendSession(@Field("refresh_token")final String refreshToken);

But this request should also send some constant values requested by the server such as client_id, client_secret and grant_type which are constant and should not be part of the application API.

What is the best way to do this?

What does google-services.json really do?

I work on adding Google Analytics and GCM services to my current app. On the guide for both services implementation, google asks developer to generate a json file: google-services.json and put it under root directory of the app.

I found that even if I delete this json file from my app, the services still works.

Just want to know for sure, what is this file really for? What its usage and how does it work?

Android testing menu content

I create menu just like tutorial says.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.game_menu, menu);
    return true;
}

I want to write a JUnit test that checks if menu items strings are correct. However I don't know how can I do something like getMenu() from outside MainActivity class and then get menu items to strings or a list. Also I can't declare field 'menu'. Thanks for help.

How to fix "None-static method 'getSystemService' can not be referenced from a static context error?

I am trying to add network speed tester functionality to my app . But I am stuck at the error. Please fix ..

java file

 package com.buckydroid.app.droidcpu.tools;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;


public class network {
    public   wifispeed(Context context){
        WifiManager wifiManager = Context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo != null) {
            Integer linkSpeed = wifiInfo.getLinkSpeed(); //measured using WifiInfo.LINK_SPEED_UNITS
        }

    }
}

Custom Seekbar preference thumb bug

I create a custom SeekBar Preference for my app. And I see it has a bug with thumb when clicking on preference. See picture below:

Seekbar thumb bug

    <SeekBar android:id="@+id/seekbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@android:id/summary"
        android:layout_toEndOf="@android:id/widget_frame"
        android:layout_alignParentEnd="true" />

Get Constant data from firebase in Android

How to get a constant value from firebase?

I'm maintaining a global count variable of number of friends a user has. Everytime user wants to add friends I need to increment that variable. How can I achieve this.

If I use a OnDataChangeListener() I will be able to read the DataSnapShot only when there is some change in data. But I want to read the data even when some part of the data has not changed.

How to use a secondary Activity in a LiveWallpaper Engine

I have a class activity that make a graphic animation (MainActivity) in an AnimatedView. Work great as an app, BUT... I want to launch this activity inside a Live Wallpaper and use it like a Animated wallpaper. Is possible?

I try this simple code but don't work:

public class LiveWallpaperService extends WallpaperService {

private class LiveWallpaperEngine extends Engine {

    Intent myIntent = new Intent(".MainActivity");
    startActivity(myIntent);

}
}

@Override
public Engine onCreateEngine() {
    // TODO Auto-generated method stub
    return null;
}

Android Studio not found AndroidManifest.xml

I'm using the Android Studio v0.2.x.

I just created a new application with default settings: File->New Project->..., then step by step.

When I built it, it failed. The log is:

Android Source Generator: [MyApplication] AndroidManifest.xml file not found

But I have checked the source. It has the AndroidManifest.xml file. Any idea what causes this?

Spring Security OAuth 2 minimal password flow

I trying to add OAuth 2 support to existing REST Spring MVC + Spring Security project, using spring-oauth-library. Without formLogin and sessions (now i using basic and custom token authentication). I just need, that user can pass his username/password from browser client to REST-server by POST request, and recieve access_token. And then can access to any resource (in the same project), by authorities, corresponding to his role, that described in Spring SecurityConfig (WebSecurityConfigurerAdapter impl). Can i do this, with minimal extra-code?

java: call external jar program (-> 'create process error')

i'm trying open/execute another program of me, which is a (.jar) file,

but i'm gettin the error that 'it is not a windows application'

(java.io.IOException: CreateProcess error=193)

here is my code:

import java.io.IOException;

public class Test8 {

    public static void main(String[] args) {

        try {

            String filepath = "C://Users//Alex//Desktop//Speedtest.jar";

            Process p = Runtime.getRuntime().exec(filepath);

        } catch (IOException e) {

            e.printStackTrace();
        }

    }

}

How to define/design a java class

I have two classes Class1 and Class2:

inside a Class1 class, one of the method is written like this below:

public class Class1 {

    public List<Class2> getMembers() {

        List<IpAddress> addresses = new ArrayList<IpAddress>();
           ...
           ...
       return addresses
    }

    // other functions

}

I want to write/design Class2 class so, that above function is valid.

public class Class2 {

}

can anyone please help me.

-Thanks

How do I run the Microsoft Android Emulator from Hyper-V Manager?

When I use the hyper-v manager to try starting the virtual machine created by the Visual Studio Android Emulator and connect to it I only get a console prompt (not root) and not the Android UI. I also get the same terminal also if I try to connect to the machine while the emulator is running.

I would like to run the virtual machine headless (only with hyper-v) ad connect with the hyper-v viewer if I need the GUI.

mercredi 27 juillet 2016

Is it possible to get Google Analytics working in the browser with ionic?

I'm working with a team to build a mobile application with ionic. We also have the application hosted on a website, and we want to setup Google Analytics with it.

I know Google Analytics works on ionic for the mobile platform, but that same method does not work in the browser.

Is it possible to have Google Analytics work in the browser when using the Ionic Framework?

Why do I have to return Unit.INSTANCE when implementing in Java a Kotlin function that returns a Unit?

If I have a Kotlin function

fun f(cb: (Int) -> Unit)

and I want to call f from Java, I have to do it like:

f(i -> {
     dosomething();
     return Unit.INSTANCE;
});

which looks very ugly. Why can't I just write it like f(i -> dosomething());, since Unit in Kotlin is equivalent to void in Java?

Get image from SDcard filter using startWith

I'm stack with how to get image from SDcard folder which image name start with ("2.") here is my code:

    if (file.isDirectory()) {
        listFile = file.listFiles();
        // Create a String array for FilePathStrings
        FilePathStrings = new String[listFile.length];
        // Create a String array for FileNameStrings
        FileNameStrings = new String[listFile.length];

        for (int i = 0; i < listFile.length; i++) {
            // Get the path of the image file
            FilePathStrings[i] = listFile[i].getAbsolutePath();
            // Get the name image file
            FileNameStrings[i] = listFile[i].getName();
        }
    }

lucene indexer stopped without complete the whole files

I'm using Hibernate Search built on top of Lucene indexing to deal with text files existing in MySQL database. The hibernate search version 4.1.1, lucene version 3.5.0 and MySQL version 5.6 . All functions that I need was working well(search , indexing ... etc). Recently, I moved the same code, libraries, and database to another server with bigger hard disk and RAM.

The problem is the lucene indexer stopped without complete the whole files without any warning or errors. what could be the problem?

The contents in my MS Access database are not getting deleted using query in Java

However, the update query works fine.

import java.sql.*;
class MyDbDel
{
    public static void main(String arg[])throws ClassNotFoundException ,   SQLException
    {
    Connection con=null;
    Statement stmt;
    ResultSet rs=null;

    try{
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        con=DriverManager.getConnection("jdbc:odbc:Database1");
        System.out.println("Connected To My Database");
    }catch(ClassNotFoundException ce){
        System.out.println(ce);
    }

    try{
        stmt=con.createStatement();
       //deletequery 

        stmt.executeUpdate("DELETE FROM Customers WHERE FirstName='Bob'");
        stmt.close();
    }catch (SQLException e){
        System.out.println(e);
    }
}
}

Add(remove) element(s) from an ImmutableSortedMultiset

I am struggling how to perform basic operations using a Guava ImmutableSortedMultiset...

  • How would one create a copy of an existing ImmutableSortedMultiset that is contains a new element?
  • How would one create a copy of an existing ImmutableSortedMultiset where one of the elements has been removed?

If possible, I would like to be able to perform these operations without sorting the existing collection each time a new element is added(removed).

How to terminate Google App Engine instance programmatically in Java?

I want to prevent Google App Engine instances from continuing to run when critical initialization fails. How can I do it programmatically in Java? System.exit() does not work in GAE.

I want to write it in the implementation of ServletContextListener like below.

public class AppContextListener implements ServletContextListener
{
    @Override
    public void contextInitialized(ServletContextEvent context)
    {
        try
        {
            // Initialization
        }
        catch (Throwable t)
        {
            // Fatal. Terminate this Google App Engine instance.
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent context)
    {
    }
}

Custom RatingBar Shows different number of stars when on api 23

When setting RatingBar in xml file and set android:drawableProgress to custom drawable I've created (as described here) it shows 5 stars in the preview screen of android studio with api 22 but when I set the api target to api 23 it shows 1 star but the ratingbar (android:width="wrap_content") is at the same width as it is with 5 stars. This is also checked on cellular phones with Lollipop and marshmallow OS (Same behavior as described).

Android app and library dependencies clash

my app uses these dependencies

 compile 'com.android.support:appcompat-v7:22.2.1'
 compile 'com.android.support:design:22.2.1'
 compile 'com.google.android.gms:play-services:7.0.0'
 compile 'com.google.code.gson:gson:2.2.4'

when i imported seek arc library it uses different dependencies

  compile 'com.android.support:appcompat-v7:23.4.0'
  compile 'com.android.support:appcompat-v7:23.2.1'
  compile 'com.android.support:design:23.2.1'
  compile project(':SeekArc_library')

How can i solve this problem ?

How to create simple xml and test for parallel testing using junit?

I am using JUnit as a framework and I am trying to set parallel testing, everywhere I lookedonline I can only find examples for TestNG. I have the Grid up and running and I can test cross platform and cross browser but I need to wait for each test to finish in order for the next to start? I just need a basic example to get me started which I think will be of great help to others like me using JUnit.

Avoid Conflict between the events in google calendar android

I'm creating an android app that creates an event in google calendar using app.

Now it is creating an event properly, but there is a problem. If I schedule the first event from 1pm to 3pm, it should not create a second event if it is on 1.30pm to 2pm on the same day.

So what I'm saying is I want to avoid time conflict (double booking) between the time in same date.

Thanks in advance

Authenticating netbeans projects to connect with openshift?

I have create a application in open shift. When connecting it to net beans platform in severer area its asking for authentication required form. I have added user name and password of open shift website login and i also added public key and content, but nothing seems to works. What should be add here?

enter image description here

Config with Spring Cloud Config

I would like to ask two questions about the Spring Cloud Config.

1) Is it possible to do an implementation of Spring Cloud Config Server to recover the properties of a base mongodb instead of git?

2) The Spring Cloud Config Client Setup automatically update when you have a change in ownership in Spring Cloud Config Server?

Thanks!!!

AVD crashes when the default Camera App is started

I'm facing a very annoying problem. My AVD starts properly, but whenever I start the default camera app, the image becomes shaky then freezes to finally crash (not responding). I thought it was my app doing so but it isn't as the same is happening with the default camera app. I thought it's my webcam but it isn't as the same thing happens when I use an emulated back camera.

What can be the problem and how to resolve it?

Check if there is enough memory before allocating byte array

I need to load a file into memory. Before I do that I want to make sure that there is enough memory in my VM left. If not I would like to show an error message. I want to avoid the OutOfMemory exception.

Approach:

  1. Get filesize of my file
  2. Use Runtime.getRuntime().freeMemory()
  3. Check if it fits

Would this work or do you have any other suggestions?

Android - avoiding parallel run of same service within multiple apps

Little background: I am developing library which uses one background service. There is a hight probability that there will be 2 or more apps implementing the library on the same android phone.

Q: Is there any solution to prevent this background service from running if one of the installed apps already launched the service? I basically need only one instance of that bg service running no matter how many apps is implementing the lib with service.

Android Java - withdraw money output?

In my Java Program I have a method:

private void giveCash(int money) {
    int banknotes[] = {10, 20, 50, 100, 200, 500};
    StringBuffer cash = new StringBuffer();
    int i = banknotes.length - 1;
    while (i >= 0)
        if (banknotes[i] > money)
            i--;
        else {
            cash.append(banknotes[i]).append(" ");
            money -= banknotes[i];
        }
    // display cash in cash field
    TextView cash = (TextView) findViewById(R.id.cash);
    cash.setText(cash);
}

For, example, if money == 990 the output will be: 500 200 200 50 20 20

How to do the output: 500x1, 200x2, 50x1, 20x2 ?

Android Preference on a personal component witch already extends a class

I created a personal component and I would like to use it in my preference page. I have to extend Preference class, but my component already extends ImageView class.

Basic component: public class MyComponent extends ImageView { }

Should be for preference : public class MyComponentPref extends ImageView, Preference { }

It's impossible to extend more than one class, so with Preference, what is the best practice ?

Thank you for your help

How to get current/max jvm heap utilization (single value) with jstat or other command-line based tool?

JConsole or J VisualVM show the maximum heap size and the current heap utilization. How can I get the same values, during the lifespan of an application, using a command-line based tool, such as jstat?

From the metrics that I collect with jstat -gc (S0C S1C S0U S1U EC EU OC OU MC MU CCSC CCSU YGC YGCT FGC FGCT GCT), how can I compute the (single value) heap utilization that is given by JConsole/Visual VM?

Get async response data from Application to Launcher Activity

I'd like to make an initialization request when my app starts up. I then want to use the response in my MainActivity. I don't want to make that request in the Activity and then deal with the Activity lifecycle when the phone gets rotated.

So I was thinking of deriving from Application and making the request there. But what's the best way to send the response data to the my launcher Activity?

Is there a "best practice" solution here?

How to tackle when the status of an webelement changes from initial value "xxx" to changed value "yyy" after the page refresh with selenium wait?

This is what i have tried with no luck,
Not sure where i am going wrong?

   if (("xxx").equals(messageStatus)) {      
   FluentWait<WebDriver> wait = new FluentWait<WebDriver> (driver)            
                .withTimeout(90, TimeUnit.SECONDS)                  
                .pollingEvery(500, TimeUnit.MILLISECONDS)            
                .ignoring(NoSuchElementException.class);              

  wait.until(new Function<WebDriver, WebElement>() {      
            public WebElement apply(WebDriver webDriver) {            
           String messageStatus =
  MessageLogPage.messageStatus.getText();            
                if (messageStatus.equals("yyy")){              
                    MessageLogPage.receivedPresentation.click();            
                }      
                    return null;          
                 }                
        });    

Any help/suggestions are much appreciated.Thanks in advance!

How to show list of nearby events in facebook integration Android?

NearByevents code after integrating facebook sdk in my android

public class NearByEvents extends AppCompatActivity {

Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_near_by_events);

    button = (Button) findViewById(R.id.button);
    listNearByEvents();
}

private void listNearByEvents() {
    AccessToken tok;
    tok = AccessToken.getCurrentAccessToken();
    String id = tok.getUserId();
    new GraphRequest(
            AccessToken.getCurrentAccessToken(), "/"+id+"/events", null, HttpMethod.GET,
            new GraphRequest.Callback() {
                public void onCompleted(GraphResponse response) {
        /* handle the result */

                    Log.e("--result", response + "");
                }
            }
    ).executeAsync();
}

}

Java applet viewer blank

I am trying to run this very simple hello world program on eclipse but when I run it, the applet viewer opens and is blank. I have the latest java SE and I believe I have the appropriate acm files. I feel like there is a very simple fix but can't get it. Much thanks!

import acm.graphics.*;
import acm.program.*;
//import java.awt.*;


public class funGraphics extends GraphicsProgram {
    public void main() {

        GLabel label = new GLabel ("Hello World", 100, 75);
        add(label);

        }
}

Android signature verification vulnerability

I have been reading about the android signature verification vulnerability and below blog holds a solution to solve the malicious files that can be included in the apk by unzipping the apk file and including files in the META-INF folder. But I am unable to understand the solution specified here. Can anyone explain me the way by which it can be achieved.. The blog link is below..

http://blog.trustlook.com/2015/09/09/android-signature-verification-vulnerability-and-exploitation/

mardi 26 juillet 2016

Java constructor of an abstract class

As far as I know (please correct me if I'm wrong) a class that is abstract cannot be instantiated. You can give it a constructor, but just can't call new on that class. If you call super in a subclass, the superclass constructor will run (and thus create an object of that class?) then how come you can actually call super in a subclass of an abstract class? I'm sure it has something to do with my misunderstanding about a constructor making an object...

get Result from shell command on jTextArea

I have to execute a shell commande windows from java swing app and get real time result :

String cmd = jTextField1.getText();

StringBuffer output = new StringBuffer();

Process p;
try {
    p = Runtime.getRuntime().exec(cmd);

    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

    String line = "";
    while ((line = reader.readLine()) != null) {
        System.out.println("" + line);
        jTextArea1.append(line + "n");
    }

} catch (Exception e) {
    e.printStackTrace();
}

the problem is that writing in jTextArea is after execute finish not real time like System.out.println(..) .

how to count the number of nodes in a binary tree with only one child?

I have implemented the following function:

public int count(Node n) {
    if (n == null) {
        return 0;
    } else if (n.left == null && n.right != null) {
        return 1 + count(n.right);
    } else if (n.left != null && n.right == null) {
        return 1 + count(n.left);
    }
    return 0;
}

The problem is when I called it with:

System.out.println(tree.count(tree.root));

It only prints me the value of the root. What am I doing wrong?

How get Button coordinate?

I have a layout activity_main.xml:

    <Button
        android:id="@+id/button"
        android:layout_marginTop="50dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|top"
        android:text="@string/hover"/>

</FrameLayout>

How can i get Button's coordinate (x, y) on screen. for now I use:

button.getX()
button.getY()

but it return 0.0, How can i achieve this.
Thanks

methods after extending abstract class

I don't know exacly how to describe my problem so I'll make an example:

public abstract class A {

  public abstract void methodToOverride();
  public void methodNotToOverride() { }

}

public class B extends A {

  @Override
  public void methodToOverride() { }
  public void someOtherMethodNotFromClassA() { }

}

now I need to do such thing in my code:

A object = new B();
object.someOtherMethodNotFromClassA();

but I get "Cannot resolve method error". Defining such method in the abstract class is not an option. Any clue?

Make JPA persistence context recognize the changes made by bulk operations

JPA bulk operations, such as DELETE or UPDATE, are issued as SQL against the database. So, the persistence context is not updated to reflect the results of the operation.

For example, updating the department of all employees, the entities managed in persistence context will not have their values updated:

entityManager.createQuery("UPDATE Employee e SET e.department = null").executeUpdate();

How to make the persistence context recognize the changes made by the bulk operation?

How to change the libstreaming's videosource?

Everybody,I'm a young android developer,and now I have a requirement which is push my android phone's screen to my PC by rtsp. Now I have start my project base on libstreaming. But I found it's videosource must be camera.So how to change it?

this is the part that set the MediaRecorder's params

enter image description here

I want to automate the below scenario as I have to do this every week and there are minimum of 100+ action like this

My Question: I want to automate the below scenario as I have to do this every week and there are minimum of 100+ actions like this.

How I do it is: Go to Chrome developer options, TimeLine option, Click on Record and perform the action and stop recorder. Now collect the time taken for "Scripting, Rendering and Painting".

This time for all actions are required for management.

Please suggest any code in java or any tool, helps me a lot.

What does the read() function of AudioRecord read?

I'm writing an Android app, and I'm relying on processing the microphone signal. I'm getting the data with an AudioRecord object, on which I perform the read() function.

I am not exactly clear on the working of this function. Does it wait for the next BufferSize bytes and give them? Or does it just return the last BufferSize bytes from an internal buffer? I.e. if I call it twice in a short interval, will the data partially overlap?

Thank you!

How to achieve this parallax type material effect?

I recently read an [article here.][1] Everything works just fine and I got this: CASE 1

But, I want it to be like this:

CASE 2

So... How do i send the image behind the card view???

Article for the layout: github*com/antoniolg/MaterializeYourApp

Please replace * with a . before opening the github url

Can't set value of location_providers_allowed using "adb shell settings put"

I'm trying to turn location on using the following commands:

adb shell settings put secure location_providers_allowed gps,wifi,network
adb reboot

But it's neither changing the value of the variable location_providers_allowed nor turning it on under Android Settings UI after the reboot.

I tried the same command to set other variables, like mock_location, and it worked without problems. Is this variable not possible to be changed?

Android version: M

How to display accented character when I built a project in javafx?

normally I can fix the problem with old topics but now I am really stuck.

Well, my problem is when I built the project and the accented character. When I run the program with Netbeans there is no problem and the accented characters are ok. But when I built the project (in UTF-8) every accented character are strange symbols. I have this problem with windows 7.

With accented character I mean á, é, ó, etc. I tried using unicode but it didn't work.

How to get Android command line tools to work?

I cannot figure out how to get my Android command line tools to work. I had run the following commands, but when I type in Android avd, the output is bash: android: command not found. Does anyone have any advice on how to get the Android command line tools to work? I have installed the SDK, etc. I am not sure what to do.

export Android_Home=/Users/username/Downloads/adt-bundle-mac-x86_64-20131030/sdk/tools
export PATH=$PATH:$ANDROID_HOME/tools

Find out number of bits needed to represent a positive integer in binary?

This is probably pretty basic, but to save me an hour or so of grief can anyone tell me how you can work out the number of bits required to represent a given positive integer in Java?

e.g. I get a decimal 11, (1011). I need to get the answer, 4.

I figured if I could work out how to set all the bits other than the most significant bit to 0, and then >>> it, I'd get my answer. But... I can't.

Error building Player: CommandInvokationFailure: Failed to re-package resources. See the Console for details

Error building Player: CommandInvokationFailure: Failed to re-package
resources. See the Console for details.
D:ProgrammingIDEadtsdkbuild-tools21.0.0aapt.exe package
--auto-add-overlay -v -f -m -J gen -M AndroidManifest.xml -S "res" ...

I really need some help. I am about to release the 2nd alpha version of my app to test the play services. but this error keeps on popping? do you know How can I get rid of this. tried removing androidmanifest like other said. reimporting but it is still there?

how to set NAVIGATION_MODE_LIST on Toolbar new appcompat v7 21

Now all methods related to navigation modes in the ActionBar class, such as setNavigationMode()... are now deprecated.

The documentation explains:

Action bar navigation modes are deprecated and not supported by inline toolbar action bars. Consider using other common navigation patterns instead.

In my current application, there is a spinner on ActionBar. How do I apply NAVIGATION_MODE_LIST on the new widget Toolbar in the new version appcompat v7 21.
Thanks in advance.

I can't stop playing loop sfx in android cocos2dx

cocos2dx 2.2.6 c++ android 5.0

it works well on ios. But when my game warning sound effect playing can't stop all the time.

exp:

code in button1: int sfxId = SimpleAudioEngine::sharedEngine()->playEffect(fileName,isLoop);

code in button2: SimpleAudioEngine::sharedEngine()->stopEffect(sfxId);

I can't stop the same sfx. But I fount that if I click button1 and button2 crazy sometimes. It will can stop the sfx. So I guess it is the engine fatal bug

How do I append text to a specific position of JTextArea (Java)?

I have a determined text in a JTextArea and want to add text to a specific position (more specifically, before every line feed), depending on a user's action.

Example:

Lorem ipsum

Dolor sit amet

To:

Lorem ipsum {text here}

Dolor sit amet {another text here}

I tried JTextArea.append(String) method, but it doesn't give me the option of choosing where to place the text.

Array of generic holders

If I have a map of Entry .. objects , and I have an array in a class

private Entry<K,V> array;

Can I say

array = new Entry[someInt];

which I've done, or do I need a typecast like my instructor says is necessary such as

array = (Entry<K,V> E[]) new Entry[someInt];

Note that the first one did work when I ran my JUnits.

How do I get to the English-language Android developer website?

When I attempt to navigate to the Android developer website, I am redirected to a version of it much of which is in Chinese. For instance, if I try to navigate to:

developer.android.com

I am redirected to:

http://developer.android.com/intl/zh-cn/index.html

I want the English language site. In some cases, I've had to have web pages translated from Chinese. What am I doing wrong? How can I suppress this behavior?

How to make a Progress Button like this for android?

How can I make a Progress Button like the one in the below GIF in Android? I searched a lot, but I couldn't find anything exactly like this:

Animated Progress Button

This button is so pretty and I really want to be able to create a Progress Button exactly like this one. Any help or links to GitHub projects would be nice.

How to setOnTouchListener to overlap child?

I have create program like this:

enter image description here

Gray shape child of green shape and green shape child of megneta shape i set ClipChildren to false to show child(gray shape) over parent. I can get OnTouchListener from gray shape but OnTochListener not work on part of gray shape out of parent(green)

How can i do this?

getting string from string start wtih "abc" and end with "def"

I am using StringUtils (import org.apache.commons.lang3.StringUtils;) library to split string like:

String str = "ZXCVFMS2ZZ1012ZZ1012ZZ1000ZZ0923ZZ0990ZZ0990ZZ0990ZZ1020DEFZXCVFMS3ZZ1012ZZ1012ZZ1000ZZ0923ZZ0990ZZ0990ZZ0990ZZ1020DEFZXCVFMERRORDEF";

I need to take out string start with zxcv* and end with *def as

String tmp1 = "ZXCVFMS2ZZ1012ZZ1012ZZ1000ZZ0923ZZ0990ZZ0990ZZ0990ZZ1020DEF";
String tmp2 = "ZXCVFMS3ZZ1012ZZ1012ZZ1000ZZ0923ZZ0990ZZ0990ZZ0990ZZ1020DEF";

any help?

Firefox is opening but terminating immediately when we launch using Selenium WebDriver

When I open Firefox manually, it is opening correctly and functioning as expected but when I try to launch the same Firefox using Selenium WebDriver, code:

WebDriver driver = new FirefoxDriver(); 

Firefox is launching and after few moments am getting error "Firefox has stopped working" with the 2 options:

  1. Check online for a solution and close the program
  2. Close the program

Please try to resolve this issue as my many of the applications runs on Firefox.

lundi 25 juillet 2016

Hide activity title when toolbar expands - Material design

In Android Studio, I find the Scrolling Activity template, which the toolbar can have the paralax effect.

When the toolbar is expanded, the text also expands. And when it collapses, the text also collapses. enter image description here

My question is: how can I make the text disappear when the toolbar is expanses instead of expanding

Cannot read long filenames in Gpg / Maven

I have some deeply nested directories on Windows 10. I had to use the following setting in git:

git config --system core.longpaths true

I now started having problems with the GPG plugin. I can do a mvn install if I move the project directly to my C: drive.

[INFO] --- maven-gpg-plugin:1.6:sign (sign-artifacts) @ saf.core.runtime ---
gpg: can't open `C:\Users\name\workspace\xxxxx_xxxxx\xxxxxxxxxxx\xxxxxxxxx\xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\xxxxxxxxxxxxxxxxxxxxxxxxx\xxxxxxxxxxxxxxxxxxxxx\xxxxxxxxxxxxxxxxxxxxxxxxxx\xxxxxxxxxxx\target\xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.jar': No error

Does Java support default parameter values?

I came across some Java code that had the following structure:

public MyParameterizedFunction(String param1, int param2)
{
    this(param1, param2, false);
}

public MyParameterizedFunction(String param1, int param2, boolean param3)
{
    //use all three parameters here
}

I know that in C++ I can assign a parameter a default value. For example:

void MyParameterizedFunction(String param1, int param2, bool param3=false);

Does Java support this kind of syntax? Are there any reasons why this two step syntax is preferable?

Binding service by BroadcastReceiver

My Application uses a service that is started by a BOOT_COMPLETE BroadcastReceiver, in run i'm getting an error

my code:

public class projet extends BroadcastReceiver { 
 public void onReceive(Context context, Intent intent) { 

  intent = new Intent(context, ScreenshotService.class);
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  context.bindService(intent, aslServiceConn, Context.BIND_AUTO_CREATE);
}
}

error:

java.lang.RuntimeException: Unable to start receiver com.example.projet: android.content.ReceiverCallNotAllowedException: BroadcastReceiver components are not allowed to bind to services

How to detect and handle two fingers moving on the screen in the same time in android?

I want to be able to handle two diffrent fingers moving on screen in the same time but in two diffrent halves of the screen, I know how to handle a two finger tap but i cannot find anywhere how to deal with two fingers move, because there is only one "ACTION_MOVE". i tried to use it and distinguish the by the half they were clicked in, but it just catches the first finger that touches the screen and ignores the other one. How Can I do it?

How to print text on android bluetooth printer?

I have a bluetooth printer, need help to print text in this printer, is there any way to do this?

the printer has a SDK, BixolonPrinter.jar, with Java2op I extracted this to pascal:

Androidapi.JNI.Interfaces.pas

but when I try to install I get the following error:

Unable to create process: Unable to install .....Project2.apk
Failure
[INSTALL_PARSE_FAILED_MANIFEST_MALFORMED]

Does CompletableFuture have any thenX method accept supplier?

From https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html It shows CompletableFuture has the following thenX methods:

thenAccept(Consumer<? super T> action)
thenApply(Function<? super T,? extends U> fn)
thenRun(Runnable action)

I'm wondering what to do if I want to append a supplier (does not accept parameter but returns value) to a callback chain made by CompletableFuture?

Resizeable widget in ConstraintLayout

I've got a ListView item with three components aligned horizontally:

  1. an ImageView containing an icon
  2. a TextView with a headline
  3. another ImageView wit a status icon

Currently, I have them arranged via a RelativeLayout and my TextView is 'elastic'.

Is it possible to create the same layout in ConstraintLayout? Basically, what I'm asking is if I can create 2 fixed-length constraints instead of percentages.

Java notify when source is updated

So basicly the problem is: I have 2 cells in a sheet in a java program (kind of a excel like program) and i want to make a method that will repeat itself everytime this cells are updated. More specifically every time a user changes the cells on the sheet i have to repeat a method that will import the information of the cells to a list. So i will need to repeat this method automatically x times, depending on the cells behavior. Any ideias how to do this? Thanks

File google-services.json is missing from module root folder. The Google Services Plugin cannot function without it.[PLAY-SERVICES]

Updated my project to the latest Play services classpath 'com.google.gms:google-services:1.5.0-beta2' also using the latest version of playservices in my app.gradle file as

compile 'com.google.android.gms:play-services-location:8.3.0'
compile 'com.google.android.gms:play-services-gcm:8.3.0'

However when i compile gradle throws exception as follows

Error:Execution failed for task ':app:processDebugGoogleServices'. > File google-services.json is missing from module root folder. The Google Services Plugin cannot function without it.

Is this going to be a huge If/Then statement?

I am trying to implement a series of notifications based on radio button options the user selects. The notifications date and time will set depending on both radio button options and the user selected date.

for example the user selects Option 1, 2 and 3 along with Jan 1st 2017 and 12 notifications are set every couple of days/weeks depending on said options.

Before I get too far into this, am I just looking at a complex if then statement to set these notifications or am i missing another solution?

Using Android Studio, how to specify "--info" to make project?

I've just switched over to Android Studio, from Eclipse, and I see this error :

Error:FAILURE: Build failed with an exception.

  • What went wrong: Task 'compileDebugSources' not found in project ':myproject'.

  • Try: Run gradle tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

How/where in the Android Studio UI do I specify "--info" ?

Android studio unexpected lock file protocol

Am trying to import an android studio project into a new machine. The import goes on fine and the directories of the project are displayed correctly.However, when i try to build or clean the project, android studio raises the following error

Gradle 'ngoma' project refresh failed
Error:Unexpected lock protocol found in lock file. Expected 3, found 0.

I have tried closing and reopening the project, changing the permissions of the folder containing the projects but nothing is changing. How can I solve this error??

DownloadManager fails with ERROR_UNKNOWN on API 17

I'm trying to use android's own DownloadManager and it works perfectly on API 19+ but the same code fails (STATUS_FAILED) with reason ERROR_UNKNOWN almost as soon as I enqueue it on API 17 phones. here's my code

Context context = MyApplication.getSharedContext();
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE).setTitle(notiTitle).
setVisibleInDownloadsUi(false);
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+fileName);
request.setDestinationUri(Uri.fromFile(file));
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);

Android how to fill a relative layout inside scroll view to full screen

i can't fill my relative layout on full screen. when a make another layout for example in bottom, he will just appear after the last layout. this is my code

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".android_app_activity.EspacePersonnelActivity"
    android:layout_width="fill_parent"
    android:background="@drawable/ep_background"
    android:id="@+id/espacePersonnelLayout"
    android:layout_height="fill_parent">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >...

How to save geoposition location in java

I get the coordinate of the map when user click on the map.Now i want to save this and to pass the coordinates to other class.If anyone know the answer please guide.

Thanks

public class Corndinates extends MapClickListener{
/**
 * Creates a mouse listener for the jxmapviewer which returns the
 * GeoPosition of the the point where the mouse was clicked.
 *
 * @param viewer the jxmapviewer
 */
public Corndinates(JXMapViewer viewer) {
    super(viewer);
}


@Override
public void mapClicked(GeoPosition location) {

    GeoPosition  cord = location;
    System.out.println(cord);

}

}

Method NdefRecord.createTextRecord("en" , "string") not working below API level 21

This code works fine when I use it on a device with Android Lollipop (5.x) or Marshmallow (6.0):

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public NdefMessage createNdfMessage(String content) {
    NdefRecord record = NdefRecord.createTextRecord("en", content);
    NdefMessage msg = new NdefMessage(new NdefRecord[]{record});
    return msg;
}

But when I try this on a device with Android 4.2.2 (API level 17) my app crashes. How can I use this code to create a Text record on API levels below 21 (that's the API level where the method NdefRecord.createTextRecord became available)?

Searching an arrayList for an object and then adding value to that same object more than once

I just started working with arrayLists - basically what I need to figure out is how to search my arrayList and if that same object is found to add a new total value to it versus just swapping it out.

ie.

arrayList = (hats, $45) 

and I have a new value to add to hats (ie. $10 dollars) - so the ultimate new total for hats = $55

...and if hats are not in the list already to add it.

Any help is appreciated !

How can I put the state text into the switch track?

I want to create this custom Switch:

enter image description here

I searched a lot and I found nothing useful about how to customize a Switch putting the thumb ball and the state text inside of the track.

====== Solved:

I used the library https://github.com/kyleduo/SwitchButton, and thats great!

Facebook "Share" button is disabled when sharing photo in android app

I'm using the code below to share a photo on facebook. But the button is disabled. I have tried the code from this link and I was able to make it work. Here is my code:

Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.ic_information);
    SharePhoto photo = new SharePhoto.Builder()
            .setBitmap(image)
            .setCaption("Hello World!")
            .build();

    SharePhotoContent content = new SharePhotoContent.Builder()
            .setContentUrl(Uri.parse("https://developers.facebook.com"))
            .addPhoto(photo)
            .build();

    shareButton = (ShareButton) findViewById(R.id.buttonShare);
    shareButton.setShareContent(content);

How to change the android emulator RAM size from the command line?

I want to edit or change the ram size while creating the android emulator from command line.

EX: While creating the emulator it's taking default ram size(Android SDK 4.0.3) 512 MB But I want to increase it to 768MB or decrease it to 256MB.

I want to change only Ram size. Because there is an option to change the Ram size.

 Do you wish to create a custom hardware profile [no] Yes

If you entered yes, we need to provide so many things.

StringBuffer capacity()

public static void main(String args[]){
  StringBuilder sb=new StringBuilder();

    System.out.println(sb.capacity());
    sb.append("abcabcabcabcabcabcab");
    System.out.println(sb.length());
    System.out.println(sb.capacity());
    System.out.println("-----");
    sb.append("abcabcabcabcabcabcab");
    System.out.println(sb.length());
    System.out.println(sb.capacity());
    System.out.println("-----");
    sb.trimToSize();
    System.out.println(sb.capacity());
    System.out.println(sb.length());
}

o/p is

16
20
34
-----
40
70
-----
40
40

My question is that in second line, the capacity should be 36(20+16). why is it showing as 34.

Configuring Spring to ignore dependencies annotated with @Inject

I have an EJB class in which I need to inject two beans - one should be injected by the EJB container and other is a Spring Container.

@Stateless
@Interceptors(SpringBeanAutowiringInterceptor.class)
@LocalBean
public class SomeClass {

    @Inject
    private EJBClass a;

    @Autowired
    private SpringComponent b;

}

Here, the Spring interceptor trying to intercept the injection of bean 'a' and it's getting failed. I want the EJB container to inject the bean 'a' and Spring container to inject bean 'b'.

Please show me a way out here.

Integrating greenDao and Jackson

I am working on a project has an android side and a backend ,and for the JSON parsing am using Jackson library on both sides. using Play 2.0 for the backend ,Ebean is Jackson annotations friendly , but the problem is with GreenDao, since GreenDao uses code generation i have to type again all the annotations every time i migrate the database. I searched around and found only
this question but I can't find any template file

am using GreenDao 2.2.0

Thanks

dimanche 24 juillet 2016

android save Ringtone in Sharedprefrences and get it again

I have get the current ringtone . Now I just want to save it in the sharedpreference .

How can I achieve that?

Here the code I tried:

Uri currentRintoneUri = RingtoneManager.getActualDefaultRingtoneUri(context
                                .getApplicationContext(), RingtoneManager.TYPE_RINGTONE);
                        Ringtone currentRingtone = RingtoneManager.getRingtone(context, currentRintoneUri);

It's not working for ringing tone but it works for edittext.

sharedpreferences = getSharedPreferences(MyPRE, Context.MODE_PRIVATE);
                        String current = sharedpreferences.getString(CUR, "");
                                SharedPreferences.Editor editor = sharedpreferences.edit();
                                editor.putString(CUR, String.valueOf((currentRingtone)));
                                editor.commit();

Where does greenDAO generator code go?

I'm investigating greenDAO for an Android version of one of our iOS apps that heavily uses CoreData functionality.

I'm confused on how to start though. I've seen the DaoGeneratorExample code, but I'm not confident on how that relates to my project.

Let's assume my project is called MyApp. Do I need to create a SECOND Android project called MyAppDaoGenerator which I just run to generate java files and put them in the MyApp directories?

Or is the schema generation supposed to exist within the MyApp code?

How Can I Print Values and Index Numbers of an ArrayList without a Loop?

Here is my code so far:

import java.util.ArrayList;

public class BasicArraylists0 
{
    public static void main(String[] args) 
    {
        ArrayList arrayList = new ArrayList();

        arrayList.add(-113);
        arrayList.add(-113);

        System.out.println(arrayList); // prints [-113, -113]
    }
}

I want to code so that it prints values, -113s in this case, and index without any brackets without using any for or while loop?

For example, I would like to print something like

"Slot 0 has a -113" "Slot 1 has a -113" and so on.

Cannot resolve PlusClient

I try to integrate my android-application to g+. I try to add PlusClient to initialize it. But AndroidStudio says : Cannot resolve PlusClient. I added these import-header:

import com.google.android.gms.plus.Plus;

Also, I tryed to add these import-header:

import com.google.android.gms.plus.PlusClient;

but AndroidStudio cannot find PlusClient after .plus. I'm using 22 api. How to fix it? Does Api still support PlusClient? And is any differences bettween Plus and PlusClient?

Android Grid View space issue

in my project i'm using gridview and get images from database perfectly but it have some space line.

in my layout code :

            `  <GridView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="none"
            android:id="@+id/listView"
            android:numColumns="3"
            android:horizontalSpacing="1dp" />

`

and it looks like this : here

How can i fix this?

Save result adb command in set /p name= (Bat file)

I want to save the result of the adb commands below as a variable in my script, but the result is wrong.

adb shell getprop ro.product.brand

Output:Samsung

adb shell getprop ro.product.model

Output: SM-G920I

set /p Brand=adb shell getprop ro.product.brand
set /p Model=adb shell getprop ro.product.model
echo Brand: %Brand% Model: %Model% > Test.txt

But the result is:

Brand: 0 Model: 0 

Any Suggestions?

when i'm creating a button it become different size in different mobiles why...?

i'm new to the android when i'm creating the button it's become variation in different mobiles please help me. enter code here

    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_gravity="center_horizontal">
            <Button
                android:layout_width="wrap_content"
                android:gravity="center"
                android:width="300sp"
                android:layout_height="wrap_content"
                android:text="chennai to coimbatore"/>
        </RelativeLayout>
    </LinearLayout>

How to add an item to Quick Settings in Android

I was thinking if there is a way to add an item in Quick Settings Panel in android ? I have an app called Mirror by Koushik Dutta that does the same. It adds an item in Quick Settings panel. I decompiled the app and saw that he's moving the apk to /system/priv-app . That's it. Nothing's related to adding an item in Quick Settings Toggle. I know it'll require root access (just a college project). Please if anyone has any idea how it can be done, it would be really helpful.

Synchronize multiRunnable

I have 3 Runnable tasks

    PeriodRunnable runnableJob1 = new PeriodRunnable(driver, bolgaria);
    PeriodRunnable runnableJob2 = new PeriodRunnable(driver, egipet);
    PeriodRunnable runnableJob3 = new PeriodRunnable(driver, turc);

    runnableJob1.run();
    runnableJob2.run();
    runnableJob3.run();

I set 'synchronized' for my object

public class PeriodRunnable implements Runnable{
    private final PeriodCountdown counterdown;

    public PeriodRunnable(WebDriver driver, PeriodTour periodTour) {
        this.driver = driver;
        this.periodTour = periodTour;
        counterdown = new PeriodCountdown(driver, periodTour);
    }
    public void run() {
        synchronized (counterdown){
            counterdown.runCounter();
        }
    }
}

but my runnableJobs's starting work all together. What i'm doing wrong, tell me please?

I can't build or run my project

I tried to build and run my program. but I saw this message. what can I do?

Rishe is app name

Error 1 :

enter image description here

Error 2 : enter image description here

Thanks in advance !

Process large file in java

How to parse large file like 1.2GB where total lines in file is 36259190. How to parse each line to an object and save it in a list.

I get each time an OutOfMemmoryError.

List<Point> points = new ArrayList<>();

public void m2() throws IOException {
    try (BufferedReader reader = Files.newBufferedReader(Paths.get(DATAFILE))) {
        reader.lines().map(s -> s.split(","))
        .skip(0)
        .forEach(p -> points.add(newPoint(p[0], p[1], p[2])));
    }
}


class Point {
    String X;
    String Y;
    String Z;
}

Why one should try throw unchecked exception over checked exception?

I've been told that I should consider throwing Unchecked exception over Checked exception in my code and not only that, but to extend the RuntimeException with my own one. Now, I do understand the difference between the two, but still doesn't understand why should I do that?

If I have this method header which throws 2 kinds of exceptions:

public static Optional<String> getFileMd5(String filePath) throws NoSuchAlgorithmException, IOException {}

Why should I replace them with one (less detailed) exception?

The sdk platform-tools (23.1) is too old to check APIs compiled with API 24; please update

I am getting this error on the latest version of Android Studio and while I have installed both Android SDK Platform API 24 Revision 1 and Android SDK Build-Tools 24.

I have also tried File>Invalidate Caches/ Restart... and Build>Rebuild Project.

EDIT: I have also followed all instructions under Android Developers, but I still get this error.

Thanks in advance for any answers.

Email with HTML content is not working on Samsung native Email app

I am using below code for sending the email.

Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "You are invited for a meeting");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,Html.fromHtml(mailBody));
startActivity(Intent.createChooser(shareIntent, "Share meeting Info"));

*mailBody in EXTRA_TEXT is a HTML content with <a> tag and string message

Its working perfectly with Gmail app but anchor tag is not working in native email client in Samsung devices.

Create new button and add it in next position

how can I create a button programmatically

Button x = new Button (this);

but this button I add it in next available position. Now, if I do this and reach four created buttons, the fifth one will be outside the screen. How can I let the fifth one check if there is enough space to the right, if not, then the button would be created below the rest.

I tried grid layout and increase the column number but it is not good as I want to support Android 7.

Add sdk tools to path in Android Studio app

I have just installed Android Studio 0.2.2 and want to add the sdk tools to path which are in this folder;

/Applications/Android Studio.app/sdk/tools

so that i can use them with e.g. Phonegap.

But after i add this folder to path it still keeps saying:

android: command not found

Oddly, i can't run any of the executables in that folder even when i cd to that folder and type their names.

What am i doing wrong?

How to set changed menu icon permanently when app restarted

I have Already changed menu item dynamically but when app get restarted it changes back to default icon.How can i changed that icon permanently?

case R.id.action_bookmark:

                                                           String isBookmark=data.getBookmark();
                                                           if(isBookmark.equals("false")) {
                                                               NewsModel newsModel=items.get(getAdapterPosition());
                                                               newsModel.setBookmark("true");
                                                               ContentValues values = newsModel.getContentValues();
                                                               NewsTable.getInstance().updateEntry(newsModel.getId(),values);
                                                               item.setIcon(R.drawable.star);
                                                               notifyDataSetChanged();
                                                           }
                                                           else{
                                                               NewsModel newsModel=items.get(getAdapterPosition());
                                                               newsModel.setBookmark("false");
                                                               ContentValues values = newsModel.getContentValues();
                                                               NewsTable.getInstance().updateEntry(newsModel.getId(),values);
                                                               item.setIcon(R.drawable.ic_bookmark_white_24dp);
                                                               notifyDataSetChanged();

                                                           }

How to pass value using httpput method in jackson?

I am using core java and jackson for consuming REST services. Now I need to update using HttpPut method. How to update value using this method My request data is like this.

{
  "comments": "Notes",
  "displaynumber": "AA245",
  "order": 1
}

I am using this type of code:

HttpPut httpput = new HttpPut(targetURI + "comments/1001");
httpput.setConfig(config);
httpput.addHeader("content-Type","application/json");
httpput.addHeader("Accept", "application/json");

After this code how to send that Json data using jackson? And I am also using basic auth on this url.

Running a browser game in Java

I would like to know how I would kind of like run a online browser game, like tetris, as a Java application so I could control it (like in tetris using the wasd or arrow keys to move blocks) from within the application I program for the game. Not sure if that makes sense but don't know how else to explain it. The purpose is to hook it up to an AI program that plays the game, but yeah I don't know how to allow the program to control the game using the games allowed inputs.

Move TextView only up and down

I would need to move TextView only up and down. I have this code, but using it you can move TextView in any direction:

textView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                int eid = event.getAction();
                switch (eid) {
                    case MotionEvent.ACTION_MOVE:
                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) textView.getLayoutParams();
                        int x = (int) event.getRawX();
                        int y = (int) event.getRawY();
                        layoutParams.leftMargin = x - 200;
                        layoutParams.topMargin = y - 250;
                        textView.setLayoutParams(layoutParams);
                        break;
                    default:
                        break;
                }
                return true;
            }
        });

Is there a way to move TextView only up and down?

Regular expression not showing a match in Java [on hold]

I am trying to use regex with this specific pattern [1-9]00[1-9]00 on this test string:

010002001010002001010002001010002001010002001010004003010004003180

It isn't not finding any matches. Can anyone explain why?

When I run the match code on this string with [1-9]00, matcher.find() yields true and count increments.

Here is my code:

private static int  CheckforRegexMatches(String inputstring, String regexpattern) {
    Pattern pattern = Pattern.compile(regexpattern);
    Matcher matcher = pattern.matcher(Factor);

    int count = 0;
    while (matcher.find()) {
        count++;
    }
    //...
}

Push notifications if app is closed (React-Native)

I'm developing React-native app (iOS & Android).
Server connected through web-socket. Server sends notifications about some specific events. App suppose to notify user (using alerts). What if I need to notify user even if app is running in background or closed - how can i do that? Push notifications with this library will help in cases when app is in background, right? But it will not work if app is closed? So, how can i notify user if app is in background or closed?

subtract List by objid

I have this code in Groovy:

def list1 = [[objid:1, name:"One"], [objid:2, name:"Two"]];
def list2 = [[objid:2, name:"Hello"]];
def list3 = list1 - list2;

println list3;

The output of the code above will result something like this:

[[objid:1, name:One], [objid:2, name:Two]]

QUESTION: How to subtract List by objid? I want the result to be something like this: [[objid:1, name:One]] since objid:2 is present in the List1. How to code it?