iT邦幫忙

0

Android Studio 連接phpmyadmin

  • 分享至 

  • xImage

Yes

之前跟著影片做,然後修改成自己需要的格式
但是不知道為甚麼沒辦法成功輸入資料,一打開就閃退 看不出來哪裡有問題

程式碼:

MainActivity.java

package com.example.connecttest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
Context context=this;
EditText account,password,name,address,phone,birthday;
WebView webview;
String url="http://localhost/Connect_php/";
CookieManager cookeManager;
String cookieStr,id_text;
ListView LV1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskWrites().detectNetwork().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedClosableObjects().detectLeakedSqlLiteObjects().penaltyDeath().penaltyLog().build());

        Wcookie(context);
        Handler myHandler=new Handler();
        myHandler.postDelayed(runTimerStop,15000);
        if(cookieStr!=null){
            myHandler.removeCallbacks(runTimerStop);
        }

        LV1=(ListView)findViewById(R.id.LV1);
        account=(EditText)findViewById(R.id.editText_account);
        password=(EditText)findViewById(R.id.editText_password);
        name=(EditText)findViewById(R.id.editText_name);
        birthday=(EditText)findViewById(R.id.editText_birthday);
        address=(EditText)findViewById(R.id.editText_address);
        phone=(EditText)findViewById(R.id.editText_phone);

        //新增資料
        Button btn_save=(Button)findViewById(R.id.btn_save);
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] et0=new String[]{account.getText().toString(),password.getText().toString(),name.getText().toString(),birthday.getText().toString(),address.getText().toString(),phone.getText().toString()};
                Inphp.Interting(et0,cookieStr,url);
                select(null);
            }
        });



        //選取資料才能更新
        LV1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
//                TextView te0=(TextView)view.findViewById(R.id.text0);
//                id_text=te0.getText().toString();
                TextView te1=(TextView) view.findViewById(R.id.text0);
                account.setText(te1.getText());
                TextView te2=(TextView) view.findViewById(R.id.text1);
                password.setText(te2.getText());
                TextView te3=(TextView) view.findViewById(R.id.text2);
                name.setText(te3.getText());
                TextView te4=(TextView) view.findViewById(R.id.text3);
                birthday.setText(te4.getText());
                TextView te5=(TextView) view.findViewById(R.id.text4);
                address.setText(te5.getText());
                TextView te6=(TextView) view.findViewById(R.id.text5);
                phone.setText(te6.getText());
            }
        });

        //更新
        Button btn_update=(Button) findViewById(R.id.btn_update);
        btn_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] et0=new String[]{account.getText().toString(),password.getText().toString(),name.getText().toString(),birthday.getText().toString(),address.getText().toString(),phone.getText().toString()};
                Upphp.updateing(et0,cookieStr,url);
                select(null);
            }
        });

        //刪除
        Button btn_delete=(Button)findViewById(R.id.btn_delete);
        btn_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] et0=new String[]{id_text};
                Delphp.Deling(et0,cookieStr,url);
                select(null);
            }
        });

    }

    private void Wcookie(Context context) {

        CookieSyncManager.createInstance(context);
        cookeManager=CookieManager.getInstance();
        webview=new WebView(context);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                cookeManager.setAcceptCookie(true);
                cookieStr=cookeManager.getCookie(url);
            }
        });
        webview.loadUrl(url);
        webview.clearHistory();
        webview.clearCache(true);

        cookeManager.removeAllCookie();
        cookeManager.removeSessionCookie();

    }

    private Runnable runTimerStop=new Runnable() {
        @Override
        public void run() {
            select(null);
        }
    };



//顯示資料
public void select(String id) {
    try {
        String r=DBphp.DBstring(id,cookieStr,url);
        JSONArray jsonArray=new JSONArray(r);
        List<Map<String,Object>> items=new ArrayList<Map<String, Object>>();

        for(int i = 0; i<jsonArray.length();i++){
            JSONObject jsonData=jsonArray.getJSONObject(i);
            Map<String,Object> item=new HashMap<String,Object>();
            item.put("Account_member", jsonData.getString("Account_member"));
            item.put("Password_member", jsonData.getString("Password_member"));
            item.put("Name_member", jsonData.getString("Name_member"));
            item.put("Birthday_member", jsonData.getString("Birthday_member"));
            item.put("Address_member", jsonData.getString("Address_member"));
            item.put("Phone_member", jsonData.getString("Phone_member"));
            items.add(item);//新增到items
        }
        SimpleAdapter SA=new SimpleAdapter(context, items, R.layout.list_text,new String[]{"Account_member","Password_member","Name_member","Birthday_member","Address_member","Phone_member"},new int[]{R.id.text0,R.id.text1,R.id.text2,R.id.text3,R.id.text4,R.id.text5});
        LV1.setAdapter(SA);

    } catch (Exception e) {
        Log.e("log_tag=",e.toString());
    }
}
}

