问:
Vue Js v-bind:class syntax not working ?
i am new in VueJs and i am having that little problem, first here is my sample HTML code :

```<code><div class="search">

        <input :class="{ longwidth : isActive }" v-show="showInput" type="text">
        <img @click="hideImgShowInput" v-show="hideImg" src="Assets/images/search-icon.png">

</div>
</code>```

i have followed the documentation exactly, and i am using PHPStorm as editor, but my function that changes the 'isActive' variable is not working i am having this error:

```<code>Attribute :class is not allowed here
</code>```

Any help would be much appreciated.

答: That sounds like a PHPStorm warning. Ignore it, or try a Vue-aware editor like vs code or atom. Your code looks fine to me.</p>

Body:
i am new in VueJs and i am having that little problem, first here is my sample HTML code :

        <input :class="{ longwidth : isActive }" v-show="showInput" type="text">

i have followed the documentation exactly, and i am using PHPStorm as editor, but my function that changes the 'isActive' variable is not working i am having this error:

Attribute :class is not allowed here

Any help would be much appreciated.


来源: stackexchange

问:
How to find an element present in data-hook through selenium
I have the HTML code as:

```<code><a class="a-size-base a-link-normal review-title a-color-base a-text-bold" data-hook="review-title" href="/gp/customer-reviews/R252N8IFRXV8TW/ref=cm_cr_getr_d_rvw_ttl?ie=UTF8&ASIN=B071NZZHF9">Security concern</a>
</code>```

and i have to search the element by data-hook as the class name is common for other attributes also and href and link-text are dynamic as it is changing for the next element as there are multiple elements that i need to fetch.

Can i search it by data-hook. If yes could someone help me with it!

答:
Sure you can.

CSS:

```<code>driver.findElement(By.cssSelector("a[data-hook='review-title']"));
</code>```

Xpath:

```<code>driver.findElement(By.xpath("//a[@data-hook='review-title']"));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the HTML code as:

Security concern

and i have to search the element by data-hook as the class name is common for other attributes also and href and link-text are dynamic as it is changing for the next element as there are multiple elements that i need to fetch.

Can i search it by data-hook. If yes could someone help me with it!

Body:
Sure you can.

CSS:

driver.findElement(By.cssSelector("a[data-hook='review-title']"));

Xpath:

driver.findElement(By.xpath("//a[@data-hook='review-title']"));


问:
Changing port number in Spring boot program. No application.properties
I just imported a java project from spring.io https://spring.io/guides/gs/rest-service/

I did it in my eclipse. I want to change the port number for the embedded tomcat to run but I can't see any application.properties (there is no src/main/resources) as it used to be when I would manually create a spring boot application through File->New->...

This is how the structure looks like

I checked out manifest.yml
and even typed

server:
  port : 9090

but it says, unknown property 'server' for type 'Cloudfoundary Manifest'

答:
YOu can add application.properties

You source folder will look like this  ignore other files


问:
Run app for more than 10 minutes in background
I am trying to keep the iOS app in active state for more than 10 mins when it enters in background state.

How can I implement this.

答:
If your App type is not one of VOIP/Audio/Location....(check Background Modes),

or you don't want to specify your App as a background App, you can implement beginBackgroundTaskWithName:expirationHandler or beginBackgroundTaskWithExpirationHandler to ask for more time to run your process in background. You can find the detailed description here

Apps moving to the background are expected to put themselves into a quiescent state as quickly as possible so that they can be suspended by the system. If your app is in the middle of a task and needs a little extra time to complete that task, it can call the beginBackgroundTaskWithName:expirationHandler: or beginBackgroundTaskWithExpirationHandler: method of the UIApplication object to request some additional execution time. Calling either of these methods delays the suspension of your app temporarily, giving it a little extra time to finish its work. Upon completion of that work, your app must call the endBackgroundTask: method to let the system know that it is finished and can be suspended.

Each call to the beginBackgroundTaskWithName:expirationHandler: or beginBackgroundTaskWithExpirationHandler: method generates a unique token to associate with the corresponding task. When your app completes a task, it must call the endBackgroundTask: method with the corresponding token to let the system know that the task is complete. Failure to call the endBackgroundTask: method for a background task will result in the termination of your app. If you provided an expiration handler when starting the task, the system calls that handler and gives you one last chance to end the task and avoid termination.


问:
Authentication when using Gmail API and Google App-Engine
This might (once again) be a silly/basic question. But here it goes.

I am trying to build a web-app that queries and displays some information from the user's Gmail. My current idea is as follows:

Have the backend run on Google AppEngine (coded in Python) where it has endpoints that take in queries like "How many such emails in the past one month" and returns the correct answer.

The frontend can be a website or an android app that can query the endpoints using REST.

The issue currently is with Authentication. I would like to know the right flow of authentication for my app. As far I see, there are two potential options:

1) Use the front-end to check if the user is logged in. If not, authenticate and send the user credentials to the backend  (using the javascript version of GMAIL API perhaps?).
2) Let the backend handle the authentication. Once it gets the query on the endpoints, if the user is not authenticated, it redirects the user to a login page. One of the issues I have with this is that I am using the Python on my AppEngine and all the GMAIL API tutorial for Python requires reading the credentials/clientID from a JSON file on the hard disk. This is not possible on AppEngine since we cannot store any file on local disk.

Can someone point me in the right direction?

Thanks.

答:
You don't need Google cloud storage to store the JSON file you can store it in  the App Engine it self, and also without storing inside the JSON file you can directly use it as clientID in the code itself.

client_id and client_secret within the JSON file

```<code>from oauth2client.client import flow_from_clientsecrets
...
flow = flow_from_clientsecrets('path_to_directory/client_secrets.json',
                               scope='https://www.googleapis.com/auth/calendar',
                               redirect_uri='http://example.com/auth_return')
</code>```

Without storing inside the JSON file

```<code>from oauth2client.client import OAuth2WebServerFlow
...
flow = OAuth2WebServerFlow(client_id='your_client_id',
                           client_secret='your_client_secret',
                           scope='https://www.googleapis.com/auth/calendar',
                           redirect_uri='http://example.com/auth_return')
