从web获取数据库到android

时间:2016-07-19 00:25:25

标签: php android mysql android-asynctask

我正在尝试从Web服务器加载我的数据库并登录到我的应用程序。

我使用oum saokosal源代码。

  

LoginActivity.java

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

final String LOG = "LoginActivity";
Button btnLogin;
EditText etUsername, etPassword;

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

    etUsername = (EditText)findViewById(R.id.etUsername);
    etPassword = (EditText)findViewById(R.id.etPassword);
    btnLogin = (Button)findViewById(R.id.btnLogin);
    btnLogin.setOnClickListener(this);
}


@Override
public void onClick(View v) {
    HashMap postData = new HashMap();

    String username = etUsername.getText().toString();
    String password = etPassword.getText().toString();

    postData.put("txtUsername", username);
    postData.put("txtPassword", password);

    PostResponseAsyncTask task1 = new PostResponseAsyncTask(LoginActivity.this, postData,
            new AsyncResponse() {
                @Override
                public void processFinish(String s) {
                    Log.d(LOG, s);
                    if(s.contains("success")){
                        Toast.makeText(LoginActivity.this, "Sucessfully Login", Toast.LENGTH_LONG).show();
                        Intent in = new Intent(LoginActivity.this, ListActivity.class);
                        startActivity(in);
                    }
                    else{
                        Toast.makeText(LoginActivity.this, "Connection Failed", Toast.LENGTH_LONG).show();
                    }
                }
            });
    task1.execute("http://symphonyrecords.gigfa.com/customer/");
}
}
  

connection.php

<?php
$servername = "my_database_servername"; //replace it with your database server name
$username = "my_database_usename";  //replace it with your database username
$password = "my_database_password";  //replace it with your database password
$dbname = "my_database_name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
?>

PostResponseAsyncTask

  

MainActivity.java

    public class MainActivity extends AppCompatActivity
{
       Button button1;
       Button button3;
       int clickerId;

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

        this.button1 = ((Button)findViewById(R.id.button1));
         this.button2 = ((Button)findViewById(R.id.button2));
        this.button3 = ((Button)findViewById(R.id.button3));
        this.button1.setOnClickListener(new View.OnClickListener()
         {
          public void onClick(View v) {
             String url = "http://10.0.3.2/client/post.php?format=json";
             PostResponseAsyncTask readTask = new PostResponseAsyncTask(MainActivity.this, new AsyncResponse()
             {
              public void processFinish(String s) {
                 Toast.makeText(MainActivity.this, s, 1).show();
              }
            });
            readTask.execute(new String[] { url });
          }
        });
        this.button2.setOnClickListener(new View.OnClickListener()
       {
          public void onClick(View v) {
             String url = "http://10.0.3.2/client/post.php";
            PostResponseAsyncTask readTask = new PostResponseAsyncTask(MainActivity.this, new AsyncResponse()
            {
               public void processFinish(String s) {
                Toast.makeText(MainActivity.this, s, 1).show();
              }
             });
            readTask.execute(new String[] { url });
          }
         });
         this.button3.setOnClickListener(new View.OnClickListener()
         {
          public void onClick(View v)
           {
           String url = "http://10.0.3.2/client/post.php";

            PostResponseAsyncTask readTask = new PostResponseAsyncTask(MainActivity.this, false, new AsyncResponse()
            {
              public void processFinish(String s)
             {
                 Toast.makeText(MainActivity.this, s, 1).show();
               }
            });
            readTask.execute(new String[] { url });
           }
        });
       }
     }
  

