donglun2024 2018-07-24 19:37
浏览 142

Android登录PostgreSQL数据库

I wrote a login page with android studio. My first database was MySQL and the app worked right. But I tried to use PostgreSQL database and change the php code to postgres database to

> $conn = new PDO("pgsql:dbname=$dbname;host=$servername", $username,
> $password);

and i did not change any java code. and now I can't connect to the database and unfortunately I do not receive any report and error from app. But I can reach the database through browser.

Java Login Class:

    package org.schools.loginregister;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class LoginActivity extends AppCompatActivity {

    public static final int CONNECTION_TIMEOUT=10000;
    public static final int READ_TIMEOUT = 15000;

    private EditText benutzername;
    private EditText passwort;
    private Button einloggenBtn;


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

        benutzername = (EditText) findViewById(R.id.benutzername);
        passwort = (EditText) findViewById(R.id.passwort);
        einloggenBtn = (Button) findViewById(R.id.einloggenbtn);

        einloggenBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String ibenutzername = benutzername.getText().toString();
                final String ipasswort = passwort.getText().toString();

                new AsyncLogin().execute(ibenutzername,ipasswort);
            }
        });
    }



    private class AsyncLogin extends AsyncTask<String,String,String>{
        ProgressDialog pdLoading = new ProgressDialog(LoginActivity.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute(){
            super.onPreExecute();

            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();
        }

        @Override
        protected String doInBackground(String... params) {
            try {

                // Enter URL address where your php file resides
                url = new URL("http://192.168.241.1//android_user_api//login.inc.php");

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return "exception";
            }
            try {
                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection)url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("POST");

                // setDoInput and setDoOutput method depict handling of both send and receive
                conn.setDoInput(true);
                conn.setDoOutput(true);

                // Append parameters to URL
                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("benutzername", params[0])
                        .appendQueryParameter("passwort", params[1]);
                String query = builder.build().getEncodedQuery();

                // Open connection for sending data
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();
                conn.connect();

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return "exception";
            }

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return(result.toString());

                }else{

                    return("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return "exception";
            } finally {
                conn.disconnect();
            }


        }

        @Override
        protected void onPostExecute(String result) {

            //this method will be running on UI thread

            pdLoading.dismiss();

            if(result.equalsIgnoreCase("true"))
            {
                /* Here launching another activity when login successful. If you persist login state
                use sharedPreferences of Android. and logout button to clear sharedPreferences.
                 */

                Intent intent = new Intent(LoginActivity.this,StartActivity.class);
                startActivity(intent);
                LoginActivity.this.finish();

            }else if (result.equalsIgnoreCase("false")){

                // If username and password does not match display a error message
                Toast.makeText(LoginActivity.this, "Invalid email or password", Toast.LENGTH_LONG).show();

            } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

                Toast.makeText(LoginActivity.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();

            }
            }
        }
    }

The PHP code for Postgresql:

    <?php

$servername = "127.0.0.1";
$username = "postgres";
$password = "12345678";
$dbname = "postgres";

try {
        $conn = new PDO("pgsql:dbname=$dbname;host=$servername", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
catch(PDOException $e)
    {
        die("OOPs something went wrong");
    }

?>

second php file:

<?php

     include 'config.inc.php';

     // Check whether username or password is set from android  
     if(isset($_POST['benutzername']) && isset($_POST['passwort']))
     {
          // Innitialize Variable
          $result='';
          $benutzername = $_POST['benutzername'];
          $passwort = $_POST['passwort'];

          // Query database for row exist or not
          $sql = 'SELECT * FROM user WHERE  benutzername = :benutzername AND passwort = :passwort;';
          $stmt = $conn->prepare($sql);
          $stmt->bindParam(':benutzername', $benutzername, PDO::PARAM_STR);
          $stmt->bindParam(':passwort', $passwort, PDO::PARAM_STR);
          $stmt->execute();
          if($stmt->rowCount())
          {
             $result="true";    
          }  
          elseif(!$stmt->rowCount())
          {
                $result="false";
          }

          // send result back to android
          echo $result;
    }

?>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 程序不包含适用于入口点的静态Main方法
    • ¥15 素材场景中光线烘焙后灯光失效
    • ¥15 请教一下各位,为什么我这个没有实现模拟点击
    • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
    • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 slam rangenet++配置
    • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
    • ¥15 ubuntu子系统密码忘记