Android -studio java .lang.NullPointerException onPostExecute App cra sh на телефоне не на эмуляторе - PullRequest
0 голосов
/ 16 июня 2020
public class AccesHTTP extends AsyncTask<String, Integer, Long> {

    private ArrayList<NameValuePair> parametres;
    private String ret = null;
    public AsyncResponse delegate = null;
    **
     * Constructeur
     */


    public AccesHTTP(){
        parametres = new ArrayList<NameValuePair>();
    }

    /**
     * Ajout d'un parametre post
     * @param nom
     * @param valeur
     */
    public void addParam(String nom, String valeur) {
        parametres.add(new BasicNameValuePair(nom, valeur));
    }

    /**
     * Connexion en tache de fond dans un thread separe
     * @param strings
     * @return
     */
    @Override
    protected Long doInBackground(String... strings) {
        HttpClient cnxHttp = new DefaultHttpClient();
        HttpPost paramCnx = new HttpPost(strings[0]);

        try {
            // encodage des parametres
            paramCnx.setEntity(new UrlEncodedFormEntity(parametres));
            // connexion et envoi de parametres, attente de reponse
            HttpResponse reponse = cnxHttp.execute(paramCnx);
            // transformation de la reponse
            ret = EntityUtils.toString(reponse.getEntity());
        } catch (UnsupportedEncodingException e) {
            Log.d("Erreur encodage", "******************"+e.toString());
        } catch (ClientProtocolException e) {
            Log.d("Erreur protocole", "******************"+e.toString());
        } catch (IOException e) {
            Log.d("Erreur I/O", "******************"+e.toString());
        }
        return null;
    }

    @Override
    protected void onPostExecute(Long result){
        delegate.processFinish((ret.toString()));
    }

}

У меня ошибка

java.lang.NullPointerException com.example.dupe.outils.AccesHTTP.onPostExecute(AccesHTTP.java:72)
com.example.dupe.outils.AccesHTTP.onPostExecute(AccesHTTP.java:20) 

, но я не знаю, как ее исправить. Когда я запускаю приложение в эмуляторе, оно работает, но когда я запускаю его на телефоне, оно вылетает.

Теперь у меня следующие ошибки:

01-06 09: 48: 30.470 22942-23238 /com.example.dupe W / dalvikvm: threadid = 13: поток завершается с неперехваченным исключением (группа = 0x41b07498) 01-06 09: 48: 30.470 155-23237 /? W / SocketClient: ошибка записи (сломанная труба) 01-06 09: 48: 30.480 22942-23238 / com.example.dupe E / test: Exception 01-06 09: 48: 30.520 22942-23238 / com.example.dupe E / AndroidRuntime: ФАТАЛЬНОЕ ИСКЛЮЧЕНИЕ: AsyncTask # 2 java .lang.RuntimeException: произошла ошибка при выполнении doInBackground () в android .os.AsyncTask $ 3.done (AsyncTask. java: 299) в java. util.concurrent.FutureTask $ Syn c .innerSetException (FutureTask. java: 273) в java .util.concurrent.FutureTask.setException (FutureTask. java: 124) в java .util.concurrent .FutureTask $ Syn c .innerRun (FutureTask. java: 307) в java .util.concurrent.FutureTask.run (FutureTask. java: 137) в android .os.AsyncTask $ SerialExecutor $ 1 .run (AsyncTask. java: 230) в java .util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor. java: 1076) в java .util.concurrent.ThreadPoolExecutor $ Worker.run (ThreadPoolExecutor $ Worker.run 1035 *: 569) в java .lang.Thread.run (Thread. java: 856) Вызвано: java .lang.ArrayIndexOutOfBoundsException: length = 0; index = 0 в com.example.dupe.outils.AccesHTTP.doInBackground (AccesHTTP. java: 51) в com.example.dupe.outils.AccesHTTP.doInBackground (AccesHTTP. java: 20) в android. os.AsyncTask $ 2.call (AsyncTask. java: 287) в java .util.concurrent.FutureTask $ Syn c .innerRun (FutureTask. java: 305) в java .util.concurrent. FutureTask.run (FutureTask. java: 137) в android .os.AsyncTask $ SerialExecutor $ 1.run (AsyncTask. java: 230) в java .util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor. 1051 *: 1076) в java .util.concurrent.ThreadPoolExecutor $ Worker.run (ThreadPoolExecutor. java: 569) в java .lang.Thread.run (Thread. java: 856) 01-06 09: 48: 30.640 427-4177 /? W / ActivityManager: принудительное завершение действия com.example.dupe /.vue .MainActivity


public interface AsyncResponse {
    void processFinish(String output);
}

