资讯专栏INFORMATION COLUMN

IDEA后台与安卓数据交互

Binguner / 2456人阅读

摘要:实现功能发数据给后台,后台根据获取到的数据查询数据库并将对应的数据发回客户端显示在界面开发工具,,端以下为需要新建或者修改的文件,以便新手学习客户端运行示例代码展示登录用户名输入框登录密码输入框登录按钮

实现功能:Android app发ID数据给IDEA
后台,后台根据获取到的ID数据查询数据库并将对应的数据发回客户端显示在app界面

开发工具:IDEA,Android studio,MySQL

Android端:(以下为需要新建或者修改的文件,以便新手学习)
Java:MainActivity
GuestToServer
layout:activity_main
build.gradle(app)
AndoidManifest.xml
客户端运行示例:

代码展示:

import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;import org.json.JSONException;import org.json.JSONObject;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;public class MainActivity extends AppCompatActivity {    //登录用户名输入框    private EditText et_username;    //登录密码输入框    private EditText et_password;    //登录按钮    private EditText id;    private Button bt_login;    private TextView tv;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //获取组件        init();        //对登录按钮的点击监控        bt_login.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // Toast.makeText(LoginActivity.this, "登录成功!", Toast.LENGTH_LONG).show();                final Handler myHandler = new Handler(){                    public void handleMessage(Message msg){                        String responseResult = (String)msg.obj;                        // Toast.makeText(LoginActivity.this, "登录成功!", Toast.LENGTH_LONG).show();                        //登录成功               System.out.println("response"+responseResult);                       try{                        JSONObject root = new JSONObject(responseResult);                           String userName = root.getString("userName");                           tv.append("userName"+"="+userName+"/n");                       }                       catch (JSONException e) {                           e.printStackTrace();                       }                        if(responseResult.equals("" +                                "true")){  Toast.makeText(com.example.myapplication.MainActivity.this, "登录成功!", Toast.LENGTH_LONG).show();                        }                        //登录失败                        else{                 Toast.makeText(com.example.myapplication.MainActivity.this, "登录失败!", Toast.LENGTH_LONG).show();                        }                    }                };                new Thread(new Runnable() {                    @Override                    public void run() {                        GuestToServer guestToServer = new GuestToServer();                        try {                            //如果是调用GuestToServer中验证用户名与密码的方法则使用下面句                           //String result = guestToServer.doPost(et_username.getText().toString().trim(), et_password.getText().toString().trim());                            String result = guestToServer.doPost(id.getText().toString().trim());                            Message msg = new Message();                         msg.obj = result;                            myHandler.sendMessage(msg);                        } catch (IOException e) {                            e.printStackTrace();                        }                    }                }).start();            }        });    }    /**     * 获取组件     */    private void init() {        et_username = (EditText)findViewById(R.id.et_username);        et_password = (EditText)findViewById(R.id.et_password);        id= (EditText)findViewById(R.id.id);        bt_login = (Button)findViewById(R.id.bt_login);        tv = (TextView) findViewById(R.id.tv);//获取到TextView组件    }}
 GuestToServer
import android.util.Log;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;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 java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.util.ArrayList;import java.util.List;public class GuestToServer {    //localhost为本地主机IP地址/login为idea后台项目名    private String url = "http://localhost:8080/login";    //服务器返回的结果//    String result = "";    /**     * 使用Post方式向服务器发送请求并返回响应     *     * //如果使用验证用户名及密码的方法那么使用public String doPost(String username, String password) throws IOException {     * //且放出下面两句参数设置    // * @param username 传递给服务器的username   //  * @param password 传递给服务器的password     *  @param id 传递给服务器的id     * @return     */    public String doPost(String id) throws IOException {        HttpClient httpClient = new DefaultHttpClient();        HttpPost httpPost = new HttpPost(url);        NameValuePair param3 = new BasicNameValuePair("id", id);        List<NameValuePair> params = new ArrayList<NameValuePair>();        params.add(param3);        //将参数包装如HttpEntity中并放入HttpPost的请求体中        HttpEntity httpEntity = new UrlEncodedFormEntity(params, "GBK");        httpPost.setEntity(httpEntity);        HttpResponse httpResponse = httpClient.execute(httpPost);        //如果响应成功        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {            //得到信息体            HttpEntity entity = httpResponse.getEntity();            InputStream inputStream = entity.getContent();            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));            String readLine = null;            while ((readLine = br.readLine()) != null) {                result += readLine;            }            inputStream.close();            return result;        }        //响应失败        else {            return "false";        }    }    /*    public String doPost(String username, String password) throws IOException {        HttpClient httpClient = new DefaultHttpClient();        HttpPost httpPost = new HttpPost(url);        //将username与password参数装入List中        NameValuePair param1 = new BasicNameValuePair("username", username);        NameValuePair param2 = new BasicNameValuePair("password", password);        List params = new ArrayList();        params.add(param1);        params.add(param2);        //将参数包装如HttpEntity中并放入HttpPost的请求体中        HttpEntity httpEntity = new UrlEncodedFormEntity(params, "GBK");        httpPost.setEntity(httpEntity);        HttpResponse httpResponse = httpClient.execute(httpPost);        //如果响应成功        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {            //得到信息体            HttpEntity entity = httpResponse.getEntity();            InputStream inputStream = entity.getContent();            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));            String readLine = null;            while ((readLine = br.readLine()) != null) {                result += readLine;            }            inputStream.close();            return result;        }        //响应失败        else {            return "false";        }    }*/}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_login"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <TextView        android:text="登录界面"        android:textSize="10dp"        android:textColor="#003399"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/textView1"        android:gravity="center_horizontal"        android:layout_margin="10dp"/>    <TextView        android:text="用户名"        android:textSize="20dp"        android:textColor="#CC0000"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/textView2"        android:layout_margin="10dp"/>    <EditText        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:inputType="textPersonName"        android:ems="10"        android:id="@+id/et_username"        android:textSize="10dp"        android:textColor="#003399"        android:layout_margin="10dp"/>    <TextView        android:text="密码 "        android:textSize="20dp"        android:textColor="#CC0000"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/textView3"        android:layout_margin="10dp"/>    <EditText        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:inputType="textPersonName"        android:ems="10"        android:id="@+id/et_password"        android:textSize="10dp"        android:textColor="#003399"        android:layout_margin="10dp"/>    <TextView        android:text="ID "        android:textSize="20dp"        android:textColor="#CC0000"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/idtextview"        android:layout_margin="10dp"/>    <EditText        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:inputType="textPersonName"        android:ems="10"        android:id="@+id/id"        android:textSize="10dp"        android:textColor="#003399"        android:layout_margin="10dp"/>    <Button        android:text="登录"        android:textSize="20dp"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/bt_login"        android:layout_marginLeft="20dp"        android:layout_marginRight="20dp"        android:background="#0099FF"/>    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/tv"/></LinearLayout>

如果项目出现报错,记得检查报错日志,一般是apache没有导入
在build.gradle里加入这行
useLibrary’org.apache.http.legacy’

由于版本不同,有些需要在manifest文件中的appication加入

<application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:roundIcon="@mipmap/ic_launcher_round"        android:supportsRtl="true"        android:theme="@style/AppTheme"        android:usesCleartextTraffic="true">        <uses-library android:name="org.apache.http.legacy" android:required="false"/>

至此,Android app搭建完毕,可试运行
IDEA后台项目搭建:
可参考上一篇小程序后台,共用一个后台与数据库无需更改

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/122987.html

相关文章

发表评论

0条评论

最新活动
阅读需要支付1元查看
<