Приложение вылетает при нажатии кнопки входа
Я пытаюсь сделать это маленькое приложение новичком, и на первой странице я хочу нажать кнопку входа в систему, чтобы перейти на страницу входа. Я провел поиск и использовал намерение, и в моем коде нет ошибок. Однако всякий раз, когда я нажимаю кнопку входа в систему, приложение вылетает, и я не знаю почему. Я старался изо всех сил, чтобы узнать, и это моя последняя надежда здесь.
Основной класс:
package com.example.ali.test;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button b3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.b3);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(),Loginpage.class);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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);
}
}
Класс входа:
package com.example.ali.test;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Loginpage extends ActionBarActivity {
Button b1,b2 , b3;
EditText ed1,ed2;
TextView tx1;
int counter = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.b3);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
b1=(Button)findViewById(R.id.button);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
b2=(Button)findViewById(R.id.button2);
tx1=(TextView)findViewById(R.id.textView3);
tx1.setVisibility(View.GONE);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(ed1.getText().toString().equals("admin") &&
ed2.getText().toString().equals("admin")) {
Toast.makeText(getApplicationContext(), "Redirecting...",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Wrong Credentials",Toast.LENGTH_SHORT).show();
tx1.setVisibility(View.VISIBLE);
tx1.setBackgroundColor(Color.RED);
counter--;
tx1.setText(Integer.toString(counter));
if (counter == 0) {
b1.setEnabled(false);
}
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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);
}
}
Это XML-файлы:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:id="@+id/b3"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:onClick="onClick"
android:layout_alignParentEnd="true" />
</RelativeLayout>
и XML для входа
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.ali.test.Loginpage">
<TextView android:text="Login" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:hint="Enter Name"
android:focusable="true"
android:textColorHighlight="#ff7eff15"
android:textColorHint="#ffff25e6"
android:layout_marginTop="46dp"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText"
android:textColorHint="#ffff299f"
android:hint="Password" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Attempts Left:"
android:id="@+id/textView2"
android:layout_below="@+id/editText2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="25dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="@+id/textView3"
android:layout_alignTop="@+id/textView2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignBottom="@+id/textView2"
android:layout_toEndOf="@+id/textview"
android:textSize="25dp"
android:layout_toRightOf="@+id/textview" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="login"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="@+id/textview"
android:layout_toStartOf="@+id/textview" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
android:id="@+id/button2"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@+id/textview"
android:layout_toEndOf="@+id/textview" />
</RelativeLayout>
Спасибо.
4 ответа
Ты звонишь setContentView()
в вашей активности входа в систему и предоставив ему тот же файл макета, что и основная деятельность. Таким образом, вы, вероятно, получаете сбой, пытаясь установить что-то в представлении после вызова findViewById()
и он вернулся null
потому что нет представления с этим идентификатором в основном макете.
Попробуй это:
setContentView(R.layout.activity_login);
в активе вашей страницы входа нет возможности вызвать тот же макет, который вы используете в своей основной деятельности
*activity_login: обратитесь к названию макета вашей страницы входа.
Вам просто нужно написать правильное имя макета в вашем Loginpage.java в setContentView()
как вы написали то же имя макета MainActivity.java, так что, вероятно, когда приложение попыталось найти идентификатор представления объявленных вами представлений, оно не нашло их, и они считались null
,
Я думаю, что ваше приложение падает, когда вы нажимаете кнопку, потому что у вас нет b3 в XML для входа в систему. Измените эту строку на странице входа на существующую кнопку:
Button button = (Button) findViewById(R.id.b3);
Сбой происходит при загрузке класса Loginpage. Чтобы быстро убедиться, что это так, переименуйте R.id.b3 в строке выше в R.id.button и повторите тест.
Вы также можете изменить эту строку в MainActivity (изменить обратно в случае сбоя:)):
Intent intent = new Intent(v.getContext(),Loginpage.class);
чтобы:
Intent intent = new Intent(MainActivity.this,Loginpage.class);
Ответ Ларри Шифера /minos23 также необходим, чтобы не потерпеть крах (но вы уже сделали это).