</code>```

Please refer this documentation for further details

Body:
You don't need Google cloud storage to store the JSON file you can store it in  the App Engine it self, and also without storing inside the JSON file you can directly use it as clientID in the code itself.

client_id and client_secret within the JSON file

from oauth2client.client import flow_from_clientsecrets
...
flow = flow_from_clientsecrets('path_to_directory/client_secrets.json',
                               scope='https://www.googleapis.com/auth/calendar',
                               redirect_uri='http://example.com/auth_return')

Without storing inside the JSON file

from oauth2client.client import OAuth2WebServerFlow
...
flow = OAuth2WebServerFlow(client_id='your_client_id',
                           client_secret='your_client_secret',
                           scope='https://www.googleapis.com/auth/calendar',
                           redirect_uri='http://example.com/auth_return')

Please refer this documentation for further details


问:
EDSDK dlls not found in release
I'm developing a program that connects to a canon camera! I've filled the application in canon site and they have sent me the EDSDK dlls!
My program works fine, but when I try to run it in release to get the exe it's not able to locate the EDSDK dlls. I've checked the dlls are both in bin/release and bin/debug and the path is also correct!
Do you have any idea what is going wrong?
Thank you in advance!
PS: I'm using C# by the way.</p>

答:
You have to put all DLLs into the same directory as your main assembly (without the sub directories you got) – not only the EDSDK.dll.

I added a lib subdirectory to my project and added all DLLs (without any further sub directories) and marked them as "copy if newer". With a post-build event I move them after build from bin\debug\lib to bin\debug:

```<code>move $(TargetDir)lib\*.dll $(TargetDir)
</code>```

Note: according to the DLLs readme file, it is recommended to use the 32 bit DLLs.

Title: EDSDK dlls not found in release

Body:
You have to put all DLLs into the same directory as your main assembly (without the sub directories you got) – not only the EDSDK.dll.

I added a lib subdirectory to my project and added all DLLs (without any further sub directories) and marked them as "copy if newer". With a post-build event I move them after build from bin\debug\lib to bin\debug:

move $(TargetDir)lib\*.dll $(TargetDir)

Note: according to the DLLs readme file, it is recommended to use the 32 bit DLLs.


问:
How to move latitude and longitude coordinates using a virtual joystick?
I have an 8 directional joystick (consisting of a knob and pad),
after setting an onTouchListener to the pad, in MotionEvent.ACTION_MOVE, I'm calculating position_x, position_y, distance, and angle, to get a direction[1-8]. Given a direction[1-8], I'd like to continuously execute a specific movement(); but MotionEvent.ACTION_MOVE only executes while finger is moving..

How can I execute a movement of the lat lng continuously?

--Lat/Lng Movement (d=direction)--

```<code>private void movement(int d, double lat, double lng) {
        if (d==1) { //up
            lat = lat + 0.0000002;}
        else if (d==2){ //upright
            lat = lat + 0.0000001;
            lng = lng + 0.0000001;
        }
        else if (d==3) { //right
            lng = lng + 0.0000002;
        }
        else if (d==4) { //downright
            lng = lng + 0.0000001;
            lat = lat - 0.0000001;
        }
        else if (d==5) { //down
            lat = lat - 0.0000002;
        }
        else if (d==6) { //downleft
            lat = lat - 0.0000001;
            lng = lng - 0.0000001;
        }
        else if (d==7) { //left
            lng = lng - 0.0000002;
        }
        else if (d==8) { //upleft
            lat = lat + 0.0000001;
            lng = lng - 0.0000001;
        }
}
</code>```

--action_move, getangle, direction--

```<code>case MotionEvent.ACTION_MOVE: {

                    position_x = (int) (pad.getX() + pad.getWidth() / 2 - knob.getWidth() / 2 * -1 - knob.getX() - pad.getPivotX());
                    position_y = (int) (pad.getY() + pad.getHeight() / 2 - knob.getHeight() / 2 * -1 - knob.getY() - pad.getPivotY());
                    distance = (float) Math.sqrt(Math.pow(position_x, 2) + Math.pow(position_y, 2));
                    angle = (float) getangle(position_x, position_y);
                    knob.setX(event.getX() + pad.getX() - knob.getWidth() / 2);
                    knob.setY(event.getY() + pad.getY() - knob.getHeight() / 2);
                    direction();
                    movement(direction(), lat, lng);

 private double getangle(float x, float y) {
    if (x >= 0 && y >= 0) return Math.toDegrees(Math.atan(y / x));
    else if (x < 0 && y >= 0) return Math.toDegrees(Math.atan(y / x)) + 180;
    else if (x < 0 && y < 0) return Math.toDegrees(Math.atan(y / x)) + 180;
    else if (x >= 0 && y < 0) return Math.toDegrees(Math.atan(y / x)) + 360;
    return 0;
}

private int direction() {
    if (distance > 50) {
        if (angle >= 67.5 && angle < 112.5) return 1;
        else if (angle >= 112.5 && angle < 157.5) return 2;
        else if (angle >= 157.5 && angle < 202.5) return 3;
        else if (angle >= 202.5 && angle < 247.5) return 4;
        else if (angle >= 247.5 && angle < 292.5) return 5;
        else if (angle >= 292.5 && angle < 337.5) return 6;
        else if (angle >= 337.5 || angle < 22.5) return 7;
        else if (angle >= 22.5 && angle < 67.5) return 8;
    } else if (distance <= 50) { //knob at rest in middle
            return 0;
    }
    return 0;
}
</code>```

答:
You can check the following question's top answer and apply the same logic of using threads and have a while loop in your ui thread.

Continuous "Action_DOWN" in Android

Body:
I have an 8 directional joystick (consisting of a knob and pad),
after setting an onTouchListener to the pad, in MotionEvent.ACTION_MOVE, I'm calculating position_x, position_y, distance, and angle, to get a direction[1-8]. Given a direction[1-8], I'd like to continuously execute a specific movement(); but MotionEvent.ACTION_MOVE only executes while finger is moving..

How can I execute a movement of the lat lng continuously?

--Lat/Lng Movement (d=direction)--

private void movement(int d, double lat, double lng) {
        if (d==1) { //up
            lat = lat + 0.0000002;}
        else if (d==2){ //upright
            lat = lat + 0.0000001;
            lng = lng + 0.0000001;
        }
        else if (d==3) { //right
            lng = lng + 0.0000002;
        }
        else if (d==4) { //downright
            lng = lng + 0.0000001;
            lat = lat - 0.0000001;
        }
        else if (d==5) { //down
            lat = lat - 0.0000002;
        }
        else if (d==6) { //downleft
            lat = lat - 0.0000001;
            lng = lng - 0.0000001;
        }
        else if (d==7) { //left
            lng = lng - 0.0000002;
        }
        else if (d==8) { //upleft
            lat = lat + 0.0000001;
            lng = lng - 0.0000001;
        }
}

--action_move, getangle, direction--

case MotionEvent.ACTION_MOVE: {

                    position_x = (int) (pad.getX() + pad.getWidth() / 2 - knob.getWidth() / 2 * -1 - knob.getX() - pad.getPivotX());
                    position_y = (int) (pad.getY() + pad.getHeight() / 2 - knob.getHeight() / 2 * -1 - knob.getY() - pad.getPivotY());
                    distance = (float) Math.sqrt(Math.pow(position_x, 2) + Math.pow(position_y, 2));
                    angle = (float) getangle(position_x, position_y);
                    knob.setX(event.getX() + pad.getX() - knob.getWidth() / 2);
                    knob.setY(event.getY() + pad.getY() - knob.getHeight() / 2);
                    direction();
                    movement(direction(), lat, lng);

 private double getangle(float x, float y) {
    if (x >= 0 && y >= 0) return Math.toDegrees(Math.atan(y / x));
    else if (x < 0 && y >= 0) return Math.toDegrees(Math.atan(y / x)) + 180;
    else if (x < 0 && y < 0) return Math.toDegrees(Math.atan(y / x)) + 180;
    else if (x >= 0 && y < 0) return Math.toDegrees(Math.atan(y / x)) + 360;
    return 0;
}

private int direction() {
    if (distance > 50) {
        if (angle >= 67.5 && angle < 112.5) return 1;
        else if (angle >= 112.5 && angle < 157.5) return 2;
        else if (angle >= 157.5 && angle < 202.5) return 3;
        else if (angle >= 202.5 && angle < 247.5) return 4;
        else if (angle >= 247.5 && angle < 292.5) return 5;
        else if (angle >= 292.5 && angle < 337.5) return 6;
        else if (angle >= 337.5 || angle < 22.5) return 7;
        else if (angle >= 22.5 && angle < 67.5) return 8;
    } else if (distance <= 50) { //knob at rest in middle
            return 0;
    }
    return 0;
}


问:
Parallel loop with insert into table
I'm trying to insert into table in a parallel loop.

```<code>public static void idToHashEncoder()
{
   string sql = "";
   Stopwatch sw = new Stopwatch();
   sw.Start();

   Parallel.For(0, 1001, i =>
   {
      sql = string.Format(@"INSERT INTO ID_TO_HASH(ID, HASH) VALUES({0},
           {1})", i.ToString(), i.ToString().GetHashCode());

     GeneralDbExecuterService.executeSqlSelectDataScript(sql.ToString());

   });

   sw.Stop();
   TimeSpan elapsedTime = sw.Elapsed;
 }
</code>```

executeSqlSelectDataScript:

```<code>public static DataTable executeSqlSelectDataScript(string sql)
{
    //String sConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ORADB"].ConnectionString;
    // OleDbConnection myConnection = new OleDbConnection(sConnectionString);
    //OleDbCommand myCommand = new OleDbCommand(sql, myConnection);
    OracleConnection myConnection = new OracleConnection(sConnectionString);
    OracleCommand myCommand = new OracleCommand(sql, myConnection);

    try
    {
       //myCommand.Parameters.Add("@p1", OleDbType.Char, 5).Value = "Test%";
       myConnection.Open();
       //OleDbDataReader myReader = myCommand.ExecuteReader();
        OracleDataReader myReader = myCommand.ExecuteReader();

        var dataTable = new DataTable();
        dataTable.Load(myReader);
        myReader.Close();
        return dataTable;

   }
   catch (Exception ex)
   {
       logger.Error(ex.Message + "sql : " + sql);
       throw ex;
   }
   finally
   {
      myConnection.Close();
   }
}
</code>```

I'm getting this:

An exception of type 'System.TypeInitializationException' occurred in
  PRD.dll but was not handled in user code

Any economical solution will be welcome

答:
You are trying INSERT but use Datatable for result. Datatable is using for SELECT. You need below command for insert because of non result:</p>

```<code>myCommand.ExecuteNonQuery();
</code>```

Title: Parallel loop with insert into table

Body:
I'm trying to insert into table in a parallel loop.

public static void idToHashEncoder()
{
   string sql = "";
   Stopwatch sw = new Stopwatch();
   sw.Start();

   Parallel.For(0, 1001, i =>
   {
      sql = string.Format(@"INSERT INTO ID_TO_HASH(ID, HASH) VALUES({0},
           {1})", i.ToString(), i.ToString().GetHashCode());

     GeneralDbExecuterService.executeSqlSelectDataScript(sql.ToString());

   });

   sw.Stop();
   TimeSpan elapsedTime = sw.Elapsed;
 }

executeSqlSelectDataScript:

public static DataTable executeSqlSelectDataScript(string sql)
{
    //String sConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ORADB"].ConnectionString;
    // OleDbConnection myConnection = new OleDbConnection(sConnectionString);
    //OleDbCommand myCommand = new OleDbCommand(sql, myConnection);
    OracleConnection myConnection = new OracleConnection(sConnectionString);
    OracleCommand myCommand = new OracleCommand(sql, myConnection);

    try
    {
       //myCommand.Parameters.Add("@p1", OleDbType.Char, 5).Value = "Test%";
       myConnection.Open();
       //OleDbDataReader myReader = myCommand.ExecuteReader();
        OracleDataReader myReader = myCommand.ExecuteReader();

        var dataTable = new DataTable();
        dataTable.Load(myReader);
        myReader.Close();
        return dataTable;

   }
   catch (Exception ex)
   {
       logger.Error(ex.Message + "sql : " + sql);
       throw ex;
   }
   finally
   {
      myConnection.Close();
   }
}

I'm getting this:

An exception of type 'System.TypeInitializationException' occurred in
  PRD.dll but was not handled in user code

Any economical solution will be welcome

Body:
You are trying INSERT but use Datatable for result. Datatable is using for SELECT. You need below command for insert because of non result:

myCommand.ExecuteNonQuery();


问:
How to map JSON Data in Javascript ES6
I would like to get the JSON data from Coinmarket.

I get the data but can't map the Data.

below my Code

```<code>    const p = document.querySelector('p');
    let endpoint = "https://api.coinmarketcap.com/v1/ticker/?convert=EUR";
    let coinsdata = [];
    fetch(endpoint)
    .then(blob => blob.json()
    .then(data => coinsdata.push(...data)));

    console.log(coinsdata);
    coinsdata.map(coindata => {
        return p.innerHTML = coindata.id;
    });
</code>```

答:
The issue with you code is that you have not properly managed the asynchronous xhr call. The code is written outside 'then' code block which is why you are not seeing anything.

The Solution:

```<code>let p = document.querySelector('p');
const endpoint = "https://api.coinmarketcap.com/v1/ticker/?convert=EUR";
fetch(endpoint)
    .then(blob => blob.json())
    .then(data => {
        data.map(obj => p.innerHTML += ("\n" + JSON.stringify(obj)) );
    });
</code>```

This will print the objects in sequence. You can change the code as per your requirement. This was just to show the core idea.

Title: How to map JSON Data in Javascript ES6

Body:
I would like to get the JSON data from Coinmarket.

I get the data but can't map the Data.

below my Code

    const p = document.querySelector('p');
    let endpoint = "https://api.coinmarketcap.com/v1/ticker/?convert=EUR";
    let coinsdata = [];
    fetch(endpoint)
    .then(blob => blob.json()
    .then(data => coinsdata.push(...data)));

    console.log(coinsdata);
    coinsdata.map(coindata => {
        return p.innerHTML = coindata.id;
    });

Body:
The issue with you code is that you have not properly managed the asynchronous xhr call. The code is written outside 'then' code block which is why you are not seeing anything.

The Solution:

let p = document.querySelector('p');
const endpoint = "https://api.coinmarketcap.com/v1/ticker/?convert=EUR";
fetch(endpoint)
    .then(blob => blob.json())
    .then(data => {
        data.map(obj => p.innerHTML += ("\n" + JSON.stringify(obj)) );
    });

This will print the objects in sequence. You can change the code as per your requirement. This was just to show the core idea.


问:
Login Page will not open profile activity
After a user registers in the signup activity page I want them to be able to press the login button in the login page and then for the app to go to a profile activity page.  However, the app crashes after typing in the username and password and pressing the login button in the login page. Here is the sets of codes and this first set is the Login Page code in "LoginPageActivity.java" activity.

```<code>package com.example.xxxx.safetyxxxxxxx;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class LoginPageActivity extends AppCompatActivity implements View.OnClickListener{

    FirebaseAuth mAuth;
    EditText editTextEmail, editTextPassword;
    ProgressBar progressBar;

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

        mAuth = FirebaseAuth.getInstance();

        editTextEmail = findViewById(R.id.editTextEmail);
        editTextPassword= (EditText) findViewById(R.id.editTextPassword);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);

    findViewById(R.id.textViewSignUp).setOnClickListener(this);
    findViewById(R.id.buttonLogin).setOnClickListener(this);

}