DBphp.java

package com.example.connecttest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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 org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class DBphp {

    private static HttpClient hC;
    private static HttpPost hP;

    public static String DBstring(String i,String Wcook,String url){

        String result="錯誤";
        try{
            hC=new DefaultHttpClient();
            hP=new HttpPost(url+"index.php");
            hP.addHeader("Cookie",Wcook+";exprise=Thu,31-Dec-37 23:55:55 GMT; path=/");

            ArrayList<NameValuePair> params=new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("Account_member",i));
            hP.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

            HttpResponse hR=hC.execute(hP);
            HttpEntity hE=hR.getEntity();
            InputStream inputStream=hE.getContent();
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream, HTTP.UTF_8),8);
            StringBuilder builder=new StringBuilder();
            String line=null;
            while((line=bufferedReader.readLine())!=null){
                builder.append(line+"/n");

            }
            inputStream.close();
            result=builder.toString();

        }catch(Exception e){
            result=e.toString();
        }finally {
            hC.getConnectionManager().shutdown();
        }

        return result;

    }
}

Delphp.java

package com.example.connecttest;

import org.apache.http.HttpResponse;
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 org.apache.http.protocol.HTTP;

import java.util.ArrayList;

public class Delphp {

    private static HttpClient hC;
    private static HttpPost hP;

    public static void Deling(String[] i,String Wcook, String url){
        try{
            hC=new DefaultHttpClient();
            hP=new HttpPost(url+"Del_text1.php");
            System.out.println("是否取得cookie="+Wcook);
            hP.addHeader("Cookie",Wcook+";expires=Thu, 31-Dec-37 23:55:55 GMT; path=/");

            ArrayList<NameValuePair> params=new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("Account_member",i[0]));
            hP.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse hR=hC.execute(hP);
            hR.getEntity();

        }catch(Exception e){
            System.out.print(e.toString());
        }
    }
}

Upphp.java

package com.example.connecttest;

import org.apache.http.HttpResponse;
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 org.apache.http.protocol.HTTP;

import java.util.ArrayList;

public class Upphp {

    private static HttpClient hC;
    private static HttpPost hP;

    public static void updateing(String[] i,String Wcook, String url){
        try{
            hC=new DefaultHttpClient();
            hP=new HttpPost(url+"Updata_text1.php");
            System.out.println("是否取得cookie="+Wcook);
            hP.addHeader("Cookie",Wcook+";expires=Thu, 31-Dec-37 23:55:55 GMT; path=/");

            ArrayList<NameValuePair>params=new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("Account_member",i[0]));
            params.add(new BasicNameValuePair("Password_member",i[1]));
            params.add(new BasicNameValuePair("Name_member",i[2]));
            params.add(new BasicNameValuePair("Birthday_member",i[3]));
            params.add(new BasicNameValuePair("Address_member",i[4]));
            params.add(new BasicNameValuePair("Phone_member",i[5]));
            hP.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse hR=hC.execute(hP);
            hR.getEntity();

        }catch(Exception e){
            System.out.print(e.toString());
        }
    }
}

Inphp.java

package com.example.connecttest;

import org.apache.http.HttpResponse;
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 org.apache.http.protocol.HTTP;

import java.net.HttpCookie;
import java.util.ArrayList;
import java.util.jar.Attributes;

public class Inphp {
    private static HttpClient hC;
    private static HttpPost hP;
    public static void Interting(String[] i, String Wcook, String url){
        String result="錯誤";
        try{
            hC=new DefaultHttpClient();
            hP=new HttpPost(url+"Inter_text1.php");
            System.out.println("是否取得cookie="+Wcook);
            hP.addHeader("Cookie",Wcook+";expires=Thu, 31-Dec-37 23:55:55 GMT; path=/");

            ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("Account_member",i[0]));
            params.add(new BasicNameValuePair("Password_member",i[1]));
            params.add(new BasicNameValuePair("Name_member",i[2]));
            params.add(new BasicNameValuePair("Birthday_member",i[3]));
            params.add(new BasicNameValuePair("Address_member",i[4]));
            params.add(new BasicNameValuePair("Phone_member",i[5]));

            hP.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse hR=hC.execute(hP);
            hR.getEntity();

        }catch(Exception e){
            System.out.print(e.toString());
        }finally {
            hC.getConnectionManager().shutdown();
        }
    }
}

Del_text1.php

