当我单击按钮时,应用程序停止

Sanzhar

我想通过从此服务器接收数据来检查与服务器的连接,这是我的代码:

  package com.example.sanzharaubakir.fin;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.HttpEntity;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.client.ClientProtocolException;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.message.BasicNameValuePair;
import cz.msebera.android.httpclient.util.EntityUtils;

/**
 * Created by sanzharaubakir on 26.07.16.
 */
public class auth extends Activity {
    EditText login;
    EditText pswd;
    Button ok;
    MyTask task;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.authorization);
        ok = (Button) findViewById(R.id.ok);
        ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //task = new MyTask();
                //task.execute();
                new MyTask().doInBackground();
            }
        });
    }



    public class MyTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... voids) {
            sendData();
            return null;
        }

       /* @Override
        protected void onPreExecute() {
        }

        protected void onPostExecute(Void result) {
        }*/
    }
    public void sendData()
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://144.76.29.144:8001/documents/api/login");
        try {
            String log = login.getText().toString();
            String psw = pswd.getText().toString();
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("username", log));
            nameValuePairs.add(new BasicNameValuePair("password", psw));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);

            int responseCode = response.getStatusLine().getStatusCode();
            String tk = EntityUtils.toString(response.getEntity());
            if (responseCode == 200)
            {
                SharedPreferences sPref = getPreferences(MODE_PRIVATE);
                SharedPreferences.Editor e = sPref.edit();
                e.putString("token", tk);
                e.apply();
                Intent intent = getIntent();
                String info = intent.getStringExtra("d");
                try {
                    HttpClient client = new DefaultHttpClient();
                    HttpPost Post = new HttpPost("http://144.76.29.144:8001");
                    List<NameValuePair> ValuePairs = new ArrayList<NameValuePair>(2);
                    ValuePairs.add(new BasicNameValuePair("data", info));
                    ValuePairs.add(new BasicNameValuePair("token", tk));

                    Post.setEntity(new UrlEncodedFormEntity(ValuePairs,"UTF-8"));
                    HttpResponse httpResponse = client.execute(Post);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    info = EntityUtils.toString(httpEntity,"UTF-8");


                } catch (MalformedURLException ex) {
                    ex.printStackTrace();

                } catch (IOException ex) {

                    ex.printStackTrace();
                }
            }
            else {

            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }
}

和XML

<?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">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login"
        />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/login"
        />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Password"
            />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/pswd"
            />
    </LinearLayout>
    <Button
        android:id="@+id/ok"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Log in"
        />
</LinearLayout>

当我尝试单击该按钮时,应用程序不幸地停止了,是否有人知道它为什么会发生?这是Log所说的:

FATAL EXCEPTION: main
                                                                              Process: com.example.sanzharaubakir.fin, PID: 2620
                                                                              java.lang.NullPointerException
                                                                                  at com.example.sanzharaubakir.fin.auth.sendData(auth.java:76)
                                                                                  at com.example.sanzharaubakir.fin.auth$MyTask.doInBackground(auth.java:60)
                                                                                  at com.example.sanzharaubakir.fin.auth$1.onClick(auth.java:47)
                                                                                  at android.view.View.performClick(View.java:4438)
                                                                                  at android.view.View$PerformClick.run(View.java:18422)
                                                                                  at android.os.Handler.handleCallback(Handler.java:733)
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                  at android.os.Looper.loop(Looper.java:136)
                                                                                  at android.app.ActivityThread.main(ActivityThread.java:5017)
                                                                                  at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                  at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                                                                                  at dalvik.system.NativeStart.main(Native Method)
狂犬病Z

请记住:建议所有耗时的操作(例如网络操作和读取数据库)都在后台线程中运行,而不是在UI线程中运行。因为它们可能导致ANR异常。您可以使用AsyncTask或仅新建一个子线程来发出http请求,并在主线程(UI线程)中显示接口。顺便说一句,如果您在Android 2.2以上版本运行,我建议使用HttpUrlConnection而不是HttpClient。

编辑:AsyncTask的用法。

您不能直接调用doInBackground方法,可以尝试以下代码供参考。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);
    ...
    ok.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new MyTask().execute();     //you can't invoke the doInBackground method directly
        }
    });
}

public class MyTask extends AsyncTask<Void, Void, Void> {

    /**
     * Runs on the UI thread before doInBackground, does preloading works generally speaking
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    /**
     * Runs on the background thread, does time-consuming operations
     */
    @Override
    protected Void doInBackground(Void... params) {
        // when you finish loading, you can call publishProgress to publish updates on the UI thread
        return null;
    }

    /**
     * Runs on the UI thread after publishProgress is invoked.
     */
    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
        // you can update the loading progress here
    }

    /**
     * Runs on the UI thread after doInBackground
     * This method won't be invoked if the task was cancelled
     */
    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

当我单击“翻译”按钮时,“应用程序名称”一直停止。

单击按钮时应用程序停止

当我单击UserInfo按钮时如果强制关闭我的应用程序

当我单击“再次播放”按钮时,我的整个应用程序崩溃

当我单击按钮时,我无法再使用应用程序,直到它结束

当我在Android应用程序中单击“笔记”按钮时,如何调用我的NoteMain类

当我向后按下按钮时,我的应用程序停止工作

android编程的新手,试图创建登录按钮以进入登录屏幕。当我单击登录按钮时,应用程序显示“停止工作”

当我单击其他片段中的搜索按钮时,应用程序崩溃

当我单击打开弹出窗口的按钮时应用程序崩溃

当我单击按钮时刷新整个用户在WinForms应用程序中输入的数据

当我单击主页按钮时,android应用程序未关闭

当我单击快速WebView中的共享按钮时,重定向到Facebook应用程序

当我单击按钮时,Android 应用程序崩溃,onClickListener 出现问题

当我单击菜单按钮时,Android 应用程序崩溃

当我按下Android Studio中的注册按钮时,应用程序停止工作

为什么当我单击提交按钮时,此 PyQt5 发票 GUI 应用程序的“Python 停止工作”?

当我单击TextView时,应用程序关闭

单击按钮时应用程序不幸停止

当我点击按钮时应用程序关闭

当我单击一个按钮时,使用 Android Studio 和我的应用程序强制关闭

当我按下后退按钮但我想停止应用程序android时打开登录活动

单击搜索时,我的应用程序已停止

当我在Web应用程序中单击一个文本框时,IIS Express突然停止

单击提交按钮时我的应用程序崩溃

我的应用程序在单击按钮时崩溃

如何获得从SQLite数据库中选择的特定值?当我单击按钮时,应用程序崩溃

每当我单击手机上的应用程序上的“开始”按钮时,是否强制关闭?

当我单击按钮转到 winforms 中的另一个表单时,应用程序冻结