【问题标题】:Access database from android phone through android app通过 android 应用程序从 android 手机访问数据库
【发布时间】:2017-10-23 09:54:29
【问题描述】:

我目前正在为我的第三年项目开发一个应用程序,它是一个 android 应用程序(我使用了 android studio),它将访问我在我的 wamp 服务器上创建的数据库,当我调试它时,连接可以从应用程序完美运行我的 android 手机(我在代码中使用了“HttpURLConnection”,其 url 是我从 (cmd/ipconfig) 获得的我的 pc ip 地址)。
问题是,一旦我将手机与电脑断开连接并尝试从手机运行应用程序,与数据库的连接将无法正常工作,而且如果我将电脑连接到另一个调制解调器,我的电脑 ip 会更改,即很正常,但我不认为每次我连接的调制解调器都更改时应该更改 ip(虽然我不太确定,服务器连接显然不是我的专家),所以我尝试使用我从“ipaddress.com”获得的互联网上我的电脑的 ip 但它不起作用,即使我直接从 android studio 调试应用程序, 我没有太多时间提交申请,所以我需要一个快速的答复,提前谢谢你 PS:我想我得提一下,我需要访问数据库才能从手机上读取和写入,因为它是一个允许登录/注册的应用程序,并将获取用户将输入的数据并将其存储在数据库中。

【问题讨论】:

  • 使用领域访问数据库

标签: android database android-studio database-connection wamp


【解决方案1】:

尝试将手机和手机连接在同一网络中。

您的连接 URL 将类似于 192.10.20.2,这是您的 ip 或计算机。使用 ipconfig 命令从 cmd 获取它。

但是每当您的网络发生变化时,您都必须反编译才能更改 ip。或通过 textview 提供 ip。

采取 Editview 采取 ip。并将其连接到您的网址。这会奏效。因为它对我有用。

【讨论】:

  • 我不明白你用textview获取ip是什么意思,以及我如何将手机和电脑准确连接到同一个网络,它们实际上都是通过同一个调制解调器连接的WIFI
  • 当 Ip 发生变化时,您必须更改 url 对吗?由于数据库在您的 PC 中,您必须提供 PC 的实际 IP。每当它改变时
  • 是的,我认为 mayeb 可能有一种使用静态 IP 的方法,因此我不必每次都更改它,并且手机可以访问数据库,即使它们是连接到同一个调制解调器,如果手机与电脑断开连接,手机仍然无法访问数据库,我在某处读到我必须更改 apache 的 http.conf 文件,在这个文件中,我有一行“ServerName localhost: 80”,也许问题来自“localhost”,所以我将其更改为我的 pc ip 地址,但它没有工作
  • 这就是为什么!我告诉拿一个Edittext。这将获得您PC的当前IP。我的意思是现在您正在更改 IP 并再次构建 apk。但是如果您使用edittext并在那里插入您的IP。那么您不必再次重新构建代码。
  • 只需获取值并将其连接到您的 URL 为 etText.getText().toString()+"/"+insert.php
【解决方案2】:

我不知道是否理解,当您将手机与电脑断开连接时,应用程序就死机了?或者简单地说它不与数据库连接。关于路由器,您需要在“no-ip”中创建一个帐户,并在端口 80 上配置 forguard 的路由器,以重定向您计算机的静态 IP。我需要更多细节和信息来帮助你。问候

【讨论】:

  • 当我断开电话时,应用程序仍然可以工作,但它不会连接到数据库,我实际上捕获了异常( java.lang.NullPointerException 尝试调用虚拟方法 boolean java.lang. String.equals on a null object reference ) ,这是因为在 php 代码中 "$mysql_qry = "select * from donateur where email like '$email'"; $result = mysqli_query($conn , $mysql_qry) ; " $result 返回 false 这意味着连接没有工作,对于路由器,如果您能提供有关 (no-ip) 帐户的更多详细信息,那就太好了,谢谢
  • 好吧,我需要你发布脚本 php、你的 java 代码、日志跟踪。关于路由器,我需要知道您是在 LAN 上工作还是外部连接到服务器?因为 NO-IP 提供了一个 DNS 来引用您的主机。用于监控您的公共 ip 是否更改
【解决方案3】:
     i'm working on an external server 
The php code (for the connection to the db)
  <?php
$db_name="pfe";
$mysql_username="root";
$mysql_password="";
$server_name="localhost";
$conn = mysqli_connect($server_name,$mysql_username,$mysql_password,$db_name);
?>
then i got another php file which handles the login part
 <?php
