android - Android 和 MySQL/PHP 数据库连接问题

标签 android mysql connection httpurlconnection

我正在制作一个非常简单的 Android 应用程序,但是当我尝试将其连接到网页时,它不起作用。我已经在互联网上尝试过很多教程,也已经在这里阅读了很多主题,但没有成功。 那么现在我将向您解释我的代码,希望我们能够共同找到解决方案。暂时谢谢您。

这是主 java 页面,我在其中通过 OnClick 方法进行连接:

package com.example.enchan.crazyup;

import android.database.Cursor;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Button;
import android.view.View;
import android.content.Intent;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;

import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.net.URL;

import android.view.Menu;
import android.app.Activity;
import android.widget.Toast;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FollowUsActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_follow_us);

        findViewById(R.id.subscribe).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                EditText email = (EditText) findViewById(R.id.email);
                String pkg = getPackageName();


                URL url_page = null;

                try {
                    url_page = new URL("http://crazyup.altervista.org/select_email.php?email==" + email.getText().toString());
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }

                try {
                    HttpURLConnection client = (HttpURLConnection) url_page.openConnection();
                } catch (IOException e) {
                    e.printStackTrace();
                }                Intent OpenNewEmailActivity = new Intent(FollowUsActivity.this, NewEmailActivity.class);
                Intent intent = OpenNewEmailActivity.putExtra(pkg + "Test", email.getText().toString());
                startActivity(OpenNewEmailActivity);
            }
        });
    }
}

这是相应的 .xml 主文件:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@drawable/bg_follow_us"
    tools:context="com.example.enchan.crazyup.FollowUsActivity">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/subscribe"
        android:src="@drawable/iscriviti"
        android:layout_marginBottom="41dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:id="@+id/email"
        android:layout_above="@+id/subscribe"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Indirizzo Email"
        android:id="@+id/email_title"
        android:layout_above="@+id/email"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

list 中有以下权限:

    <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

php 页面是这样的(如果我在浏览器上打开它,它就可以工作):

    <?php

mysql_connect("localhost","crazyup","");
mysql_select_db("my_crazyup");

$s_email = $_GET['email'];
$string = "INSERT INTO email (content) VALUES ('".$s_email."')";
$q = mysql_query($string);

if (!$q) {
    die("Errore nella query: " . mysql_error());
}

/* $q = mysql_query("SELECT * FROM email WHERE email =".$s_email);
while($e = mysql_fetch_assoc($q))
        $output[] = $e;
print(json_encode($output)); */

mysql_close();

?>

我读到,可能的问题可能是 Android 版本(Marshmallow 或 Lollipop),但我已经尝试过这两种版本,但遇到了同样的问题。 在 logcat 中没有错误,所以我不明白为什么该应用程序无法运行。

最佳答案

将此代码放入您的 onClick 方法中,我们将使用 Google Volley framework

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url_page = "http://crazyup.altervista.org/select_email.php?email==" + email.getText().toString();

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url_page,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first 500 characters of the response string.
        Log.i("stringRequest", response);
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e("stringRequest", "FAILED" + error.getMessage());
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

旧答案,使用一些已弃用的类

// Create http client object to send GET request to server
HttpClient client = new DefaultHttpClient();

// Create URL string
String url_page = "http://crazyup.altervista.org/select_email.php?email==" + email.getText().toString();

try
{
     String response = "";
     // Create Request to server and get response
     HttpGet httpGet = new HttpGet(url_page);
     ResponseHandler<String> responseHandler = new BasicResponseHandler();

     // Execute request
     response = Client.execute(httpGet, responseHandler);

     // Log request's response
     Log.i("httpGet", response);
}
catch(Exception ex)
{
     Log.e("httpGet", "FAILED" + ex.getMessage());
     ex.printStackTrace();
}

//starts new Activity
Intent OpenNewEmailActivity = new Intent(FollowUsActivity.this, NewEmailActivity.class);
Intent intent = OpenNewEmailActivity.putExtra(pkg + "Test", email.getText().toString());
startActivity(OpenNewEmailActivity);

免责声明:我使用了this link处的代码获取请求代码

关于android - Android 和 MySQL/PHP 数据库连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38737346/

相关文章:

mysql - 如何使用mysql获取group by中的第一个,最大,最小,最后一条记录

mysql - 为相互关注的用户建立 Eloquent 关系

java - 有时必须等待很长时间,直到 HttpClient.execute() 抛出异常

c# - 类型化数据集 : Can't change connection String

php - AJAX PHP文件上传和解析示例

java - 以编程方式访问Manifest.permission?

android - 服务还是 BroadcastReceiver?

java - 在 Android 中处理命令而不启动 MainActivity

android - 如何在Android中查看HDMI设备连接状态?

android - 为什么 BitmapFactory.decodeStream 返回 null?