publi c класс AccesDistant реализует AsyncResponse {

// constante
private static final String SERVERADDR = "http://dupe-charente.fr/dupe/serveurdupe.php";

public AccesDistant(){
    super();
}

/**
 * retour du serveur distant
 * @param output
 */
@Override
public void processFinish(String output) {
    Log.d("serveur", "****************"+output);
    // découpage du message reçu avec %
    String[] message = output.split("%");
    // dans message[0] : "enreg", "dernier", "Erreur !"
    // dams message[1] : reste du message

    // s'il y a 2 cases
    if(message.length>1){
        if(message[0].equals("enreg")){
            Log.d("enreg", "***************"+message[1]);

        }else{
            if(message[0].equals("dernier")){
                Log.d("dernier", "***************"+message[1]);
            }else{
                if(message[0].equals("Erreur !")){
                    Log.d("Erreur !", "***************"+message[1]);
                }
            }
        }
    }
}

public void envoi(String operation, JSONArray lesDonneesJSON){
    AccesHTTP accesDonnees = new AccesHTTP();
    // lien de delegation
    accesDonnees.delegate = this;
    // ajout parametres
    accesDonnees.addParam("operation", operation);
    accesDonnees.addParam("lesdonnees", lesDonneesJSON.toString());
    // appel au serveur
    accesDonnees.execute(SERVERADDR);
}

}



public class MainActivity extends AppCompatActivity implements View.OnClickListener, AsyncResponse {
RadioGroup grpRadioCar;
RadioGroup rg1;
RadioGroup rg;
    AccesHTTP AsyncTask = new AccesHTTP();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        grpRadioCar = findViewById(R.id.grpRadioCar);
        rg1 = findViewById(R.id.rg1);
        rg = findViewById(R.id.rg);
        init();
//this to set delegate/listener back to this class
        AsyncTask.delegate = this;

        //execute the async task
        AsyncTask.execute();

        TextView txt = (TextView) findViewById(R.id.rdAmbulance);
        TextView txt2 = (TextView) findViewById(R.id.rdTaxi);
        TextView txt3 = (TextView) findViewById(R.id.rdVsl);
        TextView txt4 = (TextView) findViewById(R.id.textView);
        TextView txt5 = (TextView) findViewById(R.id.textView2);
        TextView txt6 = (TextView) findViewById(R.id.custom_font2);
        TextView txt7 = (TextView) findViewById(R.id.radioButton9);
        TextView txt8 = (TextView) findViewById(R.id.radioButton10);
        TextView txt9 = (TextView) findViewById(R.id.radioButton11);
        TextView txt10 = (TextView) findViewById(R.id.radioButton12);
        TextView txt11 = (TextView) findViewById(R.id.textView8);
        TextView txt12 = (TextView) findViewById(R.id.nettint);
        TextView txt13 = (TextView) findViewById(R.id.lavext);
        TextView txt14 = (TextView) findViewById(R.id.btnValid);
        TextView txt15 = (TextView) findViewById(R.id.textView7);
        TextView txt16 = (TextView) findViewById(R.id.btnReset);
        TextView txt17 = (TextView) findViewById(R.id.txtNom);
        TextView txt18 = (TextView) findViewById(R.id.txtImmat);
        TextView txt19 = (TextView) findViewById(R.id.textView11);
        TextView txt20 = (TextView) findViewById(R.id.txtProd);
        TextView txt21 = (TextView) findViewById(R.id.tout);
        TextView txt22 = (TextView) findViewById(R.id.btnquit);