require "connexion.php";
$user_email =$_POST["user-email"];
$user_pass =$_POST["password"];
$mysql_qry = "select id from donateur where email like '$user_email' and                 
password like '$user_pass'";
$result = mysqli_query($conn , $mysql_qry);
if(($row=mysqli_fetch_assoc($result))!=null){
$a = array('myarray' => array("donateur", $row["id"]));
echo json_encode($a);}
else {
    $mysql_qry2 = "select id, username from association where email like     
'$user_email' and password like '$user_pass'";
$result2 = mysqli_query($conn , $mysql_qry2);
if(($row=mysqli_fetch_assoc($result2))!=null) { $a = array('myarray' => 
array("association", $row["id"]));
echo json_encode($a);
}
 else { echo "rien";}}
$conn->close();

    the java code : 

package applis.pfe;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.app.LoaderManager.LoaderCallbacks;

import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;

import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

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

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;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static android.Manifest.permission.READ_CONTACTS;


public class LoginActivity extends AppCompatActivity implements             
LoaderCallbacks<Cursor> {

/**
 * Id to identity READ_CONTACTS permission request.
 */
private static final int REQUEST_READ_CONTACTS = 0;

DonateurDAO donateurdao= new DonateurDAO(this);
AssociationDAO associationdao=new AssociationDAO(this);
/**
 * Keep track of the login task to ensure we can cancel it if requested.
 */
String ip="http://105.101.179.155/";
private UserLoginTask mAuthTask = null;

// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
public static String qui;
public static int id;
public static String username;
SessionManager session;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    ///////////////////// POUR AFFICHER LE MESSAGE DIINSCRIPTION REUSSIE /////////////////////////////////////
if(getIntent().getStringExtra("inscription")!=null &&         
getIntent().getStringExtra("inscription").equals("oui"))
{ AlertDialog a= new AlertDialog.Builder(LoginActivity.this).create();
    a.setTitle("Inscription réussie !");
    a.setMessage("Votre inscription a été validé, veuillez vous connecter     
pour pouvoir continuer");
    a.show();}
    session = new SessionManager(this);
    // Set up the login form.
    mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
  //  populateAutoComplete();
    mPasswordView = (EditText) findViewById(R.id.password);
    mPasswordView.setOnEditorActionListener(new 
 TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int id, KeyEvent         
keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
            }
            return false;
        }
    });

    Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
    mEmailSignInButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {attemptLogin();

        }
    });

    mLoginFormView = findViewById(R.id.login_form);
    mProgressView = findViewById(R.id.login_progress);

ImageButton btn;
    btn =(ImageButton)findViewById(R.id.InscriptionDonateurButton);
    btn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {Intent in= new     
Intent(LoginActivity.this,InscriptionDonateurActivity.class);
            startActivity(in);
        }
    });

   ImageButton btn1;
  btn1 =(ImageButton)findViewById(R.id.InscriptionAssociationButton);
    btn1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {Intent in= new     
Intent(LoginActivity.this,InscriptionAssociationActivity.class);
        startActivity(in);
        }
    });
}


    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

    // Store values at the time of the login attempt.
    String email = mEmailView.getText().toString();
    String password = mPasswordView.getText().toString();

    boolean cancel = false;
    View focusView = null;

    // Check for a valid password, if the user entered one.
    if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
        mPasswordView.setError(getString(R.string.error_invalid_password));
        focusView = mPasswordView;
        cancel = true;
    }

    // Check for a valid email address.
    if (TextUtils.isEmpty(email)) {
        mEmailView.setError(getString(R.string.error_field_required));
        focusView = mEmailView;
        cancel = true;
    } else if (!isEmailValid(email)) {
        mEmailView.setError(getString(R.string.error_invalid_email));
        focusView = mEmailView;
        cancel = true;
    }

    if (cancel) {
        // There was an error; don't attempt login and focus the first
        // form field with an error.
        focusView.requestFocus();
    } else {
        // Show a progress spinner, and kick off a background task to
        // perform the user login attempt.
        showProgress(true);
        mAuthTask = new UserLoginTask(email, password);
        mAuthTask.execute((Void) null);
    }
}

private boolean isEmailValid(String email) {
    //TODO: Replace this with your own logic
   return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();

}

private boolean isPasswordValid(String password) {
    //TODO: Replace this with your own logic
    return password.length() > 4;
}

