android.os.NetworkOnMainThreadException。需要使用异步任务? [英] android.os.NetworkOnMainThreadException . Need to use async task?

查看:129
本文介绍了android.os.NetworkOnMainThreadException。需要使用异步任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的android登录功能有问题,越来越 android.os.NetworkOnMainThreadException

我去掉了密码字段只是现在来测试,如果只是用户名已被张贴,我知道,这是为Android 3.2 +的一个问题。

下面是我的code:

 包com.example.toknapp;

进口的java.util.ArrayList;

公共类Login2身份延伸活动{
    联合国的EditText;
    TextView的错误;
    OK按钮;
    / **第一次创建活动时调用。 * /
    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.login);
        UN =(EditText上)findViewById(R.id.et_un);
        OK =(按钮)findViewById(R.id.btn_login);
        误差=(TextView中)findViewById(R.id.tv_error);

        ok.setOnClickListener(新View.OnClickListener(){

            @覆盖
            公共无效的onClick(视图v){
                // TODO自动生成方法存根

                ArrayList的<的NameValuePair> postParameters =新的ArrayList<的NameValuePair>();
                postParameters.add(新BasicNameValuePair(用户名,un.getText()的toString()));
                //字符串有效=1;
                串响应=无效;
                尝试 {
                    响应= CustomHttpClient.executeHttpPost(http://tokn.me/android_merchant_login.php,postParameters);
                    字符串解析度= response.toString();
                   //解析度= res.trim();
                    RES = res.replaceAll(\\ S +,);
                    //error.setText(res);

                   如果(res.equals(1))
                        error.setText(正确的用户名和密码);
                    其他
                        error.setText(对不起!不正确的用户名或密码);
                }赶上(例外五){
                    un.setText(e.toString());
                }

            }
        });
    }
}


包com.example.toknapp;

进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口java.io.InputStreamReader中;
进口java.net.URI中;
进口的java.util.ArrayList;

进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.conn.params.ConnManagerParams;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.params.HttpConnectionParams;
进口org.apache.http.params.HttpParams;

