I have problem.
I made method which creates Dialog with my own layout. And I have no idea how to pass values (Strings) from my EdiText and asing to any variable in my Activity.
In comments you can see how I was trying to solve this.
Java method
public void makeDialog(){
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_ip);
dialog.setTitle("IP connection");
// Todo passing value from dialog to activity
// final EditText ipValueConnection = (EditText)findViewById(R.id.ipValueConnection);
// ipValueConnection.setOnClickListener(this);
// EditText portValueConnection = (EditText)findViewById(R.id.portValueConnection);
// Toast.makeText(context, ipValueConnection.getText().toString(), Toast.LENGTH_LONG).show();
Button dialogButtonLogin = (Button) dialog.findViewById(R.id.dialogButtonLogin);
// if button is clicked, close the custom dialog
dialogButtonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tryToConnect();
dialog.dismiss();
}
});
// set the custom dialog components - text, image and button
// TextView text = (TextView) dialog.findViewById(R.id.IP);
dialog.show();
}
XML layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:src="#drawable/antena"
android:layout_width="220dp"
android:layout_height="120dp"
android:scaleType="centerInside"
android:background="#FFFFBB33"
android:contentDescription="#string/app_name"
android:adjustViewBounds="true"
/>
<EditText
android:id="#+id/ipValueConnection"
android:inputType="textEmailAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="IP" />
<EditText
android:id="#+id/portValueConnection"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="16dp"
android:fontFamily="sans-serif"
android:hint="PORT"/>
<Button
android:id="#+id/dialogButtonLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:layout_marginTop="5dp"
/>
</LinearLayout>
Create a interface
public interface OnClickInterface {
public void onClick();
}
call it instantiate it in your activity onCreate()
OnClickInterface onClickInterface = new OnClickInterface() {
#Override
public void onClick() {
//Call Method from here
requiredMethod();
}
};
//And in your dialog classs or method
public void makeDialog(OnClickInterface onClickInterface){
//Your code
dialogButtonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClickInterface.onClick();
dialog.dismiss();
}
});
}
The error you are getting means that a reference to the editText cannot be found in the current layout file. You have find the EditText in the custom dialog view instead of the activity view.
So instead of:
final EditText ipValueConnection =(EditText)findViewById(R.id.ipValueConnection);
use:
final EditText ipValueConnection =(EditText)dialog.findViewById(R.id.ipValueConnection);
If i have understood your question correctly,
your edit text is in dialog_ip so you need to use
final EditText ipValueConnection = (EditText) dialog.findViewById(R.id.ipValueConnection);
Then you can get text from edit text as
String text= ipValueConnection.getText().toString;
And use that variable in your activity.
Related
I created a simple activity that is intended to send two pieces of information to another activity. However, my button isn't registering any click events. Does anyone have any idea why this would be? I expected that by adding the onClick = "onClickWrite" to the XML file that they would be linked but there is no response when clicked. If anyone could help me out, I would greatly appreciate it. I have tried implementing the onClickListener, however, with that implementation, it throws an error on my Toasts.
Activity
public class InitializeClass extends Activity {
private Service service;
private Button button;
EditText infoOne;
EditText infoTwo;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.button_control);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(clicked);
infoOne= (EditText) findViewById(R.id.editText);
infoTwo= (EditText) findViewById(R.id.editText1);
}
private View.OnClickListener clicked = new View.OnClickListener(){
#Override
public void onClick(View view) {
if (service != null) {
int size = 100;
byte[] byteArray = new byte[size];
byte[] byteArrayTwo = new byte[size];
byteArray = infoOne.getText().toString().getBytes(Charset.defaultCharset());
byteArrayTwo= infoTwo.getText().toString().getBytes(Charset.defaultCharset());
if ((!(infoOne.getText().toString().isEmpty())) && (!(infoTwo.getText().toString().isEmpty()))) {
service.setInfo(byteArray);
service.setInfoTwo(byteArrayTwo);
intentMethod();
}
}
}
};
public void intentMethod() {
Intent intent = new Intent(this, DeviceScanActivity.class);
startActivity(intent);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".InitializeClass">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="#string/send_info"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColor="#color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText1" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="150dp"
android:ems="10"
android:inputType="textPersonName"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColorHint="#android:color/white"
android:textCursorDrawable="#drawable/color_cursor"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="info"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColorHint="#android:color/white"
android:textCursorDrawable="#drawable/color_cursor"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText" />
</android.support.constraint.ConstraintLayout>
You need to initialize your button first.
Button button = (Button) findViewById(R.id.button);
Hope this helps!
In your activity class assign the button to the id of the button in the xml:
private Button btn = findViewById(R.id.button);
You will then create an OnClickListener:
private View.OnClickListener clicked = new View.OnClickListener(){
#Override
public void onClick(View view) {
//Insert Code here
}
};
In your onCreate method in the same activity class you will instantiate the button and assign the button to the onClickListener:
btn = new Button(this);
btn.setOnClickListener(clicked);
There are couple of things you need to do for that.
Create Field.
private Button button;
Initialize button.
Button button = (Button) findViewById(R.id.button);
Set Listener on button.
button.setOnClickListener();
I found the answer. Service in if (service != null) was never being initialized. Stupid mistake on my part. Thanks, everyone for the help and directing me in a way to implement onClickListener!
You need to cast the button (name) with you Java code .
for example on xml you have id/button (name)
declare it on your Java file, and do the casting.
and the onClickListener will look like this :
Cast the button : Button button ;
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
I have made a simple QR code scanner app with the help of ZXing.
now .. I followed a tutorial and it's all working very well .
except for this one thing, when i successfully scan a QR code it freezes or resumes scanning if I add this line : mScannerView.resumeCameraPreview(this);
But I need my app to go back to the firstscreen/homescreen and close the camera , because the result goes into the edittext boxes .But I cannot get this to work.
I have tried looking for answers , and all I could find is convert my app so it uses an intent to scan , but I do not get the process :(
So .. if there's anyone who could help me out with this it would be amazing.
im a beginner at java , but im thinking it cant be hard to just return from where I came from.
this is my one and only activity:
public class MainActivity extends Activity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.editText4);
EditText edittext;
button = findViewById(R.id.button3);
edittext = findViewById(R.id.editText2);
final EditText finalEdittext = edittext;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Clear EditText
finalEdittext.getText().clear();
}
});
button = findViewById(R.id.button4);
edittext = findViewById(editText4);
final EditText finalEdittext1 = edittext;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Clear EditText
finalEdittext1.getText().clear();
}
});
}
public void onClick(View v){
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
protected void onPause() {
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(Result result) {
//handle result
Log.v("handleResult", result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Ordernummer of Locatie");
builder.setMessage(result.getText());
AlertDialog alertDialog = builder.create();
alertDialog.show();
updateScannerData(1,result.getText());
//resume scanning
//mScannerView.resumeCameraPreview(this);
}
private void updateScannerData(int scanType, String scannedCode) {
editText.setText(scannedCode);
}
}
this is my xml :
<RelativeLayout
<Button
android:layout_width="218dp"
android:layout_height="wrap_content"
android:layout_below="#+id/editText4"
android:layout_centerHorizontal="true"
android:background="#android:color/holo_red_light"
android:onClick="onClick"
android:text="#string/scan_qr"
tools:text="scan qr code" />
<EditText
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="61dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="197dp"
android:ems="10"
android:hint="#string/scan_order"
android:inputType="textPersonName"
android:visibility="visible"
tools:backgroundTint="#android:color/holo_red_light" />
<EditText
android:id="#+id/editText4"
android:layout_width="match_parent"
android:layout_height="62dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="67dp"
android:ems="10"
android:hint="#string/scan_locatie"
android:inputType="textPersonName"
tools:backgroundTint="#android:color/holo_red_light" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="33dp"
android:background="#android:color/holo_red_light"
android:text="#string/button"
tools:text="Versturen.." />
<Button
android:id="#+id/button2"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:background="#android:color/holo_red_light"
android:onClick="onClick"
android:text="#string/scan_qr"
tools:text="scan qr code" />
<Button
android:id="#+id/button3"
android:layout_width="40dp"
android:layout_height="38dp"
android:layout_alignStart="#+id/button4"
android:layout_below="#+id/editText2"
android:layout_marginTop="10dp"
android:background="#android:drawable/ic_delete" />
<Button
android:id="#+id/button4"
android:layout_width="39dp"
android:layout_height="37dp"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="32dp"
android:layout_marginTop="136dp"
android:background="#android:drawable/ic_delete" />
</RelativeLayout>
im thinking of a bit of code like exit.mScannerview or something but i don't know .
I want to avoid using the intent solution , because I would need a step by step guide and its not found . Thank you all for those who try to help me out.
EDIT: by adding this code : startActivity(new Intent(this,MainActivity.class));
this.finish();
EDIT2 recreate() works also , but i need a value to be displayed and that gets reset with both methods , anyone knows a trick?
it works like i want , but only is my scan result not being put into edittext field , as coded in updatescannerdata function , HOW ?
So, I have also this problem.
I viewed another apps and how they do it. So, how I understand you have minimum two ways:
create new Activity( or some fragment and use it)
(myChoise) finish(); // Activity onClick
Intent intent = new Intent(getApplicationContext(), QR_Activity.class);
startActivity(intent);
finish();
Because I didn't find solve too. RemoveAllViews doesn't work correctly for me, display is frozen.
I have a ListView and a button i want when I press the button it takes me to a Dialogue it has a Text Field and another Button when I fill the text and press the button it will be saved in the list view ( I know how to add items from the same activity to the ListView) but I don't how to add items from another activity or AlterDialoge .
public class Main3Activity extends AppCompatActivity {
EditText et;
ListView lv;
Button bt;
ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
et = (EditText) findViewById(R.id.TextAdd);
bt = (Button) findViewById(R.id.btnadd);
lv = (ListView) findViewById(R.id.listView);
arrayList = new ArrayList<String>();
adapter= new ArrayAdapter<String>(Main3Activity.this,android.R.layout.simple_list_item_1,arrayList);
lv.setAdapter(adapter);
Button mShowDialog = (Button) findViewById(R.id.btnSave);
mShowDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(Main3Activity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_add,null);
final EditText mUser = (EditText) mView.findViewById(R.id.TextAdd);
Button mAdd = (Button) mView.findViewById(R.id.btnadd);
mAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!mUser.getText().toString().isEmpty()) {
String result = et.getText().toString();
arrayList.add(result);
adapter.notifyDataSetChanged();
Toast.makeText(Main3Activity.this, "Success", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(Main3Activity.this, "Error pls Write", Toast.LENGTH_SHORT).show();
}
}
});
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
}
});
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp">
<TextView
android:id="#+id/Add"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_margin="5dp"
android:textSize="25sp"
android:text="POP UP Window" />
<EditText
android:id="#+id/TextAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:layout_marginTop="10dp"
android:inputType="textPersonName"
android:hint="write"/>
<Button
android:id="#+id/btnadd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:textColor="#android:color/white"
android:text="Add" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.jim_a.testapp.Main3Activity"
tools:layout_editor_absoluteY="81dp"
tools:layout_editor_absoluteX="0dp">
<Button
android:id="#+id/btnSave"
android:layout_height="73dp"
android:text="Open Window"
android:layout_width="0dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="16dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
tools:layout_constraintRight_creator="1"
tools:layout_constraintLeft_creator="1" />
<ListView
android:id="#+id/listView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="13dp"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginEnd="13dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="33dp"
app:layout_constraintTop_toBottomOf="#+id/btnSave"
tools:layout_constraintLeft_creator="1"
android:layout_marginBottom="31dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginLeft="13dp"
android:layout_marginRight="13dp"></ListView>
</android.support.constraint.ConstraintLayout>
Okay so I made 2 minor modifications to get your code working -
Replace "et" with "mUser" to avoid Null Pointer Exception when calling getText()
Dismiss Dialog upon successful updation of list.
Below is the onClick() method body :
AlertDialog.Builder mBuilder = new AlertDialog.Builder(Main3Activity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_add, null);
final EditText editText_mUser = (EditText) mView.findViewById(R.id.TextAdd);
Button mAdd = (Button) mView.findViewById(R.id.btnadd);
mBuilder.setView(mView);
//create dialog instance here, so that it can be dismissed from within the OnClickListener callback
final AlertDialog dialog = mBuilder.create();
mAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!editText_mUser.getText().toString().isEmpty()) {
// Instead of et.getText(), call mUser.getText()
String result = editText_mUser.getText().toString();
arrayList.add(result);
adapter.notifyDataSetChanged();
Toast.makeText(Main3Activity.this, "Success", Toast.LENGTH_SHORT).show();
//dismiss dialog once item is added successfully
dialog.dismiss();
} else {
Toast.makeText(Main3Activity.this, "Error pls Write", Toast.LENGTH_SHORT).show();
}
}
});
dialog.show();
See this for more info.
For other cases, where you want communication between 2 Activities/Fragments for Event-Based List Updation, you can check out EventBus.
I am trying to create a custom dialog class with a custom layout, but, for reasons unknown to be, I am getting a null pointer exception when trying to access the buttons for the layout. Here is the XML for the dialog:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/enableTopRelativeLayout"
android:layout_width="460dp"
android:layout_height="wrap_content"
android:background="#drawable/dialog_background"
android:paddingBottom="15dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="15dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:src="#drawable/ic_launcher" />
<RelativeLayout
android:id="#+id/enableInnerRelativeLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/imageView1" >
<TextView
android:id="#+id/enableMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerInParent="false"
android:paddingBottom="10dp"
android:text="Start service?"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/enableStrut"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_below="#id/enableMessage"
android:layout_centerHorizontal="true"
android:text=" " />
<Button
android:id="#+id/noenable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/enableMessage"
android:layout_toLeftOf="#id/enableStrut"
android:background="#drawable/button_background"
android:text="No"
android:textColorLink="#color/color2"
android:textStyle="bold" />
<Button
android:id="#+id/enable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/enableMessage"
android:layout_toRightOf="#id/enableStrut"
android:background="#drawable/button_background"
android:text="Yes"
android:textColorLink="#color/color2"
android:textStyle="bold" />
</RelativeLayout>
Here is the code for the class:
public class DialogStartService extends Dialog implements android.view.View.OnClickListener{
public Button yes;
public Button no;
public TextView tv;
public DialogStartService(Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.start_service_layout);
getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
tv = (TextView) findViewById(R.id.enableMessage);
yes = (Button) findViewById(R.id.enable);
no = (Button) findViewById(R.id.noenable);
yes.setOnClickListener(this);
no.setOnClickListener(this);
}
#Override
public void onClick(View v) {
dismiss();
}
}
I instantiate the dialog with this code:
DialogStartService enableDialog = new DialogStartService(this);
Button enable = (Button) enableDialog.findViewById(R.id.enable);
enable.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Do stuff
}
});
Button noenable = (Button) enableDialog.findViewById(R.id.noenable);
noenable.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Do stuff
}
});
enableDialog.show();
The stack trace indicates the NPE occurs on this line:
enable.setOnClickListener(new OnClickListener() {
My question for the experts is... why is this code causing a NPE, and what is the best way to fix it? Thank you for any input you have.
According to documentation of findViewById() method:
Finds a child view with the given identifier. Returns null if the specified child view does not exist or the dialog has not yet been fully created (for example, via show() or create()).
In your code you call findViewById() before show() - that's why Button enable is null.
I am having an issue with a click listener for a login modal submit button.
This is the error.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
I have a reasonable understanding of what a null pointer exception is and I have search thoroughly for an issue similar to mine. I have tried to reformat the click listener in several ways, made sure I have the correct view ID etc.
package...
import...
public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks {
//Variables
String currentPage = "";
Stack<String> crumbs = new Stack<String>();
//Fragment managing the behaviors, interactions and presentation of the navigation drawer.
private NavigationDrawerFragment mNavigationDrawerFragment;
// Used to store the last screen title. For use in {#link #restoreActionBar()}.
public CharSequence mTitle;
//temp
AuthenticateUserTokenResult authenticateUserTokenResult;
String loginErrorMessage = "";
String loginErrorTitle = "";
Boolean logonSuccessful = false;
Dialog loginDialog;
// Login EditTexts
EditText Username;
EditText CompanyID;
EditText Password;
Button Submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle(); // Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));
if(authenticateUserTokenResult == null) {
attemptLogin();
}
}
public void attemptLogin() {
loginDialog = new Dialog(this,android.R.style.Theme_Translucent_NoTitleBar);
loginDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
loginDialog.setContentView(R.layout.login_modal);
loginDialog.setCancelable(false);
//loginDialog.setOnCancelListener(cancelListener);
loginDialog.show();
Submit = (Button)findViewById(R.id.Submit);
Submit.setOnClickListener(new View.OnClickListener() // the error is on this line (specifically the .setOnClickListener)
{
#Override
public void onClick(View v)
{
ClyxUserLogin user = new ClyxUserLogin();
Username = (EditText)findViewById(R.id.Username);
user.logon = Username.getText().toString();
CompanyID = (EditText)findViewById(R.id.CompanyID);
user.idCompany = Integer.parseInt(CompanyID.getText().toString());
Password = (EditText)findViewById(R.id.Password);
user.password = Password.getText().toString();
user.idApplication = 142;
authenticate(user);
}
});
}
There is more, obviously, but not relevant to the topic I think.
Here is the XML file for the dialog that has the button on it.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#3366FF">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#FFFFFF" >
<TextView
android:id="#+id/LoginTitle"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginTop="10dp"
android:layout_marginStart="10dp"
android:textColor="#000000"
android:textSize="20sp"
android:text="Login" />
<EditText
android:id="#+id/Username"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="#+id/LoginTitle"
android:layout_margin="10dp"
android:hint="Username" />
<EditText
android:id="#+id/CompanyID"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="#+id/Username"
android:layout_alignStart="#+id/Username"
android:inputType="number"
android:hint="Company ID" />
<EditText
android:id="#+id/Password"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="#+id/CompanyID"
android:layout_alignStart="#+id/Username"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:inputType="textPassword"
android:hint="Password" />
<Button
android:id="#+id/Submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Password"
android:layout_marginBottom="10dp"
android:layout_centerHorizontal="true"
android:text="Login" />
</RelativeLayout>
</RelativeLayout>
Any help would be greatly appreciated.
Submit is null because it is not part of activity_main.xml
When you call findViewById inside an Activity, it is going to look for a View inside your Activity's layout.
try this instead :
Submit = (Button)loginDialog.findViewById(R.id.Submit);
Another thing : you use
android:layout_below="#+id/LoginTitle"
but what you want is probably
android:layout_below="#id/LoginTitle"
See this question about the difference between #id and #+id.
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
Because Submit button is inside login_modal so you need to use loginDialog view to access button:
Submit = (Button)loginDialog.findViewById(R.id.Submit);
Try giving your Button in your main.xml a more descriptive name such as:
<Button
android:id="#+id/buttonXYZ"
(use lowercase in your xml files, at least, the first letter)
And then in your MainActivity class, declare it as:
Button buttonXYZ;
In your onCreate(Bundle savedInstanceState) method, define it as:
buttonXYZ = (Button) findViewById(R.id.buttonXYZ);
Also, move the Buttons/TextViews outside and place them before the .setOnClickListener - it makes the code cleaner.
Username = (EditText)findViewById(R.id.Username);
CompanyID = (EditText)findViewById(R.id.CompanyID);
I too got similar error when i misplaced the code
text=(TextView)findViewById(R.id.text);// this line has to be below setcontentview
setContentView(R.layout.activity_my_otype);
//this is the correct place
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
I got it working on placing the code in right order as shown below
setContentView(R.layout.activity_my_otype);
text=(TextView)findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});