安卓手機(jī)app開發(fā)-調(diào)用網(wǎng)絡(luò)接口寫入mysql數(shù)據(jù)---kotlin版

花了點(diǎn)時間寫了一個入門級數(shù)據(jù)讀寫操作,是kotlin版本。教程沒有涉及json的第三方解析,沒有MVVM模式操作數(shù)據(jù)庫,所以代碼很適合了解手機(jī)開發(fā)的app是如何操作數(shù)據(jù)庫的入門者閱讀。

? 教程是采用android studio最新版下編寫的,項(xiàng)目是用底部導(dǎo)航欄的系統(tǒng)默認(rèn)模板搭建的,很容易閱讀和理解。寫入是通過遠(yuǎn)程php的接口寫入到數(shù)據(jù)庫的沒有用kotlin實(shí)現(xiàn),因?yàn)橛胮hp實(shí)現(xiàn)后端數(shù)據(jù)庫操作是非常有優(yōu)勢的,編寫代碼快捷省事。完整源碼打包到? 專業(yè)開發(fā)網(wǎng) http://www.zhuanyekaifa.com/datarwite.rar 去下載吧


看幾個效果圖:


項(xiàng)目結(jié)構(gòu)圖:紅框部分是著重改寫的部分

2 , 布局文件

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android=“http://schemas.android.com/apk/res/android”

xmlns:app=“http://schemas.android.com/apk/res-auto”

xmlns:tools=“http://schemas.android.com/tools”

android:layout_width=“match_parent”

android:layout_height=“match_parent”

tools:context=".ui.dashboard.DashboardFragment">

<EditText

? ? android:id="@+id/personname"

? ? android:layout_width="wrap_content"

? ? android:layout_height="wrap_content"

? ? android:layout_marginStart="24dp"

? ? android:layout_marginTop="130dp"

? ? android:layout_marginEnd="24dp"

? ? android:ems="10"

? ? android:inputType="textPersonName"

? ? android:text="輸入姓名"

? ? app:layout_constraintEnd_toEndOf="parent"

? ? app:layout_constraintStart_toStartOf="parent"

? ? app:layout_constraintTop_toTopOf="parent" />

<EditText

? ? android:id="@+id/personage"

? ? android:layout_width="wrap_content"

? ? android:layout_height="wrap_content"

? ? android:layout_marginTop="16dp"

? ? android:ems="10"

? ? android:inputType="number"

? ? android:text="輸入年齡"

? ? app:layout_constraintEnd_toEndOf="parent"

? ? app:layout_constraintStart_toStartOf="parent"

? ? app:layout_constraintTop_toBottomOf="@+id/personname" />

<EditText

? ? android:id="@+id/personadd"

? ? android:layout_width="wrap_content"

? ? android:layout_height="wrap_content"

? ? android:layout_marginTop="16dp"

? ? android:ems="10"

? ? android:inputType="textPersonName"

? ? android:text="輸入住址"

? ? app:layout_constraintEnd_toEndOf="parent"

? ? app:layout_constraintStart_toStartOf="parent"

? ? app:layout_constraintTop_toBottomOf="@+id/personage" />

<ImageButton

? ? android:id="@+id/imageButton"

? ? android:layout_width="wrap_content"

? ? android:layout_height="wrap_content"

? ? android:layout_marginTop="16dp"

? ? android:src="@android:drawable/ic_input_add"

? ? app:layout_constraintEnd_toEndOf="parent"

? ? app:layout_constraintStart_toStartOf="parent"

? ? app:layout_constraintTop_toBottomOf="@+id/personadd" />


3.數(shù)據(jù)請求,主要是看是如何請求遠(yuǎn)程數(shù)據(jù)的部分

package com.mykotlin.five_adddata.ui.dashboard

import android.os.Bundle

import android.os.Looper

import android.text.Editable

import android.view.LayoutInflater

import android.view.View

import android.view.ViewGroup

import android.widget.Toast

import androidx.fragment.app.Fragment

import androidx.lifecycle.ViewModelProvider

import com.mykotlin.five_adddata.databinding.FragmentDashboardBinding

import okhttp3.*

import org.json.JSONObject

import java.io.IOException