private void userLogin(){

    String email = editTextEmail.getText().toString().trim();
    String password = editTextPassword.getText().toString().trim();

    if(email.isEmpty()){
        editTextEmail.setError("Email is required");
        editTextEmail.requestFocus();
        return;
    }

    if(!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
        editTextEmail.setError("Please enter a valid email");
        editTextEmail.requestFocus();
        return;
    }

    if(password.isEmpty()){
        editTextPassword.setError("Password is required");
        editTextPassword.requestFocus();
        return;
    }

    if(password.length()<6){
        editTextPassword.setError("Minimum length of password should be 6");
        editTextPassword.requestFocus();
        return;
    }

    progressBar.setVisibility(View.VISIBLE);
        mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                progressBar.setVisibility(View.GONE);
                if (task.isSuccessful()) {
                    Intent intent = new Intent(LoginPageActivity.this, ProfileActivity.class);
                    startActivity(intent);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    finish();
                } else {
                    Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

}

    @Override
    public void onClick(View view) {
            switch (view.getId()) {
                case R.id.textViewSignUp:

                    startActivity(new Intent(this, SignUpActivity.class));

                    break;

                case R.id.buttonLogin:
                    userLogin();
                    break;
            }
        }
    }
</code>```

Here is the profile activity called "ProfileActivity.java"

```<code>package com.example.xxxx.safetyxxxxxxx;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class ProfileActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
    }
}
</code>```

Here is the android manifest code.  I have tried many different variations of declaring the ProfileActivity class in this manifest based on research and previous issues in the past with the same logcat error.

```<code>   <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.xxxx.safetyxxxxxxx">

    <application
        android:name=".Database"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".LoginPageActivity"
            android:label="@string/app_name"/>
        <activity android:name=".Main2Activity" />
        <activity
            android:name=".SignUpActivity"
            android:label="@string/app_name">

    </activity>
        <activity android:name=".ProfileActivity"
        android:label="@string/app_name"/>
    </application>

