连接云数据库我想了一下,自己目前就掌握了两种方法,一种是线程,一种是异步。那么哪种方法比较好呢。其实是异步我个人觉得更好,其实异步的连接也是一种线程的方式,不过不够明显。我写了一个登陆的demo.
先说一下单纯的线程方式:
package com.example.myphone;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView name;
private TextView psd;
private Button login;
private boolean isLogInSuccess;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(TextView) findViewById(R.id.name);
psd=(TextView) findViewById(R.id.password);
login=(Button) findViewById(R.id.login);
name.setText("123");
psd.setText("123");
login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new LoginThread().start();
}
});
}
Handler handler = new Handler() {
@SuppressWarnings({ "rawtypes" })
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
List resultList = new ArrayList();
resultList = (List) msg.obj;
System.out.println("resultList-----"+resultList);
System.out.println("size:"+resultList.size());
String returnResult = resultList.get(0).toString();
System.out.println("returnResult----"+returnResult);
if (returnResult != null && !returnResult.equals("1")) { // ?
String resultUserName = resultList.get(1).toString().trim();
System.out.println("---resultUserName-----"
+ resultUserName);
System.out.println("---- result:" + returnResult + "---");
System.out.println(returnResult.length());
String s = "login_succeed";
System.out.println("s:" + s.length());
if (returnResult.contains("succeed")) {
isLogInSuccess = true;
System.out.println(isLogInSuccess);
} else {
Toast.makeText(MainActivity.this,
"您输入的用户名和密码不匹配,请核