PostResponseAsyncTask.java

 package com.kosalgeek.genasync12;

 import android.app.ProgressDialog;
 import android.content.Context;
 import android.os.AsyncTask;
 import android.util.Log;
 import java.io.BufferedReader;
 import java.io.BufferedWriter;
 import java.io.InputStreamReader;
 import java.io.OutputStream;
 import java.io.OutputStreamWriter;
 import java.io.UnsupportedEncodingException;
 import java.net.HttpURLConnection;
 import java.net.URL;
 import java.net.URLEncoder;
 import java.util.HashMap;
 import java.util.Map.Entry;

 public class PostResponseAsyncTask extends AsyncTask<String, Void, String>
 {
   private ProgressDialog progressDialog;
   private AsyncResponse delegate;
  private Context context;
   private HashMap<String, String> postData = new HashMap();
   private String loadingMessage = "Loading...";
   private boolean showLoadingMessage = true;

   public PostResponseAsyncTask(Context context, AsyncResponse delegate)
   {
    this.delegate = delegate;
     this.context = context;
   }

   public PostResponseAsyncTask(Context context, boolean showLoadingMessage, AsyncResponse delegate)
   {
     this.delegate = delegate;
     this.context = context;
    this.showLoadingMessage = showLoadingMessage;
   }

   public PostResponseAsyncTask(Context context, HashMap<String, String> postData, AsyncResponse delegate)
   {
     this.context = context;
     this.postData = postData;
     this.delegate = delegate;
   }
   public PostResponseAsyncTask(Context context, HashMap<String, String> postData, boolean showLoadingMessage, AsyncResponse delegate)
   {
     this.context = context;
     this.postData = postData;
     this.delegate = delegate;
     this.showLoadingMessage = showLoadingMessage;
   }

  public PostResponseAsyncTask(Context context, String loadingMessage, AsyncResponse delegate)
   {
     this.context = context;
    this.loadingMessage = loadingMessage;
    this.delegate = delegate;
   }

   public PostResponseAsyncTask(Context context, HashMap<String, String> postData, String loadingMessage, AsyncResponse delegate)
   {
     this.context = context;
     this.postData = postData;
     this.loadingMessage = loadingMessage;
     this.delegate = delegate;
   }
   protected void onPreExecute()
   {
     if (this.showLoadingMessage == true) {
       this.progressDialog = new ProgressDialog(this.context);
       this.progressDialog.setMessage(this.loadingMessage);
       this.progressDialog.show();
    }

     super.onPreExecute();
   }

   protected String doInBackground(String[] urls)
   {
     String result = "";

     for (int i = 0; i <= 0; i++)
    {
      result = invokePost(urls[i], this.postData);
     }

    return result;
  }

  private String invokePost(String requestURL, HashMap<String, String> postDataParams)
   {
     String response = "";
    try {
      URL url = new URL(requestURL);

       HttpURLConnection conn = (HttpURLConnection)url.openConnection();
      conn.setReadTimeout(15000);
       conn.setConnectTimeout(15000);
      conn.setRequestMethod("POST");
       conn.setDoInput(true);
      conn.setDoOutput(true);

       OutputStream os = conn.getOutputStream();
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

       writer.write(getPostDataString(postDataParams));

      writer.flush();
       writer.close();
       os.close();
      int responseCode = conn.getResponseCode();

       if (responseCode == 200)
       {
         BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         String line;
         while ((line = br.readLine()) != null)
          response = new StringBuilder().append(response).append(line).toString();
       }
       else
       {
         response = "";

         Log.i("PostResponseAsyncTask", new StringBuilder().append(responseCode).append("").toString());
       }
    } catch (Exception e) {
       e.printStackTrace();
    }

     return response;
   }

   private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
     boolean first = true;

     for (Map.Entry entry : params.entrySet()) {
      if (first)
        first = false;
      else {
        result.append("&");
      }
       result.append(URLEncoder.encode((String)entry.getKey(), "UTF-8"));
     result.append("=");
       result.append(URLEncoder.encode((String)entry.getValue(), "UTF-8"));
    }

    return result.toString();
  }

   protected void onPostExecute(String result)
   {
     if ((this.showLoadingMessage == true) && 
(this.progressDialog.isShowing())) {
this.progressDialog.dismiss();
}

result = result.trim();

this.delegate.processFinish(result);
}

public String getLoadingMessage()
{
    return this.loadingMessage;
}

   public void setLoadingMessage(String loadingMessage) {
     this.loadingMessage = loadingMessage;
   }

  public HashMap<String, String> getPostData() {
    return this.postData;
  }

  public void setPostData(HashMap<String, String> postData) {
    this.postData = postData;
  }

   public Context getContext() {
    return this.context;
   }

   public AsyncResponse getDelegate() {
    return this.delegate;
  }
 }

http://symphonyrecords.gigfa.com/customerconnection.php文件位于我的主机

中的 customer 根文件夹中

我已经在我的cPanel中创建了我的用户名和密码数据库,它在浏览器中工作得很好,但在应用程序中它让我连接失败。

我在这里做错了什么?

0 个答案:

没有答案