</manifest>
</code>```

Here is the logcat error

12-02 12:04:56.008 2644-2644/com.example.xxxx.safetyxxxxxxx E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.xxxx.safetyxxxxxxx, PID: 2644
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.xxxx.safetyxxxxxxx/com.example.xxxx.safetyxxxxxxx.ProfileActivity}; have you declared this activity in your AndroidManifest.xml?
    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1933)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1616)
    at android.app.Activity.startActivityForResult(Activity.java:4488)
    at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
    at android.app.Activity.startActivityForResult(Activity.java:4446)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:720)
    at android.app.Activity.startActivity(Activity.java:4807)
    at android.app.Activity.startActivity(Activity.java:4775)
    at com.example.xxxx.safetyxxxxxxx.LoginPageActivity$1.onComplete(LoginPageActivity.java:79)
    at com.google.android.gms.tasks.zzf.run(Unknown Source:23)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
```
<p>Finally in case it is needed here is the loginpage layout code called "activity_login_page.xml"</p>
```<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginPageActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="53dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Hi, Welcome to Safety xxxxxxx Please Login or Signup"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/buttonLogin"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.66"></TextView>

    <Button
        android:id="@+id/buttonLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Login"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.87" />

    <EditText
        android:id="@+id/editTextEmail"
        android:layout_width="346dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="email"
        android:inputType="textEmailAddress"
        app:layout_constraintBottom_toTopOf="@+id/editTextPassword"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/textView2"
        app:layout_constraintVertical_bias="0.95" />

    <EditText
        android:id="@+id/editTextPassword"
        android:layout_width="346dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPassword"
        android:hint=" Password"
        app:layout_constraintBottom_toTopOf="@+id/buttonLogin"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        app:layout_constraintVertical_bias="0.87" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="219dp"
        android:layout_height="229dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toTopOf="@+id/editTextEmail"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.233"
        app:srcCompat="@drawable/safetyxxx" />

    <TextView
        android:id="@+id/textViewSignUp"
        android:layout_width="345dp"
        android:layout_height="35dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Do Not Have An Account?  Click Here"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonLogin" />

    <android.support.v4.widget.ContentLoadingProgressBar
        android:id="@+id/progressbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:visibility="gone"/>

</android.support.constraint.ConstraintLayout>
```

答:
You might give this a shot. </p>

```<code>    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.xxxx.safetyxxxxxxx">

    <application
        android:name=".Database"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".LoginPageActivity"
            android:label="@string/app_name">
            </activity>
        <activity android:name=".Main2Activity">
        </activity>
        <activity
            android:name=".SignUpActivity"
            android:label="@string/app_name">
    </activity>
        <activity android:name=".ProfileActivity"
        android:label="@string/app_name">
        </activity>
</application>

</manifest>
</code>```

<p>This may not help but I would personally give it a shot myself. </p>

ContentLicense: CC BY-SA 4.0

Body:
After a user registers in the signup activity page I want them to be able to press the login button in the login page and then for the app to go to a profile activity page.  However, the app crashes after typing in the username and password and pressing the login button in the login page. Here is the sets of codes and this first set is the Login Page code in "LoginPageActivity.java" activity.

package com.example.xxxx.safetyxxxxxxx;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class LoginPageActivity extends AppCompatActivity implements View.OnClickListener{

    FirebaseAuth mAuth;
    EditText editTextEmail, editTextPassword;
    ProgressBar progressBar;

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

        mAuth = FirebaseAuth.getInstance();

        editTextEmail = findViewById(R.id.editTextEmail);
        editTextPassword= (EditText) findViewById(R.id.editTextPassword);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);

    findViewById(R.id.textViewSignUp).setOnClickListener(this);
    findViewById(R.id.buttonLogin).setOnClickListener(this);

}

private void userLogin(){

    String email = editTextEmail.getText().toString().trim();
    String password = editTextPassword.getText().toString().trim();

    if(email.isEmpty()){
        editTextEmail.setError("Email is required");
        editTextEmail.requestFocus();
        return;
    }

    if(!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
        editTextEmail.setError("Please enter a valid email");
        editTextEmail.requestFocus();
        return;
    }

    if(password.isEmpty()){
        editTextPassword.setError("Password is required");
        editTextPassword.requestFocus();
        return;
    }

    if(password.length()<6){
        editTextPassword.setError("Minimum length of password should be 6");
        editTextPassword.requestFocus();
        return;
    }

    progressBar.setVisibility(View.VISIBLE);
        mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                progressBar.setVisibility(View.GONE);
                if (task.isSuccessful()) {
                    Intent intent = new Intent(LoginPageActivity.this, ProfileActivity.class);
                    startActivity(intent);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    finish();
                } else {
                    Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

}

    @Override
    public void onClick(View view) {
            switch (view.getId()) {
                case R.id.textViewSignUp:

                    startActivity(new Intent(this, SignUpActivity.class));

                    break;

                case R.id.buttonLogin:
                    userLogin();
                    break;
            }
        }
    }

Here is the profile activity called "ProfileActivity.java"

package com.example.xxxx.safetyxxxxxxx;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class ProfileActivity extends AppCompatActivity {

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

Here is the android manifest code.  I have tried many different variations of declaring the ProfileActivity class in this manifest based on research and previous issues in the past with the same logcat error.

   <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.xxxx.safetyxxxxxxx">

    <application
        android:name=".Database"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".LoginPageActivity"
            android:label="@string/app_name"/>
        <activity android:name=".Main2Activity" />
        <activity
            android:name=".SignUpActivity"
            android:label="@string/app_name">

    </activity>
        <activity android:name=".ProfileActivity"
        android:label="@string/app_name"/>
    </application>

</manifest>

Here is the logcat error

12-02 12:04:56.008 2644-2644/com.example.xxxx.safetyxxxxxxx E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.xxxx.safetyxxxxxxx, PID: 2644
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.xxxx.safetyxxxxxxx/com.example.xxxx.safetyxxxxxxx.ProfileActivity}; have you declared this activity in your AndroidManifest.xml?
    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1933)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1616)
    at android.app.Activity.startActivityForResult(Activity.java:4488)
    at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
    at android.app.Activity.startActivityForResult(Activity.java:4446)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:720)
    at android.app.Activity.startActivity(Activity.java:4807)
    at android.app.Activity.startActivity(Activity.java:4775)
    at com.example.xxxx.safetyxxxxxxx.LoginPageActivity$1.onComplete(LoginPageActivity.java:79)
    at com.google.android.gms.tasks.zzf.run(Unknown Source:23)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Finally in case it is needed here is the loginpage layout code called "activity_login_page.xml"

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginPageActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="53dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Hi, Welcome to Safety xxxxxxx Please Login or Signup"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/buttonLogin"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.66"></TextView>

    <Button
        android:id="@+id/buttonLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Login"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.87" />

    <EditText
        android:id="@+id/editTextEmail"
        android:layout_width="346dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="email"
        android:inputType="textEmailAddress"
        app:layout_constraintBottom_toTopOf="@+id/editTextPassword"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/textView2"
        app:layout_constraintVertical_bias="0.95" />

    <EditText
        android:id="@+id/editTextPassword"
        android:layout_width="346dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPassword"
        android:hint=" Password"
        app:layout_constraintBottom_toTopOf="@+id/buttonLogin"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        app:layout_constraintVertical_bias="0.87" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="219dp"
        android:layout_height="229dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toTopOf="@+id/editTextEmail"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.233"
        app:srcCompat="@drawable/safetyxxx" />

    <TextView
        android:id="@+id/textViewSignUp"
        android:layout_width="345dp"
        android:layout_height="35dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Do Not Have An Account?  Click Here"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonLogin" />

    <android.support.v4.widget.ContentLoadingProgressBar
        android:id="@+id/progressbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:visibility="gone"/>

