2015-07-06 4 views
-1

Я знаю, что этот вопрос задан снова и снова, но на него не ответили, и я искал часы, пытаясь понять это, но приложение, над которым я работаю, интегрирует Google карты. Он использует боковой навигационный ящик, который выдвигается, и вы можете выбрать фрагменты, которые затем переключают представление. Сказано, что у меня есть все библиотеки, необходимые для этого приложения, чтобы функционировать, он компилируется и строит правильно, но всякий раз, когда я нажимаю на фрагмент, в котором находится приложение, он выходит из строя. Итак, вот мои файлы.Закрытие приложения Google Maps - Android Studio

MainActivity.java -

package com.raziel.android.publictoilet; 

import android.app.Activity; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentManager; 
import android.support.v4.widget.DrawerLayout; 
import android.support.v7.app.ActionBar; 
import android.support.v7.app.ActionBarActivity; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ViewGroup; 


public class MainActivity extends ActionBarActivity 
    implements NavigationDrawerFragment.NavigationDrawerCallbacks { 

/** 
* Fragment managing the behaviors, interactions and presentation of the navigation drawer. 
*/ 
private NavigationDrawerFragment mNavigationDrawerFragment; 

/** 
* Used to store the last screen title. For use in {@link #restoreActionBar()}. 
*/ 
private CharSequence mTitle; 

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

    mNavigationDrawerFragment = (NavigationDrawerFragment) 
      getSupportFragmentManager().findFragmentById(R.id.navigation_drawer); 
    mTitle = getTitle(); 

    // Set up the drawer. 
    mNavigationDrawerFragment.setUp(
      R.id.navigation_drawer, 
      (DrawerLayout) findViewById(R.id.drawer_layout)); 

} 


@Override 
public void onNavigationDrawerItemSelected(int position) { 

    //Switches the Fragmentx.java 

    Fragment fragment; 
    switch (position){ 
     case 1: 
      fragment = FirstFragment.newInstance(position + 1); 
      break; 
     case 2: 
      fragment = SecondFragment.newInstance(position + 1); 
      break; 
     case 3: 
      fragment = ThirdFragment.newInstance(position + 1); 
      break; 

    } 

    // update the main content by replacing fragments 
    FragmentManager fragmentManager = getSupportFragmentManager(); 
    fragmentManager.beginTransaction() 
      .replace(R.id.container, PlaceholderFragment.newInstance(position + 1)) 
      .commit(); 
} 

public void onSectionAttached(int number) { 
    switch (number) { 
     case 1: 
      mTitle = getString(R.string.title_section1); 

      break; 
     case 2: 
      mTitle = getString(R.string.title_section2); 
      break; 
     case 3: 
      mTitle = getString(R.string.title_section3); 
      break; 
     case 4: 
      mTitle = getString(R.string.title_section4); 
      break; 
    } 
} 





public void restoreActionBar() { 
    ActionBar actionBar = getSupportActionBar(); 
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); 
    actionBar.setDisplayShowTitleEnabled(true); 
    actionBar.setTitle(mTitle); 
} 


@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    if (!mNavigationDrawerFragment.isDrawerOpen()) { 
     // Only show items in the action bar relevant to this screen 
     // if the drawer is not showing. Otherwise, let the drawer 
     // decide what to show in the action bar. 
     getMenuInflater().inflate(R.menu.main, menu); 
     restoreActionBar(); 
     return true; 
    } 
    return super.onCreateOptionsMenu(menu); 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

/** 
* A placeholder fragment containing a simple view. 
*/ 
public static class PlaceholderFragment extends Fragment { 
    /** 
    * The fragment argument representing the section number for this 
    * fragment. 
    */ 
    private static final String ARG_SECTION_NUMBER = "section_number"; 

    /** 
    * Returns a new instance of this fragment for the given section 
    * number. 
    */ 
    public static PlaceholderFragment newInstance(int sectionNumber) { 
     PlaceholderFragment fragment = new PlaceholderFragment(); 
     Bundle args = new Bundle(); 
     args.putInt(ARG_SECTION_NUMBER, sectionNumber); 
     fragment.setArguments(args); 
     return fragment; 
    } 

    public PlaceholderFragment() { 
    } 


    //Switches views and inflates fragments in container 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     View rootView = null; 
     rootView = inflater.inflate(R.layout.fragment_main, container, false); 
     switch(getArguments().getInt(ARG_SECTION_NUMBER)) { 
      case 1: 
       rootView = inflater.inflate(R.layout.fragment_main, container, false); 
       break; 
      case 2: 
       rootView = inflater.inflate(R.layout.map, container, false); 
       break; 
      case 3: 
       rootView = inflater.inflate(R.layout.submittoilet, container, false); 
       break; 
      case 4: 
       //rootView = inflater.inflate(R.layout.fragment_info, container, false); 
       break; 
     } 
     return rootView; 
    } 

    @Override 
    public void onAttach(Activity activity) { 
     super.onAttach(activity); 
     ((MainActivity) activity).onSectionAttached(
       getArguments().getInt(ARG_SECTION_NUMBER)); 
     } 
    } 

} 

