Calling Multiple Layouts in One Activity on 2 diff

2019-08-06 12:36发布

问题:

what am doing is that am initializing a layout on the start of my activity. Whenever a button on that layout is clicked am initializing another layout in the same activity. Whenever i click the am doing some working regarding insertion of a database record. even on ignoring the database part am getting java null pointer exception in logcat. Kindly have a look and guide me

package com.example.emp_management;

import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.SyncStateContract.Columns;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.emp_management.DatabaseHelper;

public class Administrator_Work extends Activity{

@Override
protected void onCreate(Bundle adminkakaam) {
    // TODO Auto-generated method stub

    super.onCreate(adminkakaam);
    setContentView(R.layout.administrator);
    Toast.makeText(this, "Logged in as Administrator!",Toast.LENGTH_LONG).show();
    final EditText new_user = (EditText) findViewById(R.id.editText1);
    final EditText new_pass = (EditText) findViewById(R.id.textView2);
    Button add_emp = (Button)findViewById(R.id.addemployee);
    final Button create_acc = (Button) findViewById(R.id.creat_acc);
    add_emp.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub 
            setContentView(R.layout.add_employee);
            create_acc.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    //DatabaseHelper accessing_db = new DatabaseHelper(Administrator_Work.this);
                    //accessing_db.insert_new_user(new_user.getText().toString(), new_pass.getText().toString());
                    //Toast.makeText(getApplicationContext(), "New User Has Been Created!!", Toast.LENGTH_SHORT).show();

                }
            });
        }
    });

}

}

回答1:

Calling setContentView multiple times is not recommended. I would advise you to use different fragments for your application, or at least have the first layout contain all the views you need and hide/show them according to your needs. If you insist on using different layouts for the same activity then you could have a look here.