</android.support.constraint.ConstraintLayout>

Body:
You might give this a shot.

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.xxxx.safetyxxxxxxx">

    <application
        android:name=".Database"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".LoginPageActivity"
            android:label="@string/app_name">
            </activity>
        <activity android:name=".Main2Activity">
        </activity>
        <activity
            android:name=".SignUpActivity"
            android:label="@string/app_name">
    </activity>
        <activity android:name=".ProfileActivity"
        android:label="@string/app_name">
        </activity>
</application>

</manifest>

This may not help but I would personally give it a shot myself.


问:
Google Maps API Tutorial - CurrentPlaceDetailsOnMap - task.isSuccessful issue on placeResult.addOnCompleteListener
I have just cloned the whole android-samples library and tried to run the CurrentPlaceDetailsOnMap project. I have done all the instructions given to me including creating my own API. However, everytime I just clicked Get Place (this triggers onOptionsItemSelected method then it triggers showCurrentPlace on the Activity), I get this error:

```<code>E/MapsActivityCurrentPlace: Exception: %s
 com.google.android.gms.common.api.ApiException: 13: ERROR
 at com.google.android.gms.common.internal.zzb.zzx(Unknown Source)
 at com.google.android.gms.common.internal.zzbj.zzy(Unknown Source)
 at com.google.android.gms.common.internal.zzbk.zzp(Unknown Source)
 at com.google.android.gms.common.api.internal.zzs.zzc(Unknown Source)
 at com.google.android.gms.common.api.internal.zzs.setResult(Unknown Source)
 at com.google.android.gms.location.places.zzm.zzao(Unknown Source)
 at com.google.android.gms.location.places.internal.zzx.onTransact(Unknown Source)
 at android.os.Binder.execTransact(Binder.java:573)
</code>```

I didn't change anything. Would anyone know what could be the possible reason why this isn't working?

My activity:

```<code>package com.example.currentplacedetailsonmap;

import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.GeoDataClient;
import com.google.android.gms.location.places.PlaceDetectionClient;
import com.google.android.gms.location.places.PlaceLikelihood;
import com.google.android.gms.location.places.PlaceLikelihoodBufferResponse;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;

/**
 * An activity that displays a map showing the place at the device's current location.
 */
public class MapsActivityCurrentPlace extends AppCompatActivity
        implements OnMapReadyCallback {

    private static final String TAG = MapsActivityCurrentPlace.class.getSimpleName();
    private GoogleMap mMap;
    private CameraPosition mCameraPosition;

    // The entry points to the Places API.
    private GeoDataClient mGeoDataClient;
    private PlaceDetectionClient mPlaceDetectionClient;

    // The entry point to the Fused Location Provider.
    private FusedLocationProviderClient mFusedLocationProviderClient;

    // A default location (Sydney, Australia) and default zoom to use when location permission is
    // not granted.
    private final LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085);
    private static final int DEFAULT_ZOOM = 15;
    private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
    private boolean mLocationPermissionGranted;

    // The geographical location where the device is currently located. That is, the last-known
    // location retrieved by the Fused Location Provider.
    private Location mLastKnownLocation;

    // Keys for storing activity state.
    private static final String KEY_CAMERA_POSITION = "camera_position";
    private static final String KEY_LOCATION = "location";

    // Used for selecting the current place.
    private static final int M_MAX_ENTRIES = 5;
    private String[] mLikelyPlaceNames;
    private String[] mLikelyPlaceAddresses;
    private String[] mLikelyPlaceAttributions;
    private LatLng[] mLikelyPlaceLatLngs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Retrieve location and camera position from saved instance state.
        if (savedInstanceState != null) {
            mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
            mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
        }

        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps);

        // Construct a GeoDataClient.
        mGeoDataClient = Places.getGeoDataClient(this, null);

        // Construct a PlaceDetectionClient.
        mPlaceDetectionClient = Places.getPlaceDetectionClient(this, null);

        // Construct a FusedLocationProviderClient.
        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        // Build the map.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

    }

    /**
     * Saves the state of the map when the activity is paused.
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (mMap != null) {
            outState.putParcelable(KEY_CAMERA_POSITION, mMap.getCameraPosition());
            outState.putParcelable(KEY_LOCATION, mLastKnownLocation);
            super.onSaveInstanceState(outState);
        }
    }

    /**
     * Sets up the options menu.
     * @param menu The options menu.
     * @return Boolean.
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.current_place_menu, menu);
        return true;
    }

    /**
     * Handles a click on the menu option to get a place.
     * @param item The menu item to handle.
     * @return Boolean.
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.option_get_place) {
            showCurrentPlace();
        }
        return true;
    }

    /**
     * Manipulates the map when it's available.
     * This callback is triggered when the map is ready to be used.
     */
    @Override
    public void onMapReady(GoogleMap map) {
        mMap = map;

        // Use a custom info window adapter to handle multiple lines of text in the
        // info window contents.
        mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

            @Override
            // Return null here, so that getInfoContents() is called next.
            public View getInfoWindow(Marker arg0) {
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {
                // Inflate the layouts for the info window, title and snippet.
                View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_contents,
                        (FrameLayout) findViewById(R.id.map), false);

                TextView title = ((TextView) infoWindow.findViewById(R.id.title));
                title.setText(marker.getTitle());

                TextView snippet = ((TextView) infoWindow.findViewById(R.id.snippet));
                snippet.setText(marker.getSnippet());

                return infoWindow;
            }
        });

        // Prompt the user for permission.
        getLocationPermission();

        // Turn on the My Location layer and the related control on the map.
        updateLocationUI();

        // Get the current location of the device and set the position of the map.
        getDeviceLocation();
    }

    /**
     * Gets the current location of the device, and positions the map's camera.
     */
    private void getDeviceLocation() {
        /*
         * Get the best and most recent location of the device, which may be null in rare
         * cases when a location is not available.
         */
        try {
            if (mLocationPermissionGranted) {
                Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
                locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
                    @Override
                    public void onComplete(@NonNull Task<Location> task) {
                        if (task.isSuccessful()) {
                            // Set the map's camera position to the current location of the device.
                            mLastKnownLocation = task.getResult();
                            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                                    new LatLng(mLastKnownLocation.getLatitude(),
                                            mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
                        } else {
                            Log.d(TAG, "Current location is null. Using defaults.");
                            Log.e(TAG, "Exception: %s", task.getException());
                            mMap.moveCamera(CameraUpdateFactory
                                    .newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
                            mMap.getUiSettings().setMyLocationButtonEnabled(false);
                        }
                    }
                });
            }
        } catch (SecurityException e)  {
            Log.e("Exception: %s", e.getMessage());
        }
    }

    /**
     * Prompts the user for permission to use the device location.
     */
    private void getLocationPermission() {
        /*
         * Request location permission, so that we can get the location of the
         * device. The result of the permission request is handled by a callback,
         * onRequestPermissionsResult.
         */
        if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
                android.Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mLocationPermissionGranted = true;
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                    PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
        }
    }

    /**
     * Handles the result of the request for location permissions.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        mLocationPermissionGranted = false;
        switch (requestCode) {
            case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mLocationPermissionGranted = true;
                }
            }
        }
        updateLocationUI();
    }

    /**
     * Prompts the user to select the current place from a list of likely places, and shows the
     * current place on the map - provided the user has granted location permission.
     */
    private void showCurrentPlace() {
        if (mMap == null) {
            return;
        }

        if (mLocationPermissionGranted) {
            // Get the likely places - that is, the businesses and other points of interest that
            // are the best match for the device's current location.
            @SuppressWarnings("MissingPermission") final
            Task<PlaceLikelihoodBufferResponse> placeResult =
                    mPlaceDetectionClient.getCurrentPlace(null);
            placeResult.addOnCompleteListener
                    (new OnCompleteListener<PlaceLikelihoodBufferResponse>() {
                        @Override
                        public void onComplete(@NonNull Task<PlaceLikelihoodBufferResponse> task) {
                            if (task.isSuccessful() && task.getResult() != null) {
                                PlaceLikelihoodBufferResponse likelyPlaces = task.getResult();

                                // Set the count, handling cases where less than 5 entries are returned.
                                int count;
                                if (likelyPlaces.getCount() < M_MAX_ENTRIES) {
                                    count = likelyPlaces.getCount();
                                } else {
                                    count = M_MAX_ENTRIES;
                                }

                                int i = 0;
                                mLikelyPlaceNames = new String[count];
                                mLikelyPlaceAddresses = new String[count];
                                mLikelyPlaceAttributions = new String[count];
                                mLikelyPlaceLatLngs = new LatLng[count];

                                for (PlaceLikelihood placeLikelihood : likelyPlaces) {
                                    // Build a list of likely places to show the user.
                                    mLikelyPlaceNames[i] = (String) placeLikelihood.getPlace().getName();
                                    mLikelyPlaceAddresses[i] = (String) placeLikelihood.getPlace()
                                            .getAddress();
                                    mLikelyPlaceAttributions[i] = (String) placeLikelihood.getPlace()
                                            .getAttributions();
                                    mLikelyPlaceLatLngs[i] = placeLikelihood.getPlace().getLatLng();

                                    i++;
                                    if (i > (count - 1)) {
                                        break;
                                    }
                                }

                                // Release the place likelihood buffer, to avoid memory leaks.
                                likelyPlaces.release();

                                // Show a dialog offering the user the list of likely places, and add a
                                // marker at the selected place.
                                openPlacesDialog();

                            } else {
                                Log.e(TAG, "Exception: %s", task.getException());
                            }
                        }
                    });
        } else {
            // The user has not granted permission.
            Log.i(TAG, "The user did not grant location permission.");

            // Add a default marker, because the user hasn't selected a place.
            mMap.addMarker(new MarkerOptions()
                    .title(getString(R.string.default_info_title))
                    .position(mDefaultLocation)
                    .snippet(getString(R.string.default_info_snippet)));

            // Prompt the user for permission.
            getLocationPermission();
        }
    }

    /**
     * Displays a form allowing the user to select a place from a list of likely places.
     */
    private void openPlacesDialog() {
        // Ask the user to choose the place where they are now.
        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // The "which" argument contains the position of the selected item.
                LatLng markerLatLng = mLikelyPlaceLatLngs[which];
                String markerSnippet = mLikelyPlaceAddresses[which];
                if (mLikelyPlaceAttributions[which] != null) {
                    markerSnippet = markerSnippet + "\n" + mLikelyPlaceAttributions[which];
                }

                // Add a marker for the selected place, with an info window
                // showing information about that place.
                mMap.addMarker(new MarkerOptions()
                        .title(mLikelyPlaceNames[which])
                        .position(markerLatLng)
                        .snippet(markerSnippet));

                // Position the map's camera at the location of the marker.
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(markerLatLng,
                        DEFAULT_ZOOM));
            }
        };

        // Display the dialog.
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle(R.string.pick_place)
                .setItems(mLikelyPlaceNames, listener)
                .show();
    }

    /**
     * Updates the map's UI settings based on whether the user has granted location permission.
     */
    private void updateLocationUI() {
        if (mMap == null) {
            return;
        }
        try {
            if (mLocationPermissionGranted) {
                mMap.setMyLocationEnabled(true);
                mMap.getUiSettings().setMyLocationButtonEnabled(true);
            } else {
                mMap.setMyLocationEnabled(false);
                mMap.getUiSettings().setMyLocationButtonEnabled(false);
                mLastKnownLocation = null;
                getLocationPermission();
            }
        } catch (SecurityException e)  {
            Log.e("Exception: %s", e.getMessage());
        }
    }
}
</code>```

