Android 带有按钮onclick listener的nullPointerException

Android 带有按钮onclick listener的nullPointerException,android,Android,我无法解决nullPointerException问题。有人能帮忙吗 my code: package gsb.com; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.widget.TextView; the main class public class ActivitePrincipale extends Activity {

我无法解决nullPointerException问题。有人能帮忙吗

my code:

package gsb.com;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.widget.TextView;

the main class

public class ActivitePrincipale extends Activity {
    //Variables pour l'authentification
        private TextView tv;
        public static final int RESULT_Main = 1;

        @Override
        protected void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activite_principale);

            //Authentification
            //Appel de la page de Login 
            startActivityForResult(new Intent(ActivitePrincipale.this, Login.class), RESULT_Main);
            //tv = new TextView(this);
            //setContentView(tv);
        }

        //Procédure d'authentification
        private void startup(Intent i) 
        {
            // Récupère l'identifiant        
            int user = i.getIntExtra("userid",-1);

            //Affiche les identifiants de l'utilisateur
            tv.setText("UserID: "+String.valueOf(user)+" logged in");
        }

        protected void onActivityResult(int requestCode, int resultCode, Intent data) 
        { 
            if(requestCode == RESULT_Main && resultCode == RESULT_CANCELED)  
                finish(); 
            else 
                startup(data);
        }


}
登录类

package gsb.com;
import gsb.com.R;


