TingmengA通过本文主要向大家介绍了数据库,android,http等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.pets.main.BaseApp;
import com.pets.main.MainActivity;
import com.pets.main.R;
import com.pets.utils.DialogUtil;
import com.pets.utils.JSONParser;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("deprecation")
public class LoginActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialogl;
JSONParser jsonParser = new JSONParser();
EditText inputLogName;
EditText inputLogPassword;
String username0,password0;
boolean available;
private static String url_up = "http://localhost/login.php";
private static final String TAG_MESSAGE = "message";
private static final String TAG_SUCCESS = "success";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);// 不显示程序的标题栏
setContentView(R.layout.activity_login);
// Edit Text
inputLogName = (EditText) findViewById(R.id.username);
inputLogPassword = (EditText) findViewById(R.id.password);
// Create button
Button btnlogin = (Button) findViewById(R.id.button_login);
// button click event
/**
* 首先检查网络连接状况,testConnectivityManager();
*/
testConnectivityManager();
if(available){
btnlogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// creating new product in background thread
username0 = inputLogName.getText().toString();
password0 = inputLogPassword.getText().toString();
if(validate()&&validate1()){
/**
* 开启异步进程,进行数据传输
*/
new Up().execute();
}
}
});
}
Button to_regist=(Button)findViewById(R.id.button_to_regist);
to_regist.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(LoginActivity.this,RegistActivity.class));
}
});
}
private boolean validate(){
String user = inputLogName.getText().toString().trim();
if (user.equals("")){
DialogUtil.showDialog(this, "用户名不能为空", false);
return false;
}
return true;
}
private boolean validate1(){
String user = inputLogPassword.getText().toString().trim();
if (user.equals("")){
DialogUtil.showDialog(this, "密码不能为空", false);
return false;
}
return true;
}
public void testConnectivityManager() {
ConnectivityManager connManager = (ConnectivityManager) this
.getSystemService(CONNECTIVITY_SERVICE);
// 获取代表联网状态的NetWorkInfo对象
NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
// 获取当前的网络连接是否可用
available = networkInfo.isAvailable();
if(available){
Log.i("通知", "当前的网络连接可用");
}
else{
Log.i("通知", "当前的网络连接不可用");
}
}
/**
* 在后台运行的异步进程,进行数据交互
* */
class Up extends AsyncTask<String, String, String> {
/**
* 在后台进程开始之前,显示 dialog
* */
@Override
protected void onPreExecute() {//异步进程
super.onPreExecute();
/**
* pDialogl是进度条会话框
* 显示进度会话框
*/
pDialogl = new ProgressDialog(LoginActivity.this);
pDialogl.setMessage("...登录中...");
pDialogl.setIndeterminate(false);
pDialogl.setCancelable(true);
pDialogl.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("username", username0));
params1.add(new BasicNameValuePair("password", password0));
// getting JSON Object
// Note that create product url accepts POST method
System.out.println("request php json");
try{
JSONObject json = jsonParser.makeHttpRequest(url_up, "POST", params1);
System.out.println("exit php json");
String message = json.getString(TAG_MESSAGE);
String suce=json.getString(TAG_SUCCESS);
System.out.println("get message "+message+" "+suce);
System.out.println("it was not run! ");
if(suce.equals("1")){
Intent intent=new Intent(LoginActivity.this,MainActivity.class);
BaseApp.setUser(username0);
BaseApp.setState("1");
startActivity(intent);
}
return message;
}catch(Exception e){
e.printStackTrace();
return "";
}
// check for success tag
}
/**
* After completing background task Dismiss the progress dialog
* **/
@SuppressLint("ShowToast")
protected void onPostExecute(String message) {
pDialogl.dismiss();
//message 为接收doInbackground的返回值
System.out.println("onPostExecute"+message);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
}
Json处理
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
@SuppressWarnings("deprecation")
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
// Making HTTP request
try {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
JSONTokener(sb.toString());
sb.append(line + "\n");
}
is.close();
json = sb.toString();
System.out.println("makeHttpRequest"+json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
Log.d("json", json.toString());
}
try {
jObj = new JSONObject(json);
System.out.println("new json"+json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
private String JSONTokener(String in) {
// TODO Auto-generated method stub
if (in != null && in.startsWith("\ufeff")) {
in = in.substring(1);
}
return in;
}
}