My Build Gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.example.currentplacedetailsonmap"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        resValue "string", "google_maps_key", (project.findProperty("GOOGLE_MAPS_API_KEY") ?: "")
    }
    buildTypes {
        debug {
            debuggable true
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    compile 'com.google.android.gms:play-services:11.2.0'
    testCompile 'junit:junit:4.12'
}
</code>```

ANDROID VERSION: -> 7.0

答: I had the same problem. Maybe I had found a solution. The problem is com.google.android.geo.API_KEY in your AndroidManifest.xml. The key should support Google Maps Android API and Google Places API for Android. You can check the key on the https://console.developers.google.com/apis

Body:
I have just cloned the whole android-samples library and tried to run the CurrentPlaceDetailsOnMap project. I have done all the instructions given to me including creating my own API. However, everytime I just clicked Get Place (this triggers onOptionsItemSelected method then it triggers showCurrentPlace on the Activity), I get this error:

E/MapsActivityCurrentPlace: Exception: %s
 com.google.android.gms.common.api.ApiException: 13: ERROR
 at com.google.android.gms.common.internal.zzb.zzx(Unknown Source)
 at com.google.android.gms.common.internal.zzbj.zzy(Unknown Source)
 at com.google.android.gms.common.internal.zzbk.zzp(Unknown Source)
 at com.google.android.gms.common.api.internal.zzs.zzc(Unknown Source)
 at com.google.android.gms.common.api.internal.zzs.setResult(Unknown Source)
 at com.google.android.gms.location.places.zzm.zzao(Unknown Source)
 at com.google.android.gms.location.places.internal.zzx.onTransact(Unknown Source)
 at android.os.Binder.execTransact(Binder.java:573)

I didn't change anything. Would anyone know what could be the possible reason why this isn't working?

My activity:

package com.example.currentplacedetailsonmap;

import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.GeoDataClient;
import com.google.android.gms.location.places.PlaceDetectionClient;
import com.google.android.gms.location.places.PlaceLikelihood;
import com.google.android.gms.location.places.PlaceLikelihoodBufferResponse;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;

/**
 * An activity that displays a map showing the place at the device's current location.
 */
public class MapsActivityCurrentPlace extends AppCompatActivity
        implements OnMapReadyCallback {

    private static final String TAG = MapsActivityCurrentPlace.class.getSimpleName();
    private GoogleMap mMap;
    private CameraPosition mCameraPosition;

    // The entry points to the Places API.
    private GeoDataClient mGeoDataClient;
    private PlaceDetectionClient mPlaceDetectionClient;

    // The entry point to the Fused Location Provider.
    private FusedLocationProviderClient mFusedLocationProviderClient;

    // A default location (Sydney, Australia) and default zoom to use when location permission is
    // not granted.
    private final LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085);
    private static final int DEFAULT_ZOOM = 15;
    private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
    private boolean mLocationPermissionGranted;

    // The geographical location where the device is currently located. That is, the last-known
    // location retrieved by the Fused Location Provider.
    private Location mLastKnownLocation;

    // Keys for storing activity state.
    private static final String KEY_CAMERA_POSITION = "camera_position";
    private static final String KEY_LOCATION = "location";

    // Used for selecting the current place.
    private static final int M_MAX_ENTRIES = 5;
    private String[] mLikelyPlaceNames;
    private String[] mLikelyPlaceAddresses;
    private String[] mLikelyPlaceAttributions;
    private LatLng[] mLikelyPlaceLatLngs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Retrieve location and camera position from saved instance state.
        if (savedInstanceState != null) {
            mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
            mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
        }

        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_maps);

        // Construct a GeoDataClient.
        mGeoDataClient = Places.getGeoDataClient(this, null);

        // Construct a PlaceDetectionClient.
        mPlaceDetectionClient = Places.getPlaceDetectionClient(this, null);

        // Construct a FusedLocationProviderClient.
        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        // Build the map.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

    }

    /**
     * Saves the state of the map when the activity is paused.
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (mMap != null) {
            outState.putParcelable(KEY_CAMERA_POSITION, mMap.getCameraPosition());
            outState.putParcelable(KEY_LOCATION, mLastKnownLocation);
            super.onSaveInstanceState(outState);
        }
    }

    /**
     * Sets up the options menu.
     * @param menu The options menu.
     * @return Boolean.
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.current_place_menu, menu);
        return true;
    }

    /**
     * Handles a click on the menu option to get a place.
     * @param item The menu item to handle.
     * @return Boolean.
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.option_get_place) {
            showCurrentPlace();
        }
        return true;
    }

    /**
     * Manipulates the map when it's available.
     * This callback is triggered when the map is ready to be used.
     */
    @Override
    public void onMapReady(GoogleMap map) {
        mMap = map;

        // Use a custom info window adapter to handle multiple lines of text in the
        // info window contents.
        mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

            @Override
            // Return null here, so that getInfoContents() is called next.
            public View getInfoWindow(Marker arg0) {
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {
                // Inflate the layouts for the info window, title and snippet.
                View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_contents,
                        (FrameLayout) findViewById(R.id.map), false);

                TextView title = ((TextView) infoWindow.findViewById(R.id.title));
                title.setText(marker.getTitle());

                TextView snippet = ((TextView) infoWindow.findViewById(R.id.snippet));
                snippet.setText(marker.getSnippet());

                return infoWindow;
            }
        });

        // Prompt the user for permission.
        getLocationPermission();

        // Turn on the My Location layer and the related control on the map.
        updateLocationUI();

        // Get the current location of the device and set the position of the map.
        getDeviceLocation();
    }

    /**
     * Gets the current location of the device, and positions the map's camera.
     */
    private void getDeviceLocation() {
        /*
         * Get the best and most recent location of the device, which may be null in rare
         * cases when a location is not available.
         */
        try {
            if (mLocationPermissionGranted) {
                Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
                locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
                    @Override
                    public void onComplete(@NonNull Task<Location> task) {
                        if (task.isSuccessful()) {
                            // Set the map's camera position to the current location of the device.
                            mLastKnownLocation = task.getResult();
                            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                                    new LatLng(mLastKnownLocation.getLatitude(),
                                            mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
                        } else {
                            Log.d(TAG, "Current location is null. Using defaults.");
                            Log.e(TAG, "Exception: %s", task.getException());
                            mMap.moveCamera(CameraUpdateFactory
                                    .newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
                            mMap.getUiSettings().setMyLocationButtonEnabled(false);
                        }
                    }
                });
            }
        } catch (SecurityException e)  {
            Log.e("Exception: %s", e.getMessage());
        }
    }

    /**
     * Prompts the user for permission to use the device location.
     */
    private void getLocationPermission() {
        /*
         * Request location permission, so that we can get the location of the
         * device. The result of the permission request is handled by a callback,
         * onRequestPermissionsResult.
         */
        if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
                android.Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mLocationPermissionGranted = true;
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                    PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
        }
    }

    /**
     * Handles the result of the request for location permissions.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        mLocationPermissionGranted = false;
        switch (requestCode) {
            case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mLocationPermissionGranted = true;
                }
            }
        }
        updateLocationUI();
    }

    /**
     * Prompts the user to select the current place from a list of likely places, and shows the
     * current place on the map - provided the user has granted location permission.
     */
    private void showCurrentPlace() {
        if (mMap == null) {
            return;
        }

        if (mLocationPermissionGranted) {
            // Get the likely places - that is, the businesses and other points of interest that
            // are the best match for the device's current location.
            @SuppressWarnings("MissingPermission") final
            Task<PlaceLikelihoodBufferResponse> placeResult =
                    mPlaceDetectionClient.getCurrentPlace(null);
            placeResult.addOnCompleteListener
                    (new OnCompleteListener<PlaceLikelihoodBufferResponse>() {
                        @Override
                        public void onComplete(@NonNull Task<PlaceLikelihoodBufferResponse> task) {
                            if (task.isSuccessful() && task.getResult() != null) {
                                PlaceLikelihoodBufferResponse likelyPlaces = task.getResult();

                                // Set the count, handling cases where less than 5 entries are returned.
                                int count;
                                if (likelyPlaces.getCount() < M_MAX_ENTRIES) {
                                    count = likelyPlaces.getCount();
                                } else {
                                    count = M_MAX_ENTRIES;
                                }

                                int i = 0;
                                mLikelyPlaceNames = new String[count];
                                mLikelyPlaceAddresses = new String[count];
                                mLikelyPlaceAttributions = new String[count];
                                mLikelyPlaceLatLngs = new LatLng[count];

                                for (PlaceLikelihood placeLikelihood : likelyPlaces) {
                                    // Build a list of likely places to show the user.
                                    mLikelyPlaceNames[i] = (String) placeLikelihood.getPlace().getName();
                                    mLikelyPlaceAddresses[i] = (String) placeLikelihood.getPlace()
                                            .getAddress();
                                    mLikelyPlaceAttributions[i] = (String) placeLikelihood.getPlace()
                                            .getAttributions();
                                    mLikelyPlaceLatLngs[i] = placeLikelihood.getPlace().getLatLng();

                                    i++;
                                    if (i > (count - 1)) {
                                        break;
                                    }
                                }

                                // Release the place likelihood buffer, to avoid memory leaks.
                                likelyPlaces.release();

                                // Show a dialog offering the user the list of likely places, and add a
                                // marker at the selected place.
                                openPlacesDialog();

                            } else {
                                Log.e(TAG, "Exception: %s", task.getException());
                            }
                        }
                    });
        } else {
            // The user has not granted permission.
            Log.i(TAG, "The user did not grant location permission.");

            // Add a default marker, because the user hasn't selected a place.
            mMap.addMarker(new MarkerOptions()
                    .title(getString(R.string.default_info_title))
                    .position(mDefaultLocation)
                    .snippet(getString(R.string.default_info_snippet)));

            // Prompt the user for permission.
            getLocationPermission();
        }
    }

    /**
     * Displays a form allowing the user to select a place from a list of likely places.
     */
    private void openPlacesDialog() {
        // Ask the user to choose the place where they are now.
        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // The "which" argument contains the position of the selected item.
                LatLng markerLatLng = mLikelyPlaceLatLngs[which];
                String markerSnippet = mLikelyPlaceAddresses[which];
                if (mLikelyPlaceAttributions[which] != null) {
                    markerSnippet = markerSnippet + "\n" + mLikelyPlaceAttributions[which];
                }

                // Add a marker for the selected place, with an info window
                // showing information about that place.
                mMap.addMarker(new MarkerOptions()
                        .title(mLikelyPlaceNames[which])
                        .position(markerLatLng)
                        .snippet(markerSnippet));

                // Position the map's camera at the location of the marker.
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(markerLatLng,
                        DEFAULT_ZOOM));
            }
        };

        // Display the dialog.
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle(R.string.pick_place)
                .setItems(mLikelyPlaceNames, listener)
                .show();
    }

    /**
     * Updates the map's UI settings based on whether the user has granted location permission.
     */
    private void updateLocationUI() {
        if (mMap == null) {
            return;
        }
        try {
            if (mLocationPermissionGranted) {
                mMap.setMyLocationEnabled(true);
                mMap.getUiSettings().setMyLocationButtonEnabled(true);
            } else {
                mMap.setMyLocationEnabled(false);
                mMap.getUiSettings().setMyLocationButtonEnabled(false);
                mLastKnownLocation = null;
                getLocationPermission();
            }
        } catch (SecurityException e)  {
            Log.e("Exception: %s", e.getMessage());
        }
    }
}

My Build Gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.example.currentplacedetailsonmap"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        resValue "string", "google_maps_key", (project.findProperty("GOOGLE_MAPS_API_KEY") ?: "")
    }
    buildTypes {
        debug {
            debuggable true
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    compile 'com.google.android.gms:play-services:11.2.0'
    testCompile 'junit:junit:4.12'
}

ANDROID VERSION: -> 7.0


问:
Structural design patterns: (Private class data) Is there a difference between these two examples
The following is an example of this pattern from sourcemaking.com:

https://sourcemaking.com/design_patterns/private_class_data

There are two examples, the crossed out main class and the main class that contains the data class.

My question is simply what is the difference between the following and the given correct implementation at the link:

```<code>public class MainClass {

    private final <Type> attribute1;
    private final <Type> attribute2;
    private final <Type> attribute3;

    public MainClass(<Type> attribute1, <Type> attribute2, <Type> attribute3 {
        this.attribute1 = attribute1;
        this.attribute2 = attribute2;
        this.attribute3 = attribute3;
    }
}
</code>```

Cheers

答:
Your code here is not an example of that pattern. The crossed out model is what not to do.

You need a separate Java object to hold the attributes, and that page lists exactly why the pattern exists - to limit exposure of fields

And since this point

Main class must initialize data class through the data class's constructor

The data object can be declared as final

Body:
The following is an example of this pattern from sourcemaking.com:

https://sourcemaking.com/design_patterns/private_class_data

There are two examples, the crossed out main class and the main class that contains the data class.

My question is simply what is the difference between the following and the given correct implementation at the link:

public class MainClass {

    private final <Type> attribute1;
    private final <Type> attribute2;
    private final <Type> attribute3;

    public MainClass(<Type> attribute1, <Type> attribute2, <Type> attribute3 {
        this.attribute1 = attribute1;
        this.attribute2 = attribute2;
        this.attribute3 = attribute3;
    }
}

Cheers


问:
Automatically redraw a highStock chart under Angularjs
I want to make a highStock chart under AngularJS, and I want to change some chart option by some buttons. However, it seems that changing the option does not redraw the chart automatically. I tried to follow a thread which works with highChart, but I cannot make the directive work with highStock. Here is a plunker, the watch is well triggered, whereas I don't know how redraw the chart well.

```<code>  .directive('highchart', function($parse, $timeout) {
    return {
      restrict: 'E',
      template: '<div></div>',
      replace: true,
      link: function(scope, element, attrs) {
        var config = $parse(attrs.config)(scope);
        Highcharts.stockChart(element[0], config);

        scope.$watch(attrs.watch, function(newVal) {
          if (newVal) {
            console.log("here" + JSON.stringify(newVal))
            $timeout(function() {
              Highcharts.stockChart(element[0], config);
            }, 0);
          }
        });
      }
    }
  })
</code>```

Could anyone help?

答:
For updating already rendered chart you need to use functions from this section of the API: https://api.highcharts.com/class-reference/classes.list (Chart.update(), Series.addPoint() etc.).

Your example with update function: https://plnkr.co/edit/X1LnekXUX0WrodQFCqMp?p=preview

```<code>    $scope.chooseUnit = function (unit) {
      $scope.chart.series[0].update({
        dataGrouping: {
          units: [[unit.name, [1]]]
        }
      });
      $scope.unitSelected = unit
    }
</code>```

Body:
I want to make a highStock chart under AngularJS, and I want to change some chart option by some buttons. However, it seems that changing the option does not redraw the chart automatically. I tried to follow a thread which works with highChart, but I cannot make the directive work with highStock. Here is a plunker, the watch is well triggered, whereas I don't know how redraw the chart well.

  .directive('highchart', function($parse, $timeout) {
    return {
      restrict: 'E',
      template: '

',
      replace: true,
      link: function(scope, element, attrs) {
        var config = $parse(attrs.config)(scope);
        Highcharts.stockChart(element[0], config);

        scope.$watch(attrs.watch, function(newVal) {
          if (newVal) {
            console.log("here" + JSON.stringify(newVal))
            $timeout(function() {
              Highcharts.stockChart(element[0], config);
            }, 0);
          }
        });
      }
    }
  })

Could anyone help?

Body:
For updating already rendered chart you need to use functions from this section of the API: https://api.highcharts.com/class-reference/classes.list (Chart.update(), Series.addPoint() etc.).

Your example with update function: https://plnkr.co/edit/X1LnekXUX0WrodQFCqMp?p=preview

    $scope.chooseUnit = function (unit) {
      $scope.chart.series[0].update({
        dataGrouping: {
          units: [[unit.name, [1]]]
        }
      });
      $scope.unitSelected = unit
    }


问:
Pandas reshape columns to time-series rows
I have a pandas dataframe (unhappily with duplicates...)

```<code>Date        Partner   Value
2017-02-01  Partner1  150
2017-03-01  Partner1  170
2017-02-01  Partner2  160
2017-03-01  Partner2  185
2017-02-01  Partner1  40
2017-03-01  Partner1  90
</code>```

Which I want to reshape by partners, looking like this:

```<code>Partner    2017-02-01   2017-03-01
Partner1   150          170
Partner2   160          185
Partner1   40           90
</code>```

How would I go about this?

答:
Actually, I found the answer I needed:</p>

```<code>series = pd.pivot_table(data, values="Value", index="Partner", columns="Date")
</code>```

Body:
I have a pandas dataframe (unhappily with duplicates...)

Date        Partner   Value
2017-02-01  Partner1  150
2017-03-01  Partner1  170
2017-02-01  Partner2  160
2017-03-01  Partner2  185
2017-02-01  Partner1  40
2017-03-01  Partner1  90

Which I want to reshape by partners, looking like this:

Partner    2017-02-01   2017-03-01
Partner1   150          170
Partner2   160          185
Partner1   40           90

How would I go about this?

Body:
Actually, I found the answer I needed:

series = pd.pivot_table(data, values="Value", index="Partner", columns="Date")