class DashboardFragment : Fragment() {

private var dashboardViewModel: DashboardViewModel? = null

private var _binding: FragmentDashboardBinding? = null

// This property is only valid between onCreateView and

// onDestroyView.

private val binding get() = _binding!!

override fun onCreateView(

? ? inflater: LayoutInflater,

? ? container: ViewGroup?,

? ? savedInstanceState: Bundle?

? ? ): View? {

? ? dashboardViewModel =

? ? ? ? ViewModelProvider(this).get(DashboardViewModel::class.java)

? ? _binding = FragmentDashboardBinding.inflate(inflater, container, false)

? ? val root: View = binding.root

? ? val pname = binding.personname.text

? ? val page = binding.personage.text

? ? val padd=binding.personadd.text

? ? binding.imageButton.setOnClickListener {

? ? ? ? getAdd(pname,page,padd)

? ? }

? ? return root

}

private fun getAdd(name: Editable, age: Editable, add: Editable){

? ? **val client = OkHttpClient()

? ? var url = "http://www.kuaidian777.com/mydata.php"

? ? val urlAPI: String = url**

? ? val builder = FormBody.Builder()

? ? builder.add("hname", name.toString())

? ? builder.add("hage", age.toString())

? ? builder.add("hadd", add.toString())

? ? val formBody = builder.build()

? ? val request = Request.Builder()

? ? ? ? .method("POST", formBody)

? ? ? ? .url(urlAPI).build()

? ? client.newCall(request).enqueue(object : Callback {

? ? ? ? ? ? override fun onResponse(call: Call, response: Response) {

? ? ? ? ? ? ? ? val result = response.body?.string()

? ? ? ? ? ? ? ? var jstr=""

? ? ? ? ? ? ? ? var myjson= JSONObject(result)

? ? ? ? ? ? ? ? //println("result:" + myjson)

? ? ? ? ? ? ? ? if(myjson.getString("msg")=="ok") {

? ? ? ? ? ? ? ? ? ? Looper.prepare();

? ? ? ? ? ? ? ? ? ? Toast.makeText(context, "輸入寫入成功", Toast.LENGTH_SHORT).show()

? ? ? ? ? ? ? ? ? ? Looper.loop();

? ? ? ? ? ? ? ? }else {

? ? ? ? ? ? ? ? ? ? Looper.prepare();

? ? ? ? ? ? ? ? ? ? Toast.makeText(context, "唉,失敗了", Toast.LENGTH_SHORT).show()

? ? ? ? ? ? ? ? ? ? Looper.loop();

? ? ? ? ? ? ? ? ? ? //println(myjson.getString("msg"))

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? ? ? override fun onFailure(call: Call, e: IOException) {

? ? ? ? ? ? ? ? println("Failed request api :( " + e.message)

? ? ? ? ? ? }

? ? })

}

override fun onDestroyView() {

? ? super.onDestroyView()

? ? _binding = null

}


}

4.點(diǎn)擊 +按鈕后 把數(shù)據(jù)寫入數(shù)據(jù)庫,通過調(diào)用遠(yuǎn)程http://www.kuaidian777.com/mydata.php寫入的

接口內(nèi)容

<? header('Content-Type:application/json; charset=utf-8'); $mysql_server_name = 'localhost'; //改成自己的mysql數(shù)據(jù)庫服務(wù)器?

$mysql_username = '。。。。。'; //改成自己的mysql數(shù)據(jù)庫用戶名

?$mysql_password = '。。。。。'; //改成自己的mysql數(shù)據(jù)庫密碼

?$mysql_database = '。。。。。'; //改成自己的mysql數(shù)據(jù)庫名 $conn=mysqli_connect($mysql_server_name,$mysql_username,$mysql_password,$mysql_database); //連接數(shù)據(jù)庫 //連接數(shù)據(jù)庫錯誤提示

?if (mysqli_connect_errno($conn)) {?

die("連接 MySQL 失敗: " . mysqli_connect_error());?

}?

mysqli_query($conn,"set names utf8"); //數(shù)據(jù)庫編碼格式

?$hname=$_POST["hname"]; $hage=$_POST["hage"];;?

$hadd=$_POST["hadd"];;

?$sql="INSERT INTO `testme`(`hname`, `hage`, `hadd`) VALUES ('".$hname."',".$hage.",'".$hadd."')";?

mysqli_query($conn,$sql);

??>

技術(shù)探討 : qq 2047879076

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容