当SetContentView设置回主活动时,应用程序崩溃

时间:2017-02-25 12:48:51

标签: java android android-studio

当我在另一个布局上设置内容视图时,它可以很好地工作,但是当我将内容视图设置回主布局时,它会崩溃。

我的主要课程及其中的一切。一切都发生在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 个答案:

答案 0 :(得分:1)

进行更改

D/cocos2d-x debug info: {
                            gl.supports_OES_packed_depth_stencil: true
                            gl.supports_vertex_array_object: false
                            gl.supports_BGRA8888: false
                            gl.supports_ATITC: false
                            gl.supports_S3TC: false
                            cocos2d.x.version: cocos2d-x-3.14.1
                            gl.supports_discard_framebuffer: false
                            cocos2d.x.compiled_with_profiler: false
                            gl.supports_PVRTC: false
                            cocos2d.x.build_type: DEBUG
                            gl.renderer: Android Emulator OpenGL ES Translator (NVIDIA GeForce 9400M OpenGL Engine)
                            gl.supports_OES_depth24: true
                            gl.supports_ETC1: true
                            gl.supports_OES_map_buffer: false
                            cocos2d.x.compiled_with_gl_state_cache: true
                            gl.version: OpenGL ES 2.0 (2.1 NVIDIA-10.0.51 310.90.10.05b12)
                            gl.supports_NPOT: true
                            gl.max_texture_units: 16
                            gl.vendor: Google (NVIDIA Corporation)
                            gl.max_texture_size: 8192
                        }
D/cocos2d-x debug info: create rendererRecreatedListener for GLProgramState
D/cocos2d-x debug info: create rendererRecreatedListener for GLProgramState
D/cocos2d-x debug info: create rendererRecreatedListener for GLProgramState
D/cocos2d-x debug info: create rendererRecreatedListener for GLProgramState
A/libc: Fatal signal 11 (SIGSEGV) at 0x00000000 (code=128), thread 1352 (Thread-88)