• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Application crashes when SetContentView set back to main activity

TerZer

Lurker
When I set content view on another layout its works perfectly, but when I set content view back to main layout its crashes.

My main class:

Java:
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;
    View rootView;
    /**
     * 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();
    }

    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        can = this;
        Log.d("--***** MAP  ", "::Loading Map");
        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(
                can, 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(can);

        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(can).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));


    }

    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    @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) {

                        //View view = can.findViewById(android.R.id.content);
                        //Log.d("a", "" + ((ViewGroup)view).getChildCount() );
                        //((ViewGroup) view).removeView(view);
                        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);
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
    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();
    }

    @RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
    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);
    }
}

Error:

Java:
    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)
 
Your stack trace doesn't match up with the line numbers you're showing in the code. This makes it hard to know what's going on. Line 245 shown in the stack trace doesn't correspond to a setContentView() in your code.
 
Your stack trace doesn't match up with the line numbers you're showing in the code. This makes it hard to know what's going on. Line 245 shown in the stack trace doesn't correspond to a setContentView() in your code.
I haven't added all imports. It happens in void firstTime() and line is:
Java:
setContentView(R.layout.activity_main);
I think it's because of Fragment, but I'm not really sure. :/
 
So.. I figure that the problem is to remove fragment then calling SetContentView();
But not there is another problem.
Error:
Code:
Binary XML file line #12: Error inflating class fragment
 
Back
Top Bottom