When I click a button it goes to another activity instead of the activity I wanted it to [closed]

I made an app that whenever i click the button it goes to another activity. Instead of going to another activity where i want it to, it just goes to an activity that is a replicate of the activity itself. I’ve kinda been tinkering with the AndroidManifest.xml with the guide of Logcat so maybe the problem is in the AndroidManifest.xml but i dont know how to solve it.

MainActivity.java

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import androidx.core.app.ActivityCompat;
import androidx.appcompat.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.ajts.androidmads.library.SQLiteToExcel;
import com.example.DraftApp2.activity.ScanTab;
import com.example.DraftApp2.util.Utils;

import java.io.File;


import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
SQLiteToExcel sqliteToExcel;
String directory_path = Environment.getExternalStorageDirectory().getPath() + "/Attendance/";
private static final String TAG = "MainActivity";
EditText editName,editSurename,edittMarks;
Button btnAddData;
Button btnviewAll;
Button btn_export;
Button btn_scan;
TextView txtlast;
Button btn_share;
Button btn_delete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myDb=new DatabaseHelper(getApplicationContext());
        myDb = new DatabaseHelper(getApplicationContext());
        editName=(EditText)findViewById(R.id.editText_name);
        editSurename=(EditText)findViewById(R.id.editText_surename);
        edittMarks=(EditText)findViewById(R.id.editText_marks);
        btnAddData=(Button)findViewById(R.id.button_add);
        btnviewAll=(Button)findViewById(R.id.txt_last);
        btn_export=(Button)findViewById(R.id.btn_export);
        btn_delete=(Button)findViewById(R.id.btn_delete);
        btn_scan=(Button)findViewById(R.id.button_scan);
        txtlast=findViewById(R.id.textView);
        btn_share=findViewById(R.id.btn_share);

        AddData();
        ViewAll();

        getSupportActionBar().setTitle("SQLite Database to Excel ");// set title of Main activity

        //permission for file READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE
        try {

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // this will request for permission from the user if not yet granted
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            } else {
                // Download code here
                System.out.println("NOt ok");
            }
        }catch (Exception e){
            System.out.println(e);
        }

        File file = new File(directory_path);   //check if there any file in this directory path
        if (!file.exists()) {
            file.mkdirs();
        }

        //delete ALL data
 btn_delete.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
        Integer deleteRows=myDb.deleteData();  //delete ALL DATA IN database table
        Toast.makeText(MainActivity.this,"Delete all database table data",Toast.LENGTH_LONG).show();

     }
 });
        //sharing
btn_share.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        try {

            String filelocation= Environment.getExternalStorageDirectory().getPath() + "/Attendance/student.xls";
            Intent intent = new Intent(Intent.ACTION_SENDTO);
            intent.setType("text/plain");
            String message="File to be shared is .";
            intent.putExtra(Intent.EXTRA_SUBJECT, "Students REPORT");
            intent.putExtra(Intent.EXTRA_STREAM, Uri.parse( "file://"+filelocation));
            intent.putExtra(Intent.EXTRA_TEXT, message);
            intent.setData(Uri.parse("mailto:[email protected]"));   //insert your email address("mailto:[email protected]")
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            startActivity(intent);
        } catch(Exception e)  {
            System.out.println("is exception raises during sending mail"+e);
        }
    }
});

   btn_export.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(final View view) {

           // Export SQLite DB as EXCEL FILE
           sqliteToExcel = new SQLiteToExcel(getApplicationContext(), DatabaseHelper.DATABASE_NAME, directory_path);
           sqliteToExcel.exportAllTables("student.xls", new SQLiteToExcel.ExportListener() {
               @Override
               public void onStart() {

               }

               @Override
               public void onCompleted(String filePath) {
                 Utils.showSnackBar(view, "Successfully Exported");
                  // Toast.makeText(MainActivity.this, "Export successful!", Toast.LENGTH_SHORT).show();
               }

               @Override
               public void onError(Exception e) {
                   e.printStackTrace();
                   //Toast.makeText(MainActivity.this, "No Export", Toast.LENGTH_SHORT).show();
                   Utils.showSnackBar(view, "Not Exported");
               }
           });


       }
   });

    btn_scan.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent startIntent = new Intent(getApplicationContext(), ScanTab.class);
            startActivity(startIntent);
        }
    });

    }