map.java - Это держит acutal «код карты» это потому, что с раскладкой стороны под MainActivity расширяет ActionBarActivity ... NavigationDrawerCallbacks он не может реализовать две функции обратного вызова , package com.raziel.android.publictoilet;

import android.app.Activity; 
import android.os.Bundle; 

import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.MapFragment; 
import com.google.android.gms.maps.OnMapReadyCallback; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.MarkerOptions; 

public class map extends Activity implements OnMapReadyCallback { 

// Used to call the map and inflate fragment in container 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.map); 

    MapFragment mapFragment = (MapFragment) getFragmentManager() 
      .findFragmentById(R.id.the_map); 
    mapFragment.getMapAsync(this); 
} 

@Override 
public void onMapReady(GoogleMap map) { 
    LatLng sydney = new LatLng(-33.867, 151.206); 

    map.setMyLocationEnabled(true); 
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13)); 

    map.addMarker(new MarkerOptions() 
      .title("Sydney") 
      .snippet("The most populous city in Australia.") 
      .position(sydney)); 
    } 
} 

Теперь есть секции сбоку. Все с ярлыками и такой тот, который держит карту называют map.xml -

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
      xmlns:tools="http://schemas.android.com/tools" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:paddingRight="@dimen/activity_horizontal_margin" 
      android:paddingTop="@dimen/activity_vertical_margin" 
      android:paddingBottom="@dimen/activity_vertical_margin" 
      tools:context=".MainActivity$PlaceholderFragment"> 



<fragment xmlns:android="http://schemas.android.com/apk/res/android" 
      android:name="com.google.android.gms.maps.SupportMapFragment" 
      android:id="@+id/the_map" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      /> 

</RelativeLayout> 

Вот мой файл AndroidManifest.xml. Это содержит все необходимые части, которые могут потребоваться для моего картографического приложения, такого как мой API_KEY, который включен.

AndroidManifest.xml -

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.raziel.android.publictoilet" 
android:versionCode="1" 
android:versionName="1.0" > 

<uses-sdk 
    android:minSdkVersion="14" 
    android:targetSdkVersion="22" /> 

<!-- Include required permissions for Google Mobile Ads to run --> 
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 

<uses-feature 
    android:glEsVersion="0x00020000" 
    android:required="true" /> 

<android:uses-permission 
    android:name="android.permission.READ_EXTERNAL_STORAGE" 
    android:maxSdkVersion="18" /> 

<uses-permission android:name="android.permission.GET_ACCOUNTS" /> 
<uses-permission android:name="android.permission.USE_CREDENTIALS" /> 

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

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 

    <meta-data 
     android:name="com.raziel.android.publictoilet.API_KEY" 
     android:value="AIzaSyAD8T-3hzTjWAJEuM4jQoUd-wj7IC6k2sc" /> 
    <meta-data 
     android:name="com.raziel.android.publictoilet.gms.version" 
     android:value="@integer/google_play_services_version" /> 
    <!-- Include the AdActivity and InAppPurchaseActivity configChanges and themes. --> 
    <activity 
     android:name="com.google.android.gms.ads.AdActivity" 
     android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" 
     android:theme="@android:style/Theme.Translucent" /> 
    <activity 
     android:name="com.google.android.gms.ads.purchase.InAppPurchaseActivity" 
     android:theme="@style/Theme.IAPTheme" /> 

    <meta-data 
     android:name="com.google.android.gms.version" 
     android:value="@integer/google_play_services_version" /> 
    <meta-data 
     android:name="com.google.android.gms.wallet.api.enabled" 
     android:value="true" /> 

    <receiver 
     android:name="com.google.android.gms.wallet.EnableWalletOptimizationReceiver" 
     android:exported="false" > 
     <intent-filter> 
      <action android:name="com.google.android.gms.wallet.ENABLE_WALLET_OPTIMIZATION" /> 
     </intent-filter> 
    </receiver> 
</application> 

LogCat показывает, что это вызвано:

Caused by: java.lang.RuntimeException: API key not found. Check that <meta-data android:name="com.google.android.geo.API_KEY" android:value="your API key"/> is in the <application> element of AndroidManifest.xml 

Но дело в том, что я не могу изменить файл AndroidManifest.xml, чтобы это исправить потому что он автоматически восстанавливает каждую сборку! И, как вы можете ясно видеть, это в AndroidManifest.xml. Я попытался сделать его доступным только для чтения, но тогда он просто компилируется навсегда, не выдавая никаких ошибок. Кто-нибудь может помочь. Опять же, это в Android Studio.

ответ

0

Nevermind Я исправил его. Приложение создало файл AndroidManifest.xml, и я пытался его отредактировать. Это было неправильно. Правильный находится в app/src/main, и я добавил к этому свой ключ. Спасибо парню, который проголосовал за меня, очень полезный.

Смежные вопросы