2017-02-25 6 views
-3

別のレイアウトでコンテンツビューを設定すると、コンテンツビューが完全に動作しますが、コンテンツビューをメインレイアウトに戻すとクラッシュします。SetContentViewをメインアクティビティに戻したときにアプリケーションがクラッシュする

My Mainクラスとそのすべてが含まれています。すべてがpublic void firstTime()で起こります。

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { 

    private MapFragment mapsFragment; 
    static MainActivity can; 
    static FloatingActionButton fab; 
    static FloatingActionButton show; 
    private String encoded_string; 
    private Bitmap bitmap; 
    private String picturePath; 
    /** 
    * ATTENTION: This was auto-generated to implement the App Indexing API. 
    * See https://g.co/AppIndexing/AndroidStudio for more information. 
    */ 
    private GoogleApiClient client; 

    private void initializeMapsFragment() { 
     FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction(); 
     mapsFragment = new MapFragment(); 
     SupportMapFragment supportMapFragment = mapsFragment; 
     mTransaction.add(R.id.map, supportMapFragment); 
     mTransaction.commit(); 
    } 

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

     Log.d("--***** MAP ", "::Loading Map"); 
     can = this; 
     setContentView(R.layout.activity_main); 
     initializeMapsFragment(); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 
     fab = (FloatingActionButton) findViewById(R.id.fab); 
     show = (FloatingActionButton) findViewById(R.id.show); 
     show.hide(); 
     fab.hide(); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       callPopup(); 

      } 
     }); 

     show.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       stats(); 

      } 
     }); 

     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
       this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
     drawer.setDrawerListener(toggle); 
     toggle.syncState(); 


     NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
     navigationView.setNavigationItemSelectedListener(this); 

     Button searchButton = (Button) findViewById(R.id.searchButton); 

     searchButton.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 

       EditText searchView = (EditText) findViewById(R.id.searchView1); 
       String text = searchView.getText().toString(); 

       Geocoder geocoder = new Geocoder(getBaseContext()); 
       List<Address> addresses = null; 

       try { 
        // Getting a maximum of 3 Address that matches the input 
        // text 
        addresses = geocoder.getFromLocationName(text, 3); 
        if (addresses != null && !addresses.equals("")) 
         search(addresses); 

       } catch (Exception e) { 

       } 

      } 
     }); 

     client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); 
    } 


    protected void search(List<Address> addresses) { 

     Address address = (Address) addresses.get(0); 
     LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude()); 

     MapFragment.mapView.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
     MapFragment.mapView.animateCamera(CameraUpdateFactory.zoomTo(15)); 


    } 

    @Override 
    public void onBackPressed() { 
     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     if (drawer.isDrawerOpen(GravityCompat.START)) { 
      drawer.closeDrawer(GravityCompat.START); 
     } else { 
      super.onBackPressed(); 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

    @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); 
    } 

    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB) 
    @SuppressWarnings("StatementWithEmptyBody") 
    @Override 
    public boolean onNavigationItemSelected(MenuItem item) { 
     FragmentManager fm = getFragmentManager(); 
     android.support.v4.app.FragmentManager sFm = getSupportFragmentManager(); 

     int id = item.getItemId(); 


     if (id == R.id.nav_camera) { 

      if (!mapsFragment.isAdded()) 
       sFm.beginTransaction().add(R.id.map, mapsFragment).commit(); 
      else 
       sFm.beginTransaction().show(mapsFragment).commit(); 
     } else if (id == R.id.nav_share) { 

      Intent sharingIntent = new Intent(Intent.ACTION_SEND); 
      sharingIntent.setType("text/plain"); 
      String shareBody = "Check this app out --> link.kys"; 
      sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Best Free Parking app"); 
      sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody); 
      startActivity(Intent.createChooser(sharingIntent, "Share via")); 

     } else if (id == R.id.nav_send) { 

     } 

     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     drawer.closeDrawer(GravityCompat.START); 
     return true; 
    } 

    public void firstTime() { 


     setContentView(R.layout.firsttime); 

     (findViewById(R.id.cancelBut)) 
       .setOnClickListener(new View.OnClickListener() { 

        public void onClick(View arg0) { 

         setContentView(R.layout.activity_main); 
        } 

       }); 


    } 

    public static void load(){ 

     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(can); 
     if (!prefs.getBoolean("firstTime", false)) { 

      can.firstTime(); 

      //SharedPreferences.Editor editor = prefs.edit(); 
      //editor.putBoolean("firstTime", true); 
      //editor.commit(); 
     } 

    } 

    private void stats() { 

     setContentView(R.layout.stats); 



     RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingBar); 
     ratingbar.setRating((float) 2.0); 
     ratingbar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() { 
      public void onRatingChanged(RatingBar ratingBar, float rating, 
             boolean fromUser) { 

       ratingBar.setRating((float) 2.0); 

      } 
     }); 


     ((Button) findViewById(R.id.cancBut)).setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       setContentView(R.layout.content_main); 
      } 
     }); 
    } 

    private void callPopup() { 


     final PopupWindow popupWindow; 

     LayoutInflater layoutInflater = (LayoutInflater) getBaseContext() 
       .getSystemService(LAYOUT_INFLATER_SERVICE); 

     View popupView = layoutInflater.inflate(R.layout.popup, null); 

     popupWindow = new PopupWindow(popupView, 
       DrawerLayout.LayoutParams.WRAP_CONTENT, DrawerLayout.LayoutParams.MATCH_PARENT, 
       true); 

     popupWindow.setTouchable(true); 
     popupWindow.setFocusable(true); 

     popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0); 
     final EditText name = (EditText) popupView.findViewById(R.id.edtimageName); 

     ((Button) popupView.findViewById(R.id.plcBut)).setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       selectPhoto(); 
      } 
     }); 

     ((Button) popupView.findViewById(R.id.saveBtn)) 
       .setOnClickListener(new View.OnClickListener() { 

        @TargetApi(Build.VERSION_CODES.GINGERBREAD) 
        public void onClick(View arg0) { 
         new Encode_image().execute(); 
         popupWindow.dismiss(); 

        } 

       }); 

     ((Button) popupView.findViewById(R.id.cancelbtutton)) 
       .setOnClickListener(new View.OnClickListener() { 

        public void onClick(View arg0) { 

         popupWindow.dismiss(); 
        } 
       }); 


    } 


    private void selectPhoto() { 

     Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); 
     photoPickerIntent.setType("image/*"); 
     startActivityForResult(photoPickerIntent, 10); 

    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

     if (requestCode == 10 && resultCode == RESULT_OK) { 

      Uri selectedImage = data.getData(); 

      String[] filePathColumn = {MediaStore.Images.Media.DATA}; 
      Cursor cursor = getContentResolver().query(selectedImage, 
        filePathColumn, null, null, null); 
      cursor.moveToFirst(); 

      int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
      picturePath = cursor.getString(columnIndex); 
      cursor.close(); 
     } 
    } 

    /** 
    * ATTENTION: This was auto-generated to implement the App Indexing API. 
    * See https://g.co/AppIndexing/AndroidStudio for more information. 
    */ 
    public Action getIndexApiAction() { 
     Thing object = new Thing.Builder() 
       .setName("Main Page") // TODO: Define a title for the content shown. 
       // TODO: Make sure this auto-generated URL is correct. 
       .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]")) 
       .build(); 
     return new Action.Builder(Action.TYPE_VIEW) 
       .setObject(object) 
       .setActionStatus(Action.STATUS_TYPE_COMPLETED) 
       .build(); 
    } 

    @Override 
    public void onStart() { 
     super.onStart(); 

     // ATTENTION: This was auto-generated to implement the App Indexing API. 
     // See https://g.co/AppIndexing/AndroidStudio for more information. 
     client.connect(); 
     AppIndex.AppIndexApi.start(client, getIndexApiAction()); 
    } 

    @Override 
    public void onStop() { 
     super.onStop(); 

     // ATTENTION: This was auto-generated to implement the App Indexing API. 
     // See https://g.co/AppIndexing/AndroidStudio for more information. 
     AppIndex.AppIndexApi.end(client, getIndexApiAction()); 
     client.disconnect(); 
    } 

    private class Encode_image extends AsyncTask<Void, Void, Void> { 
     @Override 
     protected Void doInBackground(Void... voids) { 

      bitmap = BitmapFactory.decodeFile(picturePath); 
      ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); 
      bitmap.recycle(); 

      byte[] array = stream.toByteArray(); 
      encoded_string = Base64.encodeToString(array, 0); 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void aVoid) { 
      makeRequest(); 
     } 
    } 

    private void makeRequest() { 
     RequestQueue requestQueue = Volley.newRequestQueue(this); 
     StringRequest request = new StringRequest(Request.Method.POST, "http://185.80.129.86/upload.php", 
       new Response.Listener<String>() { 
        @Override 
        public void onResponse(String response) { 

        } 
       }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 

      } 
     }) { 
      @Override 
      protected Map<String, String> getParams() throws AuthFailureError { 
       HashMap<String, String> map = new HashMap<>(); 
       map.put("encoded_string", encoded_string); 
       map.put("image_name", "testing123.jpg"); 

       return map; 
      } 
     }; 
     requestQueue.add(request); 
    } 
} 