        Typeface font = Typeface.createFromAsset(getAssets(), "aller.ttf");
        txt.setTypeface(font);
        txt2.setTypeface(font);
        txt3.setTypeface(font);
        txt4.setTypeface(font);
        txt5.setTypeface(font);
        txt6.setTypeface(font);
        txt7.setTypeface(font);
        txt8.setTypeface(font);
        txt9.setTypeface(font);
        txt10.setTypeface(font);
        txt11.setTypeface(font);
        txt12.setTypeface(font);
        txt13.setTypeface(font);
        txt14.setTypeface(font);
        txt15.setTypeface(font);
        txt16.setTypeface(font);
        txt17.setTypeface(font);
        txt18.setTypeface(font);
        txt19.setTypeface(font);
        txt20.setTypeface(font);
        txt21.setTypeface(font);
        txt22.setTypeface(font);



    }

    // propriétés
    private EditText txtNom;
    private EditText txtImmat;
    private RadioButton rdAmbulance;
    private RadioButton rdVsl;
    private RadioButton rdTaxi;
    private TextView textView5;
    private ImageView imgDupe;
    private Controle controle;
    private RadioButton radioButton9;
    private RadioButton radioButton10;
    private RadioButton radioButton11;
    private RadioButton radioButton12;
    private RadioButton nettint;
    private RadioButton lavext;
    private RadioButton tout;
    private EditText txtProd;



    /**
     * initialisation des liens avec les objets graphiques
     */
    private  void init() {
        txtNom = (EditText)findViewById(R.id.txtNom);
        txtImmat = (EditText)findViewById(R.id.txtImmat);
        txtProd = (EditText)findViewById(R.id.txtProd);
        rdAmbulance = (RadioButton) findViewById(R.id.rdAmbulance);
        rdVsl = (RadioButton)findViewById(R.id.rdVsl);
        rdTaxi = (RadioButton)findViewById(R.id.rdTaxi);
        radioButton9 = (RadioButton)findViewById(R.id.radioButton9);
        radioButton10 = (RadioButton)findViewById(R.id.radioButton10);
        radioButton11 = (RadioButton)findViewById(R.id.radioButton11);
        radioButton12 = (RadioButton)findViewById(R.id.radioButton12);
        nettint = (RadioButton)findViewById(R.id.nettint);
        lavext = (RadioButton)findViewById(R.id.lavext);
        tout = (RadioButton)findViewById(R.id.tout);
        this.controle = Controle.getInstance(this);
        grpRadioCar = (RadioGroup) findViewById(R.id.grpRadioCar);
        rg = (RadioGroup) findViewById(R.id.rg);
        rg1 = (RadioGroup) findViewById(R.id.rg1);
        Button clearButton = (Button) findViewById(R.id.btnReset);
        clearButton.setOnClickListener(this);
        Button q =(Button) findViewById(R.id.btnquit);
        ecouteValidation();
        recupProfil();

    }

    /**
     * Ecoute evenement bouton Validation
     */

    private void ecouteValidation(){
        ((Button) findViewById(R.id.btnValid)).setOnClickListener(new Button.OnClickListener() {

            public void onClick(View v) {
                // Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
                //Log.d("message", "clic ok sur le bouton Valid ******************");
                String nom = null;
                String immat = null;
                Integer typev = 0;
                Integer des = 0;
                Integer net = 0;
                String prod = null;

                try {
                    nom = txtNom.getText().toString();
                    immat = txtImmat.getText().toString();
                    prod = txtProd.getText().toString();
                } catch (Exception e) {};
                if(rdAmbulance.isChecked()){
                    typev = 1;
                }
                if(rdVsl.isChecked()){
                    typev = 2;
                }
                if(rdTaxi.isChecked()){
                    typev = 3;
                }

                if(radioButton9.isChecked()){
                    des = 1;
                }
                if(radioButton10.isChecked()){
                    des = 2;
                }
                if(radioButton11.isChecked()){
                    des = 3;
                }

                if(radioButton12.isChecked()){
                    des = 4;
                }


                if(nettint.isChecked()){
                    net=1;
                }

                if(lavext.isChecked()){
                    net=2;
                }

                if(tout.isChecked()){
                    net=3;
                }


                if (nom.isEmpty() || immat.isEmpty() || prod.isEmpty()) {
                    Toast.makeText(MainActivity.this, "Saisie incorrecte", Toast.LENGTH_SHORT).show();
                } else {
                    afficheResult(nom, immat, typev, des, net, prod);
                    Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    /**
     * Affichage du message
     * @param nom
     * @param immat
     * @param typev
     * @param des
     * @param net
     * @param prod
     */
    private void afficheResult(String nom, String immat, Integer typev, Integer des, Integer net, String prod){
    this.controle.creerProfil(nom, immat,typev, des, net, prod,this);
    }

    /**
     * recup profil s'il a été serializé
     */
    private void recupProfil(){
        if (controle.getNom() != null) {
            txtNom.setText(controle.getNom().toString());
            txtImmat.setText(controle.getImmat().toString());
            txtProd.setText(controle.getProd().toString());

            if(controle.getTypev()==1){
                rdAmbulance.setChecked(true);
            }
            if(controle.getTypev()==2){
                rdVsl.setChecked(true);
            }
            if(controle.getTypev()==3){
                rdTaxi.setChecked(true);
            }


            if(controle.getDes()==1){
                radioButton9.setChecked(true);
            }
            if(controle.getDes()==2){
                radioButton10.setChecked(true);
            }
            if(controle.getDes()==3){
                radioButton11.setChecked(true);
            }
            if(controle.getDes()==4){
                radioButton12.setChecked(true);
            }


            if(controle.getNet()==1){
                nettint.setChecked(true);
            }

            if(controle.getNet()==2){
                lavext.setChecked(true);
            }

            if(controle.getNet()==3){
                tout.setChecked(true);
            }

            ((Button)findViewById(R.id.btnValid)).performClick();


        }

    }


    @Override
    public void onClick(View v) {
        rg.clearCheck();
        rg1.clearCheck();
        grpRadioCar.clearCheck();
    }


    public void exitApp(View v)
    {
        finish();
        System.exit(0);
    }


    @Override
    public void processFinish(String output) {
        //Here you will receive the result fired from async class
        //of onPostExecute(result) method.
    }
}

1 Ответ

0 голосов
/ 16 июня 2020

Hola ami go: читая ваши журналы, я обнаружил, что в вашем коде, вероятно, нет некоторых значений в этой части:

HttpPost paramCnx = new HttpPost (strings [0] );

Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0 at com.example.dupe.outils.AccesHTTP.doInBackground(AccesHTTP.java:51) at com.example.dupe.outils.AccesHTTP.doInBackground(AccesHTTP.java:20) at android.os.AsyncTask$2.call(AsyncTask.java:287) at

Поэтому я бы рекомендовал вам проверить (отладить), имеет ли переменная strings хотя бы одно значение.

...