import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class Login extends Activity
{
    // Lien vers votre page php sur le serveur
    private static final String UPDATE_URL  = some ip
    public ProgressDialog progressDialog;
    private EditText UserEditText;
    private EditText PassEditText;
    private android.widget.Button button;

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Log.i("Info","Dans Login - onCreate --------------");
        //initialisation d'une progress bar
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Patientez svp...");
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(false);

        //recuperation des elements de la vue
        UserEditText = (EditText)findViewById(R.id.username);
        if (UserEditText == null) { Log.w("Info", "UserEditText est null --------------"); }
        PassEditText = (EditText)findViewById(R.id.password);
        if (PassEditText == null) { Log.w("Info", "PassEditText est null --------------"); }
        button = (Button)findViewById(R.id.okbutton);
        if (button == null) { Log.w("Info", "button est null --------------"); }

        //definition du listener du bouton ok
        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                int userSize = UserEditText.getText().length();
                int passSize = PassEditText.getText().length();

                //si les deux champs sont complétés
                if(userSize > 0 && passSize > 0){
                    progressDialog.show();
                    String user = UserEditText.getText().toString();
                    String pass = PassEditText.getText().toString();
                    //appel de la fonction doLogin qui va appeler le script connect.php
                    doLogin(user,pass);
                }
                else {
                    createDialog("Erreur !!", "SVP Entrez un nom d'utilisateur et un mot de passe.");
                }
            }
        });

        button = (Button)findViewById(R.id.cancelbutton);
        //creation du listener du bouton annuler pour sortir de l'appli
        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                quit(false, null);
            }
        });
    }

    private void quit(boolean succes, Intent i){
        //envoi d'un resultat qui va permettre de quitter l'appli
        setResult((succes)? Activity.RESULT_OK : Activity.RESULT_CANCELED,i);
        finish();
    }

    private void createDialog(String title, String text){
        //affichage d'un popup
        AlertDialog ad  = new AlertDialog.Builder(this)
                .setPositiveButton("Ok", null).setTitle(title).setMessage(text)
                .create();
        ad.show();
    }

    private void doLogin(final String login, final String pass){
        final String pw = md5(pass);
        //final String pw = pass;

        //creation d'un thread
        Thread t = new Thread(){
            public void run(){
                Looper.prepare();
                //connexion au serveur pour communiquer avec le php
                DefaultHttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(),15000);

                HttpResponse response;
                HttpEntity entity;

                try{
                    //on etablit un lien avec le script connect.php
                    HttpPost post = new HttpPost(UPDATE_URL);
                    List<NameValuePair> nvp = new ArrayList<NameValuePair>();
                    nvp.add(new BasicNameValuePair("username",login));
                    nvp.add(new BasicNameValuePair("password",pw));
                    post.setHeader("Content-Type", "application/x-www-form-urlencoded");

                    //passage des params login et password qui vont etre recup par le script php en Post
                    post.setEntity(new UrlEncodedFormEntity(nvp, HTTP.UTF_8));

                    //recup du resultat du script
                    response = client.execute(post);
                    entity = response.getEntity();
                    InputStream is = entity.getContent();

                    //appel d'une fonction pour traduire la reponse
                    read(is);
                    is.close();

                    if(entity != null){
                        entity.consumeContent();
                    }
                }
                catch(Exception e){
                    progressDialog.dismiss();
                    createDialog("Error", "Impossible d'etablir une connexion");
                }
                Looper.loop();
            }
        };
        t.start();
    }

    private void read(InputStream inpStr){
        //traduction du resultat du flux
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp;

        try{
            sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();

            //classe definie plus bas
            LoginContentHandler lch = new LoginContentHandler();

            xr.setContentHandler(lch);
            xr.parse(new InputSource(inpStr));          
        }
        catch(ParserConfigurationException e){}
        catch(SAXException e){}
        catch(IOException e){}
    }

    private String md5(String in) {

        MessageDigest digest;

        try {

            digest = MessageDigest.getInstance("MD5");

            digest.reset();

            digest.update(in.getBytes());

            byte[] a = digest.digest();

            int len = a.length;

            StringBuilder sb = new StringBuilder(len << 1);

            for (int i = 0; i < len; i++) {
                sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
                sb.append(Character.forDigit(a[i] & 0x0f, 16));
            }

            return sb.toString();

        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;
    }

    private class LoginContentHandler extends DefaultHandler {
        //Traite le retour du script connect.php

        private boolean in_loginTag = false;
        private int userID;
        private boolean error_occured = false;

        public void startElement(String n, String l, String q, Attributes a) throws SAXException {

                if(l=="login"){
                    in_loginTag = true;
                }

                if(l=="error"){
                    progressDialog.dismiss();

                    switch(Integer.parseInt(a.getValue("value"))){
                    case 1:
                        createDialog("Error", "Impossible de se connecter à la base de données");
                        break;
                    case 2:
                        createDialog("Error", "Erreur dans la base de données, Table manquante");
                        break;
                    case 3:
                        createDialog("Error", "Login ou mot de passe invalide !");
                        break;
                    }
                    error_occured = true;
                }

                if(l=="user" && in_loginTag && a.getValue("id")!=""){
                    //si tout est ok on recup l'id de l'utilisateur
                    userID = Integer.parseInt(a.getValue("id"));
                }                           
        }

        public void endElement(String n, String l, String q) throws SAXException {
            //on renvoie l'id si tout est ok
            if(l=="login"){
                in_loginTag = false;

                if(! error_occured){
                    progressDialog.dismiss();
                    Intent i = new Intent();
                    i.putExtra("userid", userID);
                    quit(true, i);
                }
            }
        }

        public void characters(char ch[], int start, int length){}
        public void startDocument() throws SAXException{}
        public void endDocument() throws SAXException{}
    }
}

似乎有些人确实对按钮监听器有问题,但阅读帖子并没有给我预期的解决方案。感谢您的帮助。

您正在尝试将同一按钮变量设置为布局上的两个不同按钮:

button = (Button)findViewById(R.id.okbutton);
button = (Button)findViewById(R.id.cancelbutton);
您需要为它们创建两个单独的变量

编辑经过多次辩论,我再次尝试了一些代码,并意识到问题所在

我按如下方式设置了按钮:

button = (Button) findViewById(R.id.ok);
button = (Button) findViewById(R.id.cancel);