/**
 * Shows the progress UI and hides the login form.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
    // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
    // for very easy animations. If available, use these APIs to fade-in
    // the progress spinner.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            }
        });

        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });
    } else {
        // The ViewPropertyAnimator APIs are not available, so simply show
        // and hide the relevant UI components.
        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
    }
}

@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
    return new CursorLoader(this,
            // Retrieve data rows for the device user's 'profile' contact.
            Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
                    ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,

            // Select only email addresses.
            ContactsContract.Contacts.Data.MIMETYPE +
                    " = ?", new String[]{ContactsContract.CommonDataKinds.Email
            .CONTENT_ITEM_TYPE},

            // Show primary email addresses first. Note that there won't be
            // a primary email address if the user hasn't specified one.
            ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}

@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
    List<String> emails = new ArrayList<>();
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        emails.add(cursor.getString(ProfileQuery.ADDRESS));
        cursor.moveToNext();
    }

    addEmailsToAutoComplete(emails);
}

@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {

}

private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
    //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
    ArrayAdapter<String> adapter =
            new ArrayAdapter<>(LoginActivity.this,
                    android.R.layout.simple_dropdown_item_1line, emailAddressCollection);

    mEmailView.setAdapter(adapter);
}


private interface ProfileQuery {
    String[] PROJECTION = {
            ContactsContract.CommonDataKinds.Email.ADDRESS,
            ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
    };

    int ADDRESS = 0;
    int IS_PRIMARY = 1;
}

/**
 * Represents an asynchronous login/registration task used to authenticate
 * the user.
 */
public class UserLoginTask extends AsyncTask<Void, Void, String> {

    private final String mEmail;
    private final String mPassword;

    UserLoginTask(String email, String password) {
        mEmail = email;
        mPassword = password;
    }

    @Override
    protected String doInBackground(Void... params) {
        // TODO: attempt authentication against a network service.
String login_url= ip.concat("login.php");
        try {
            URL url= new URL(login_url);
            HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            OutputStream outputStream= httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter= new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
            String Post_data= URLEncoder.encode("user-email","UTF-8")+"="+URLEncoder.encode(mEmail,"UTF-8")+"&"
                    +URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(mPassword,"UTF-8");
            bufferedWriter.write(Post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream=httpURLConnection.getInputStream();
            qui=null;
            id=0;
            BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String  resultat="";
           String ligne="";
            while((ligne=bufferedReader.readLine())!=null)
            resultat += ligne;
if (resultat.equals("rien")) return  resultat; else {
            JSONObject jsonObject = new JSONObject(resultat);
           JSONArray json_data = jsonObject.getJSONArray("myarray");
            qui=json_data.getString(0);
            id=json_data.getInt(1);
               username= json_data.getString(2);}
          /*  for(int i=0;i<json_data.length();i++)
            {
                k++;
                qui= json_data.getString(1);
                id= json_data.getInt(2);
                //r.add(json_data.getString("categorie"));

            }*/

            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return resultat;
        } catch (MalformedURLException e) {
            e.printStackTrace();return e.toString();
        } catch (IOException e) {
            e.printStackTrace();return e.toString();
        } catch (JSONException e) {
            e.printStackTrace(); return  e.toString();
        }
    }
      /*  for (String credential : DUMMY_CREDENTIALS) {
            String[] pieces = credential.split(":");
            if (pieces[0].equals(mEmail)) {
                // Account exists, return true if the password matches.
                return pieces[1].equals(mPassword);
            }
        }*/

        // TODO: register the new account here.



    @Override
    protected void onPostExecute(String resultat) {
        mAuthTask = null;
        showProgress(false);
        /////////////////////////////////////////////////////////////////////////////////
        Intent i;
        AlertDialog a;

        if (resultat.equals("rien")){i= new Intent(LoginActivity.this,LoginActivity.class);
            a= new AlertDialog.Builder(LoginActivity.this).create();
            a.setTitle("Erreur");
            a.setMessage(" Email et/ou mot de passe erroné(s)");
            a.show();} else {

            try {
                session.createLoginSession(mEmail,username,qui,id);
                session.checkLogin();
                if (qui.equals("donateur")) {

                    i = new Intent(LoginActivity.this, Suite_Inscription_Donateur.class);
                    i.putExtra("id", id);
                    startActivity(i);
                } else if (qui.equals("association")) {

                    session.createLoginSession(mEmail,username,qui,id);
                    i = new Intent(LoginActivity.this, Suite_Inscription_Association.class);
                    i.putExtra("id", id);
                    startActivity(i);
                }
            } catch (Exception e) {
                e.printStackTrace();
                a= new AlertDialog.Builder(LoginActivity.this).create();
                a.setTitle("Erreur");
                a.setMessage("Erreur :".concat(e.toString()));
                a.show();
            }
        }


    @Override
    protected void onCancelled() {
        mAuthTask = null;
        showProgress(false);
    }
}

}

【讨论】:

  • 我认为您收到 null 是因为您的脚本没有发送任何内容。试试:
  • 不,我实际上忘了添加处理登录的 php 脚本,它使用 connection.php 文件并返回一些东西,当我调试应用程序时,这段代码确实返回了一些东西,但是当我在断开连接的手机上启动应用程序时,它不会,我是否必须通过网络托管将数据库置于在线状态才能工作?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-19
相关资源
最近更新 更多