资讯专栏INFORMATION COLUMN

IDEA后台与安卓数据交互

Binguner / 2226人阅读

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

实现功能: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

相关文章

  • 深入探讨安卓UI线程子线程交互5大设计

    摘要:在程序运行的时候就被创建,是一个当中的主线程,主要是负责控制界面的显示更新和控件交互。为了解决这个问题,下面将探讨这线程于子线程之间的五种交互方式。运行在线程,主要目的是为后台线程的运行做准备。然后在线程中创建该类必须在线程中创建。 什么是UI线程 在一个Android 程序开始运行的时候,会单独启动一个Process。默认的情况下,所有这个程序中的Activity或者Service(...

    Alan 评论0 收藏0
  • 快速激发灵感的7个安卓应用模板

    摘要:如果你想知道在安卓应用中是如何缓存音频的,那么这个模板是你不容错过的选择。在没有案例的情况下,安卓模板显示了一些可用到的功能,例如添加,更新和查看产品,当库存过低时能通知用户。 Restaurant Finder 该模板拥有丰富的功能,它甚至包含了一个部署到服务器后台的就绪功能。该应用程序允许用户搜索附近的餐厅,阅读评论并在社交媒体进行分享,它还具有通过电子邮件或短信进行预定的功能。 ...

    asoren 评论0 收藏0
  • Android之应用市场排行榜、上架、首发

    摘要:文章大纲一应用市场排行榜介绍二应用市场上架介绍三应用市场首发介绍四参考文档一应用市场排行榜介绍艾媒咨询权威发布中国移动应用商店市场监测报告。应用上架必须要提交阿里的保证函。应用首发申请提交后,工作人员将在个工作文章大纲 一、应用市场排行榜介绍二、应用市场上架介绍三、应用市场首发介绍四、参考文档   一、应用市场排行榜介绍   iiMedia Research(艾媒咨询)权威发布...

    岳光 评论0 收藏0
  • 安卓App测试简析

    摘要:安卓调试桥简介即,他是提供的一个通用的调试工具,借助这个工具,我们可以很好的调试开发的程序,在安装的的开发包目录下。 安卓系统知识简介1.1安卓系统架构: 1、应用程序层 2、应用程序框架层 3、系统运行库库层 4、系统内核层 1.2安卓权限系统: Android操作系统其实是一个多用户的linux操作系统,每个android应用使用不同的用户,运行在自己的安全沙盘里。系统为所有的文件...

    KnewOne 评论0 收藏0
  • android代码 - 收藏集 - 掘金

    摘要:最新最全的开源项目合集掘金是由整理并维护的安卓相关开源项目库集合。源码地址应用瘦身,从到掘金,大家好,我是。注意,如果标题带有英文,说明官方还没有翻译成中一行代码解决闪屏页广告页篇掘金闪屏页或者广告页在众多里是比较常见的。 最新最全的 Android 开源项目合集 - Android - 掘金awesome-github-android-ui 是由OpenDigg整理并维护的安卓UI相...

    tuniutech 评论0 收藏0

发表评论

0条评论

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