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

Apps error: class MainActivity is already defined in package

ericosman

Lurker
Hi,

I'm busy to create my fist app at this moment, and i ran into an issue.
When i try to compile my code i get "error: class MainActivity is already defined in package "
I read on the internet i should remove one line that does that and combine the rest of the code.
Now is there one problem i cant figure out.
My first line says
public class MainActivity extends AppCompatActivity
and the line that makes the code not work says:
public class MainActivity extends AppCompatActivity { <---- it has a bracket

So i tryed to remove the bracket and other stuff but i could get it to work, it there something i dont see?

This is the full code :


JavaScript:
package com.prosen.myweb;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.view.KeyEvent;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;




public class MainActivity extends AppCompatActivity

        implements NavigationView.OnNavigationItemSelectedListener {

    private WebView wv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

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

        wv = (WebView) findViewById(R.id.webView1);
        WebSettings settings = wv.getSettings();
        settings.setJavaScriptEnabled(true);

        wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        wv.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        wv.getSettings().setAppCacheEnabled(true);
        wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        settings.setDomStorageEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        settings.setUseWideViewPort(true);
        settings.setSavePassword(true);
        settings.setSaveFormData(true);

        wv.loadUrl("http://websitelink1");
      wv.setWebViewClient(new MywebViewClient());

    }

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




    public class MainActivity extends AppCompatActivity {

        private static  String url = "http://websitelink2/paperVersion.json";
        String VersionUpdate;

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


            new VersionCheck().execute();
        }


        private class VersionCheck extends AsyncTask<Void, Void, Void> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();


            }

            @Override
            protected Void doInBackground(Void... arg0) {
                HttpHandler sh = new HttpHandler();


                String jsonStr = sh.makeServiceCall(url);

                if (jsonStr != null){
                    try {
                        JSONObject jsonObj = new JSONObject(jsonStr);
                        JSONArray version = jsonObj.getJSONArray("Version");
                        for (int i = 0; i < version.length(); i++){

                            JSONObject v = version.getJSONObject(i);

                            VersionUpdate = v.getString("version");
                        }



                    }catch (final JSONException e) {
                        // Log.e(TAG, "Json parsing error: " + e.getMessage());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(),
                                        "Json parsing error: " + e.getMessage(),
                                        Toast.LENGTH_LONG)
                                        .show();
                            }
                        });

                    }
                } else {
                    //Log.e(TAG, "Couldn't get json from server.");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Couldn't get json from server. Check LogCat for possible errors!",
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }


                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);


                String VersionName = BuildConfig.VERSION_NAME;


                if (VersionUpdate.equals(VersionName)){

                    //Do Nothing
                }else {

                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("Our App got Update");
                    builder.setIcon(R.mipmap.ic_launcher);
                    builder.setCancelable(false);
                    builder.setMessage("New version available, select update to update our app")
                            .setPositiveButton("UPDATE", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    final String appName = getPackageName();

                                    try {
                                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appName)));
                                    } catch (android.content.ActivityNotFoundException anfe) {
                                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appName)));
                                    }

                                    finish();

                                }
                            });

                    AlertDialog alert = builder.create();
                    alert.show();


                }


            }
        }
    }





    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_belknop) {
            /////////////////BELKNOP//////////////
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "0000000000"));
            startActivity(intent);






        } else if (id == R.id.nav_meting) {
            wv.loadUrl("http://websitelink1");

        } else if (id == R.id.nav_handleiding) {
            wv.loadUrl("http://websitelink2/");


        } else if (id == R.id.nav_contact) {
            wv.loadUrl("http://websitelink2");


        }

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

    private class MywebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (Uri.parse(url).getHost().endsWith("link2.nl")){

                return false;
            }


            if (Uri.parse(url).getHost().endsWith("link1.nl")){

                return false;

            }


            else {

                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

                startActivity(intent);

                return true;

            }
        }


    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getAction()== KeyEvent.ACTION_DOWN){

            switch(keyCode){
                case KeyEvent.KEYCODE_BACK:

                    if(wv.canGoBack()){

                        wv.goBack();
                    }

                    else{

                        finish();
                    }

                    return true;
            }
        }

        return super.onKeyDown(keyCode, event);
    }



}


Is there anyone who can help me with the code ? :-)
Thanks in advance
 
You're getting this error because you've defined two classes called MainActivity in the same file.
Java doesn't allow duplicate class names. You need to decide which class definition is correct, and delete the other one.
The two class declarations are -

Code:
public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

and

Code:
public class MainActivity extends AppCompatActivity {
 
Hi,

Thanks, i read it as 2 lines :)

Now i have the following line to fail:
protected void onCreate(Bundle savedInstanceState) {

Do i also have to combine them?

I combined them:

JavaScript:
 private WebView wv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //////////////////////////////////////////////////////
        new VersionCheck().execute();
        /////////////////////////////////////////////////////
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

But now the app crashes

I put the "added code" in between the ///////////////






What i try to add is a version check, if there is an update it will popup in the app.
I use this code:
http://androidmkab.com/2017/05/24/show-update-dialog-android-application/
 
Last edited:
Back
Top Bottom