public void AddData(){
        btnAddData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd 'at' HH:mm:ss");
                String currentDateandTime = sdf.format(new Date());

             boolean isInserted= myDb.insertData(editName.getText().toString(),editSurename.getText().toString(),edittMarks.getText().toString());

           if (isInserted=true){
               Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();

           }else {
               Toast.makeText(MainActivity.this,"Data Not Inserted",Toast.LENGTH_LONG).show();
           }
            }
        });

}

public void ViewAll(){
        btnviewAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             Cursor res=myDb.getAllData();
             if(res.getCount()==0){                     //when there is no data show message..error message is depend on  "showMessage"method
                 //show message
                 showMessage("Error","Nothing Found");
                 return;

             }
             StringBuffer buffer=new StringBuffer();

                 while(res.moveToNext()){                                               //read and collect data in database in coloum
                    // buffer.append("ID :"+ res.getString(0)+"n");
                     buffer.append("Date :"+ res.getString(1)+"n");
                     buffer.append("Values :"+ res.getString(2)+"n");
                    buffer.append("Marks :"+ res.getString(3)+"nn");
                  //   buffer.append("Date :"+ res.getString(4)+"nn");


                 }
                 //show all data
                 showMessage("Data of Database",buffer.toString());                  //show all data in list.list is depnd on  "showMessage"method
             }


        });


}
public void showMessage(String title,String Message){                   //show message method
    AlertDialog.Builder builder=new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(Message);
    builder.show();

}

}

ScanTab.java

import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.Settings;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.DraftApp2.R;
import com.example.DraftApp2.parser.NdefMessageParser;
import com.example.DraftApp2.record.ParsedNdefRecord;

import java.util.List;

public class ScanTab extends AppCompatActivity {