公共类CustomHttpClient {
    / **所花费的时间为我们的客户超时* /
    公共静态最终诠释HTTP_TIMEOUT = 30 * 1000; //毫秒

    / **我们的HttpClient单实例* /
    私有静态HttpClient的mHttpClient;

    / **
     *获取我们的单我们HttpClient的对象实例。
     *
     返回:一个HttpClient的对象连接参数设置
     * /
    私有静态HttpClient的getHttpClient(){
        如果(mHttpClient == NULL){
            mHttpClient =新DefaultHttpClient();
            最后的HttpParams PARAMS = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(参数,可以HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(参数,可以HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(参数,可以HTTP_TIMEOUT);
        }
        返回mHttpClient;
    }

    / **
     *执行一个HTTP POST请求到指定的URL与
     *指定的参数。
     *
     *参数的URL网址张贴请求
     *参数postParameters的参数通过发送请求
     返回:所述请求的结果
     * @throws异常
     * /
    公共静态字符串executeHttpPost(字符串URL,ArrayList的<的NameValuePair> postParameters)抛出异常{
        BufferedReader中的= NULL;
        尝试 {
            HttpClient的客户= getHttpClient();
            HttpPost请求=新HttpPost(URL);
            UrlEn codedFormEntity formEntity =新UrlEn codedFormEntity(postParameters);
            request.setEntity(formEntity);
            HTT presponse响应= client.execute(要求);
            在=新的BufferedReader(新的InputStreamReader(response.getEntity()的getContent()));

            StringBuffer的SB =新的StringBuffer();
            串线=;
            串NL = System.getProperty(line.separator);
            而((行= in.readLine())!= NULL){
                sb.append(行+ NL);
            }
            附寄();

            字符串结果= sb.toString();
            返回结果;
        } 最后 {
            如果(在!= NULL){
                尝试 {
                    附寄();
                }赶上(IOException异常E){
                    e.printStackTrace();
                }
            }
        }
    }

    / **
     *执行一个HTTP GET请求到指定的URL。
     *
     *参数的URL网址张贴请求
     返回:所述请求的结果
     * @throws异常
     * /
    公共静态字符串executeHttpGet(字符串URL)抛出异常{
        BufferedReader中的= NULL;
        尝试 {
            HttpClient的客户= getHttpClient();
            HTTPGET请求=新HTTPGET();
            request.setURI(新的URI(URL));
            HTT presponse响应= client.execute(要求);
            在=新的BufferedReader(新的InputStreamReader(response.getEntity()的getContent()));

            StringBuffer的SB =新的StringBuffer();
            串线=;
            串NL = System.getProperty(line.separator);
            而((行= in.readLine())!= NULL){
                sb.append(行+ NL);
            }
            附寄();

            字符串结果= sb.toString();
            返回结果;
        } 最后 {
            如果(在!= NULL){
                尝试 {
                    附寄();
                }赶上(IOException异常E){
                    e.printStackTrace();
                }
            }
        }
    }
}
 

解决方案

我想你想peform在你的主线程的一些网络操作

NetworkOnMainThreadException 从文档

  

的异常当应用程序试图执行时引发   联网运行其主线程。

更新:

它能够更好地使用的AsyncTask

 私有类MyAsyncTask扩展的AsyncTask<虚空,虚空,虚空>
    {

        ProgressDialog mProgressDialog;
        @覆盖
        保护无效onPostExecute(无效的结果){
            mProgressDialog.dismiss();
        }

        @覆盖
        在preExecute保护无效(){
            mProgressDialog = ProgressDialog.show(ActivityName.this,
                                            载入中...,数据载入中......);
        }

        @覆盖
        保护无效doInBackground(虚空...... PARAMS){
           //你的网络操作
            返回null;
        }
    }
 

I'm having a problem with my android login functionality, getting android.os.NetworkOnMainThreadException

I removed the password field just for now to test if just the username was being posted, I'm aware that this is a problem for android 3.2+.

Here is my code:

package com.example.toknapp;

import java.util.ArrayList;

public class login2 extends Activity {
    EditText un;
    TextView error;
    Button ok;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        un=(EditText)findViewById(R.id.et_un);
        ok=(Button)findViewById(R.id.btn_login);
        error=(TextView)findViewById(R.id.tv_error);

        ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
                postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
                //String valid = "1";
                String response = null;
                try {
                    response = CustomHttpClient.executeHttpPost("http://tokn.me/android_merchant_login.php", postParameters);
                    String res=response.toString();
                   // res = res.trim();
                    res= res.replaceAll("\\s+","");                              
                    //error.setText(res);

                   if(res.equals("1"))
                        error.setText("Correct Username or Password");
                    else
                        error.setText("Sorry!! Incorrect Username or Password"); 
                } catch (Exception e) {
                    un.setText(e.toString());
                }

            }
        });
    }
}


package com.example.toknapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class CustomHttpClient {
    /** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

    /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;

    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
    private static HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }

    /**
     * Performs an HTTP Post request to the specified url with the
     * specified parameters.
     *
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

解决方案

I guess you are trying to peform some Network operation on your main thread

NetworkOnMainThreadException from the Docs

The exception that is thrown when an application attempts to perform a networking operation on its main thread.

UPDATE:

Its Better to use AsyncTask

private class MyAsyncTask extends AsyncTask<Void, Void, Void>
    {

        ProgressDialog mProgressDialog;
        @Override
        protected void onPostExecute(Void result) {
            mProgressDialog.dismiss();
        }

        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(ActivityName.this, 
                                            "Loading...", "Data is Loading...");
        }

        @Override
        protected Void doInBackground(Void... params) {
           // your network operation
            return null;
        }
    }

这篇关于android.os.NetworkOnMainThreadException。需要使用异步任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