button.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v){
         //stuff
     }
});

button.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v){
         // other stuff
     }
});
button = (Button) findViewById(R.id.ok);
button.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v){
         //stuff
     }
});

button = (Button) findViewById(R.id.cancel);
button.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v){
         // other stuff
     }
});
这行不通!!!然而,经过多次辩论后,我想尝试以下其他方法:

button = (Button) findViewById(R.id.ok);
button = (Button) findViewById(R.id.cancel);

button.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v){
         //stuff
     }
});

button.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v){
         // other stuff
     }
});
button = (Button) findViewById(R.id.ok);
button.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v){
         //stuff
     }
});

button = (Button) findViewById(R.id.cancel);
button.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v){
         // other stuff
     }
});

另一方面,这是可行的

您的问题在这里,或者至少有一个是您没有在
登录
中膨胀布局。因此,您尝试使用的任何视图(
按钮
编辑文本
,等等)都将为

onCreate()
中调用
setContentView(R.layout.yourLayout)在尝试设置
视图之前

UserEditText = (EditText)findViewById(R.id.username);
视图
存在于
布局
中,因此在使用
充气器或调用
setContentView(…)对
布局
充气之前,它们都是
空的

另外,由于你是新来的,关于这个网站的几件事

  • 请阅读
  • 发布代码时,请选择您认为最相关的部分,并将其与相关日志和错误消息一起发布。如果需要,我们将请求更多
  • 如果你发布了多个类,请将它们分开,而不是一个长的部分,以便成员更容易阅读
  • 通常不需要所有导入语句

这些不是真正的问题,但会帮助您获得更好/更快的答案

您必须首先在super之后使用
setContentview(R.layout.XXXX)
,然后只有您才能使用资源。另外,您将得到空指针异常。。
登录活动中缺少“设置内容”视图

我注意到您的登录活动中没有setContentView。
通常,如果人们在调用setContentView之前调用findViewById(…),就会得到空指针错误。在您的情况下,甚至没有setContentView()。

如果“确定”按钮没有响应单击,则侦听器实例可能正在被垃圾收集器清理

将侦听器创建为类级属性:

private OnClickListener okListener = new View.OnClickListener() { ... };
private OnClickListener cancelListener = new View.OnClickListener() { ... };
然后在onCreate()中分配它们:


由于侦听器在活动中具有引用,因此不会对其进行垃圾收集。我在另一个线程上启动媒体播放器时遇到了类似的问题。玩家被杀是因为我没有保留对线程的引用,所以垃圾收集器看到一个未引用的对象树并将其清除。

UserEditText或PasseEditText可能为空吗?只需在侦听器的第一行设置一个断点,然后在调试器中逐步执行即可。您是否查看了第67行的调用内容?请接受其中一个对您有用的答案,以表示您的感谢,这样可以帮助其他人回答相同的问题。好的,谢谢您的评论。第67行是登录类中带有button.SetOnClickListener的那一行,因为您没有像在我的回答中那样调用
setContentView()
按钮是
null
,所以当您尝试设置
侦听器或调用其上的函数时,您会得到
NPE
没有问题,我看到了,所以我只是给你们下一次的建议。这都是关于学习的。无论如何,您的登录页面应该有一个xml文件。在初始化任何
视图之前设置此选项
谢谢!现在可以了。真的很有帮助。正如我所说的,我对java编程非常陌生。大块头!如何在活动活动中收集单个方法垃圾?那没有道理。线程被垃圾回收的原因是它与活动是分开的,并且没有链接到活动。你试过这个密码吗?似乎对我不起作用…这段代码还没有结束,但我想先在emulator中试用,并在apk启动时崩溃。现在没事了,谢谢!
((Button)findViewById(R.id.okbutton)).setOnClickListener(okListener);
((Button)findViewById(R.id.cancelbutton)).setOnClickListener(cancelListener );