    private NfcAdapter nfcAdapter;
    private PendingIntent pendingIntent;
    private TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (TextView) findViewById(R.id.text);
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);

        if (nfcAdapter == null) {
            Toast.makeText(this, "No NFC", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        pendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, this.getClass())
                        .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (nfcAdapter != null) {
            if (!nfcAdapter.isEnabled())
                showWirelessSettings();

            nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (nfcAdapter != null){
            nfcAdapter.disableForegroundDispatch(this);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        resolveIntent(intent);
    }

    private void resolveIntent(Intent intent) {
        String action = intent.getAction();

        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs;

            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];

                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }

            } else {
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                byte[] payload = dumpTagData(tag).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
                msgs = new NdefMessage[] {msg};
            }

            displayMsgs(msgs);
        }
    }

    private void displayMsgs(NdefMessage[] msgs) {
        if (msgs == null || msgs.length == 0)
            return;

        StringBuilder builder = new StringBuilder();
        List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
        final int size = records.size();

        for (int i = 0; i < size; i++) {
            ParsedNdefRecord record = records.get(i);
            String str = record.str();
            builder.append(str).append("n");
        }

        text.setText(builder.toString());
        Toast.makeText(this, "NFC Tag Detected", Toast.LENGTH_SHORT).show();
    }

    private void showWirelessSettings() {
        Toast.makeText(this, "You need to enable NFC", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
        startActivity(intent);
    }

    private String dumpTagData(Tag tag) {
        StringBuilder sb = new StringBuilder();
        byte[] id = tag.getId();
        sb.append("ID (hex): ").append(toHex(id)).append('n');
        sb.append("ID (reversed hex): ").append(toReversedHex(id)).append('n');
        sb.append("ID (dec): ").append(toDec(id)).append('n');
        sb.append("ID (reversed dec): ").append(toReversedDec(id)).append('n');

        String prefix = "android.nfc.tech.";
        sb.append("Technologies: ");
        for (String tech : tag.getTechList()) {
            sb.append(tech.substring(prefix.length()));
            sb.append(", ");
        }

        sb.delete(sb.length() - 2, sb.length());

        for (String tech : tag.getTechList()) {
            if (tech.equals(MifareClassic.class.getName())) {
                sb.append('n');
                String type = "Unknown";

                try {
                    MifareClassic mifareTag = MifareClassic.get(tag);

                    switch (mifareTag.getType()) {
                        case MifareClassic.TYPE_CLASSIC:
                            type = "Classic";
                            break;
                        case MifareClassic.TYPE_PLUS:
                            type = "Plus";
                            break;
                        case MifareClassic.TYPE_PRO:
                            type = "Pro";
                            break;
                    }
                    sb.append("Mifare Classic type: ");
                    sb.append(type);
                    sb.append('n');

                    sb.append("Mifare size: ");
                    sb.append(mifareTag.getSize() + " bytes");
                    sb.append('n');

                    sb.append("Mifare sectors: ");
                    sb.append(mifareTag.getSectorCount());
                    sb.append('n');

                    sb.append("Mifare blocks: ");
                    sb.append(mifareTag.getBlockCount());
                } catch (Exception e) {
                    sb.append("Mifare classic error: " + e.getMessage());
                }
            }

            if (tech.equals(MifareUltralight.class.getName())) {
                sb.append('n');
                MifareUltralight mifareUlTag = MifareUltralight.get(tag);
                String type = "Unknown";
                switch (mifareUlTag.getType()) {
                    case MifareUltralight.TYPE_ULTRALIGHT:
                        type = "Ultralight";
                        break;
                    case MifareUltralight.TYPE_ULTRALIGHT_C:
                        type = "Ultralight C";
                        break;
                }
                sb.append("Mifare Ultralight type: ");
                sb.append(type);
            }
        }

        return sb.toString();
    }

    private String toHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = bytes.length - 1; i >= 0; --i) {
            int b = bytes[i] & 0xff;
            if (b < 0x10)
                sb.append('0');
            sb.append(Integer.toHexString(b));
            if (i > 0) {
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    private String toReversedHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; ++i) {
            if (i > 0) {
                sb.append(" ");
            }
            int b = bytes[i] & 0xff;
            if (b < 0x10)
                sb.append('0');
            sb.append(Integer.toHexString(b));
        }
        return sb.toString();
    }

    private long toDec(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = 0; i < bytes.length; ++i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;
    }

    private long toReversedDec(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = bytes.length - 1; i >= 0; --i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;


    }
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.DraftApp2">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.NFC" />
    <uses-feature android:name="android.hardware.nfc" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:replace="android:appComponentFactory"
        android:appComponentFactory="@string/app_name">

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

            <intent-filter>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>
                <data android:scheme="http"
                    android:host="com.example.draftapp2"
                    android:pathPrefix="/cv"/>
                <data android:scheme="cv"
                    android:host="hello"/>
            </intent-filter>
        </activity>

        <activity android:name=".activity.ScanTab">
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE"/>
                <data android:scheme="http"
                    android:host="com.example.draftapp2.activity"
                    android:pathPrefix="/cv"/>
                <data android:scheme="cv"
                    android:host="hello"/>
            </intent-filter>
        </activity>

    </application>

</manifest>

Answer

You didn’t specify which button click intent you’re having problem,but beside this what I really noticed you using same layout activity_main in both your Activity class which are MainActivity and ScanTab (please use “Activity” while defining activity class,its suppose to be ScanTabActivity) in setContentView()

Leave a Reply

Your email address will not be published. Required fields are marked *