<?php
	require_once("SQL_data.php");
	$insert_new1=isset($_POST["Account_member"])<>NULL?$_POST["Account_member"]:"";


	mysql_select_db($database,$GD);
	$sql=sprintf("DELETE FROM member WHERE Account_member='%s'",$insert_new1);

	$Result=mysql_query($sql,$GD) or die(mysql_error());
    
	mysql_close();
	exit();
?>

Index.php

<?php
	require_once("SQL_data.php");
	$sql="select * from member  order by Account_member ";
	mysql_select_db($database,$GD);
	$Result=mysql_query($sql,$GD) or die(mysql_error());

	while($r = mysql_fetch_assoc($Result))
	$output[]=$r;
	header('Content-type: application/json; charset=utf-8');
	print(json_encode($output,JSON_UNESCAPED_UNICODE));//JSON_UNESCAPED_UNICODE為中文不轉成unicode碼
	mysql_close();
	exit();
?>

Inter_text1.php

<?php
//echo("finish"); //測試用
	require_once("SQL_data.php");
	$insert_new1=isset($_POST["Account_member"])<>NULL?$_POST["Account_member"]:"ddddd";
	$insert_new2=isset($_POST["Password_member"])<>NULL?$_POST["Password_member"]:"0";
	$insert_new3=isset($_POST["Name_member"])<>NULL?$_POST["Name_member"]:"0";
	$insert_new4=isset($_POST["Birthday_member"])<>NULL?$_POST["Birthday_member"]:"0";
	$insert_new5=isset($_POST["Address_member"])<>NULL?$_POST["Address_member"]:"0";
	$insert_new6=isset($_POST["Phone_member"])<>NULL?$_POST["Phone_member"]:"0";

//https://devildemon20100423.blogspot.com/2018/11/android-studio-mysqllistview.html
	mysql_select_db($database,$GD);
	$sql=sprintf("INSERT INTO member(Account_member,Password_member,Name_member,Birthday_member,Address_member,Phone_member)
	VALUES ('%s','%s','%s',%s,'%s','%s')",$insert_new1,$insert_new2,$insert_new3,$insert_new4,$insert_new5,$insert_new6);

	$Result=mysql_query($sql,$GD) or die(mysql_error());

	mysql_close();
	exit();
?>

SQL_data.php

<?php
	$hostname="localhost";
	$username="Max";
	$password="max650915";
	$database="pressure_helper";
	$GD=mysqli_connect($hostname,$username,$password) or trigger_error(mysqli_error(),E_USER_ERROR);
	//$GD=mysqli_connect($hostname,$username,$password);
	//UTF8 編碼問題如下
	mysqli_query($GD,"SET NAMES UTF8");
	mysqli_query($GD,"SET CHARACTER_SET_CLIENT='utf8'");
	mysqli_query($GD,"SET CHARACTER_SET_RESULTS='utf8'");
?>

Updata_text1.php

<?php
	require_once("SQL_data.php");
	$insert_new1=isset($_POST["Account_member"])<>NULL?$_POST["Account_member"]:"NULL";
	$insert_new2=isset($_POST["Password_member"])<>NULL?$_POST["Password_member"]:"0";
	$insert_new3=isset($_POST["Name_member"])<>NULL?$_POST["Name_member"]:"0";
	$insert_new4=isset($_POST["Birthday_member"])<>NULL?$_POST["Birthday_member"]:"0";
	$insert_new5=isset($_POST["Address_member"])<>NULL?$_POST["Address_member"]:"0";
	$insert_new6=isset($_POST["Phone_member"])<>NULL?$_POST["Phone_member"]:"0";

	mysql_select_db($database,$GD);
	$sql=sprintf("UPDATE member SET Account_member='%s',Password_member='%s',Name_member='%s',Birthday_member=%s,Address_member='%s',Phone_member='%s' WHERE Account_member='%s'",$insert_new0,$insert_new1,$insert_new2,$insert_new3,$insert_new4,$insert_new6);

	$Result=mysql_query($sql,$GD) or die(mysql_error());

	mysql_close();
	exit();
?>
GHH iT邦新手 1 級 ‧ 2022-06-06 16:18:07 檢舉
錯誤訊息
max_0814 iT邦新手 5 級 ‧ 2022-06-06 17:54:35 檢舉
沒有任何錯誤訊息 只有閃退
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
海綿寶寶
iT邦大神 1 級 ‧ 2022-06-07 17:58:09

我試著執行程式
但是缺少 layout xml
就放棄了

max_0814 iT邦新手 5 級 ‧ 2022-06-08 14:09:08 檢舉

了解

我要發表回答

立即登入回答