2016-01-03 5 views
0

Я пытаюсь сделать это маленькое приложение в качестве новичка, и на первой странице я хочу нажать кнопку входа в систему, чтобы перейти на страницу входа. Я сделал поиск, и я использовал намерение, и у моего кода нет ошибок. Однако, всякий раз, когда я нажимаю кнопку входа в систему, приложение падает, и я не знаю, почему. Я изо всех сил старался это выяснить, и это моя последняя надежда здесь.Приложение сбой при нажатии кнопки входа

Главный класс:

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> 

Спасибо.

+0

Log cat пожалуйста! –

+0

^^ очень сложно помочь вам без отслеживания стека и типа ошибки и т. Д. – rodit

+0

01-04 00: 11: 09.926 4272-4272/com.example.ali.test E/AndroidRuntime: FATAL EXCEPTION: main Процесс: com.example.ali.test, PID: 4272 java.lang.RuntimeException: Невозможно запустить Activity ComponentInfo {com.example.ali.test/com.example.ali. test.Loginpage}: java.lang.NullPointerException: попытка вызвать виртуальный метод void android.widget.TextView.setVisibility (int) 'на ссылке нулевого объекта на android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2808) at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2873) –

ответ

3

Вы вызываете setContentView() в свой логин и присваиваете ему тот же файл макета, что и ваш основной вид деятельности. Таким образом, вы, вероятно, получаете сбои, пытаясь установить что-то в представлении после вызова findViewById(), и он вернул null, потому что в главном макете нет представления с этим идентификатором.

2

Попробуйте это:

setContentView(R.layout.activity_login); 

в вашем LoginPage activty unstead вызова тот же макет, который вы используете в вашем MainActivity

* activity_login: см имя макета Ваш Пройти Активность

+0

okay i now now –

1

Вам просто нужно написать правильное название макета в своем Loginpage.java в setContentView(), поскольку вы написали одно и то же имя макета MainActivity.java, поэтому, вероятно, когда приложение попыталось найти идентификатор вида указанных вами представлений, оно их не нашло, и они считались null.

+0

Я изменил setContentView() моей страницы входа в систему, сбой сразу, когда я нажимаю кнопку на первой главной странице –

0

Я думаю, что ваше приложение рушится, когда вы нажимаете кнопку, потому что у вас нет 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); 

Ларри Schiefer/minos23 ответ также необходим для того, чтобы не (но вы сделали это уже).

+0

yess это сработало окончательно , –

+0

Огромное вам спасибо –

+0

ОК сделаю будет человек, спасибо большое –

Смежные вопросы