2 telen0928 telen0928 于 2013.07.30 23:03 提问

大家看看下面的代码有什么问题,为什么在Eclipse里老是出现

public class MainActivity extends Activity {
/** Called when the activity is first created. */
private Button loginBtn;
private Button registerBtn;
private EditText inputUsername;
private EditText inputPassword;
private CheckBox saveInfoItem;
private ProgressDialog mDialog;
private String responseMsg = "";
private static final int REQUEST_TIMEOUT = 5*1000;//设置请求超时5秒钟

private static final int SO_TIMEOUT = 10*1000; //设置等待数据超时时间10秒钟

//private static final int LOGIN_OK = 1;
private SharedPreferences sp;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    loginBtn = (Button)findViewById(R.id.login_btn_login);
    registerBtn = (Button)findViewById(R.id.login_btn_zhuce);
    inputUsername = (EditText)findViewById(R.id.login_edit_account);
    inputPassword = (EditText)findViewById(R.id.login_edit_pwd);
    CheckNetworkState();
     loginBtn.setOnClickListener(new Button.OnClickListener()
    {

        @Override
        public void onClick(View arg0) {
            mDialog = new ProgressDialog(MainActivity.this);
            mDialog.setTitle("登陆");
            mDialog.setMessage("正在登陆服务器,请稍后...");
            mDialog.show();
            Thread loginThread = new Thread(new LoginThread());

            loginThread.start();

        }

    });

    registerBtn.setOnClickListener(new Button.OnClickListener()
    {

        @Override
        public void onClick(View arg0) {
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, Zhuce.class);
            startActivity(intent);
        }

    });
}


private boolean loginServer(String username, String password)
{
    boolean loginValidate = false;
    //使用apache HTTP客户端实现
    String urlStr = "http://192.168.1.101:8080/login/LoginServlet";
    HttpPost request = new HttpPost(urlStr);
    //如果传递参数多的话,可以丢传递的参数进行封装
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    //添加用户名和密码
    params.add(new BasicNameValuePair("username",username));
    params.add(new BasicNameValuePair("password",password));
    try
    {
        //设置请求参数项
        request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        HttpClient client = getHttpClient();
        //执行请求返回相应
        HttpResponse response = client.execute(request);

        //判断是否请求成功
        if(response.getStatusLine().getStatusCode()==200)
        {
            loginValidate = true;
            //获得响应信息
            responseMsg = EntityUtils.toString(response.getEntity());
        }
    }catch(Exception e)
    {
        e.printStackTrace();
    }
    return loginValidate;
}



//初始化HttpClient,并设置超时
public HttpClient getHttpClient()
{
    BasicHttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
    HttpClient client = new DefaultHttpClient(httpParams);
    return client;
}

public void CheckNetworkState()
{
boolean flag = false;
ConnectivityManager manager = (ConnectivityManager)getSystemService(
Context.CONNECTIVITY_SERVICE);
State mobile = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
//如果3G、wifi、2G等网络状态是连接的,则退出,否则显示提示信息进入网络设置界面
if(mobile == State.CONNECTED||mobile==State.CONNECTING)
return;
if(wifi == State.CONNECTED||wifi==State.CONNECTING)
return;
showTips();
}

private void showTips()
{
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setIcon(android.R.drawable.ic_dialog_alert);
    builder.setTitle("没有可用网络");
    builder.setMessage("当前网络不可用,是否设置网络?");
    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // 如果没有网络连接,则进入网络设置界面
            startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
        }
    });
    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            MainActivity.this.finish();
        }
    });
    builder.create();
    builder.show();
}
//Handler
Handler handler = new Handler()
{
    public void handleMessage(Message msg)
    {
        switch(msg.what)
        {
        case 0:
            mDialog.cancel();

            Toast.makeText(getApplicationContext(), "登录成功!", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
            break;
        case 1:
            mDialog.cancel();
            Toast.makeText(getApplicationContext(), "密码错误", Toast.LENGTH_SHORT).show();
            break;
        case 2:
            mDialog.cancel();
            Toast.makeText(getApplicationContext(), "URL验证失败", Toast.LENGTH_SHORT).show();
            break;

        }

    }
};

//LoginThread线程类
class LoginThread implements Runnable
{

    @Override
    public void run() {
        String username = inputUsername.getText().toString();
        String password = inputPassword.getText().toString();    
        boolean checkstatus = sp.getBoolean("checkstatus", false);
        if(checkstatus)
        {
             //获取已经存在的用户名和密码
            String realUsername = sp.getString("username", "");
            String realPassword = sp.getString("password", "");
            if((!realUsername.equals(""))&&!(realUsername==null)||(!realPassword.equals(""))||!(realPassword==null))
            {
                if(username.equals(realUsername)&&password.equals(realPassword))
                {
                    username = inputUsername.getText().toString();
                    password = inputPassword.getText().toString();
                }
            }
        }else
        {
            password = md5(password);
        }
        System.out.println("username="+username+":password="+password);

        //URL合法,但是这一步并不验证密码是否正确
        boolean loginValidate = loginServer(username, password);
        System.out.println("----------------------------bool is :"+loginValidate+"----------response:"+responseMsg);
        Message msg = handler.obtainMessage();
        if(loginValidate)
        {
            if(responseMsg.equals("success"))
            {
                msg.what = 0;
                handler.sendMessage(msg);
            }else
            {
                msg.what = 1;
                handler.sendMessage(msg);
            }

        }else
        {
            msg.what = 2;
            handler.sendMessage(msg);
        }
    }

}


/**
 * MD5单向加密,32位,用于加密密码,因为明文密码在信道中传输不安全,明文保存在本地也不安全  
 * @param str
 * @return
 */

public static String md5(String str)

{

MessageDigest md5 = null;

try

{

md5 = MessageDigest.getInstance("MD5");

}catch(Exception e)

{

e.printStackTrace();

return "";

}

    char[] charArray = str.toCharArray();  
    byte[] byteArray = new byte[charArray.length];  

    for(int i = 0; i < charArray.length; i++)  
    {  
        byteArray[i] = (byte)charArray[i];  
    }  
    byte[] md5Bytes = md5.digest(byteArray);  

    StringBuffer hexValue = new StringBuffer();  
    for( int i = 0; i < md5Bytes.length; i++)  
    {  
        int val = ((int)md5Bytes[i])&0xff;  
        if(val < 16)  
        {  
            hexValue.append("0");  
        }  
        hexValue.append(Integer.toHexString(val));  
    }  
    return hexValue.toString();  
}  

}

1个回答

cj6585256
cj6585256   2013.07.31 10:20

出现什么问题你都没说啊?

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!