エラー:

E/AndroidRuntime: FATAL EXCEPTION: main 
       Process: com.robertas.parking.bestfreeparking, PID: 3501 
       java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 
        at android.view.ViewGroup.addViewInner(ViewGroup.java:3936) 
        at android.view.ViewGroup.addView(ViewGroup.java:3786) 
        at android.view.ViewGroup.addView(ViewGroup.java:3758) 
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:810) 
        at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916) 
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:802) 
        at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916) 
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:802) 
        at android.view.LayoutInflater.inflate(LayoutInflater.java:504) 
        at android.view.LayoutInflater.inflate(LayoutInflater.java:414) 
        at android.view.LayoutInflater.inflate(LayoutInflater.java:365) 
        at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284) 
        at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143) 
        at com.robertas.parking.bestfreeparking.MainActivity$4.onClick(MainActivity.java:245) 
        at android.view.View.performClick(View.java:4780) 
        at android.view.View$PerformClick.run(View.java:19866) 
        at android.os.Handler.handleCallback(Handler.java:739) 
        at android.os.Handler.dispatchMessage(Handler.java:95) 
        at android.os.Looper.loop(Looper.java:135) 
        at android.app.ActivityThread.main(ActivityThread.java:5254) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at java.lang.reflect.Method.invoke(Method.java:372) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

答えて

1

メイクはこれが

Log.d("--***** MAP ", "::Loading Map"); 
can = this; 
setContentView(R.layout.activity_main); 
initializeMapsFragment(); 
+0

だから私は削除する必要が変更されます。 することができます=この; – TerZer

+0

can = thisを削除する必要はありません。 –

+0

置き換えられましたが、それでも動作しません、エラーを追加しました。 – TerZer

関連する問題