我想知道如何连接数据库........?

时间:2016-06-23 09:21:10

标签: android sql web-services sqlite

我是Android的新手我想知道如何连接数据库。我看到你的视频中的一个视频,我跟着洞视频但它不工作。我不知道我哪里弄错了。请帮助我。从一周开始我正在尝试的话但是现在我也没有得到解决方案请帮我堆叠流量。

class ServerRequests {
    ProgressDialog progressDialog;
    public static final int CONNECTION_TIMEOUT=1000*15;
    public static final String       
    SERVER_ADDRESS="http://192.168.1.11/myfolder/new1.php";

    public ServerRequests(Context context){
        progressDialog=new ProgressDialog(context);
        progressDialog.setCancelable(false);
        progressDialog.setTitle("processing");
        progressDialog.setMessage("please wait.....");
    }
    public void storeUserDataInBackground(User user,GetUserCallbackuserCallback{
        progressDialog.show();
        new StoreUserDataAsyncTask(user,userCallback).execute();

    }
    public void fetchUserDataInBackground(User user,GetUserCallback callBack){
        progressDialog.show();
        new fetchUserDataAsynctask(user,callBack).execute();

    }
    public class StoreUserDataAsyncTask extends AsyncTask<Void,Void,Void>{
        User user;
        GetUserCallback userCallback;
        public StoreUserDataAsyncTask(User user,GetUserCallback userCallback){
            this.user=user;
            this.userCallback=userCallback;
        }

        @Override
        protected Void doInBackground(Void... params) {
            ArrayList<NameValuePair>dataToSend=new ArrayList<>();
            dataToSend.add(new BasicNameValuePair("name",user.name));
            dataToSend.add(new BasicNameValuePair("age",user.age + ""));
            dataToSend.add(new BasicNameValuePair("username",user.username));
            dataToSend.add(new BasicNameValuePair("password",user.password));

            HttpParams httpRequestParams = new BasicHttpParams();
                                                     HttpConnectionParams.setConnectionTimeout(httpRequestParams,CONNECTION_TIMEOUT);
                                                                                                  HttpConnectionParams.setSoTimeout(httpRequestParams,CONNECTION_TIMEOUT);

            HttpClient client = new DefaultHttpClient(httpRequestParams);
            HttpPost post = new HttpPost(SERVER_ADDRESS + "Register.php");

            try{
                post.setEntity(new URLEncoderFormEntity(dataToSend));
                client.execute(post);
            }catch (Exception e){
                e.printStackTrace();
            }


            return null;
        }
        @Override
        protected void onpostExecute(Void aVoid){
            progressDialog.dismiss();
            userCallback.done(null);
            super.onPostExecute(aVoid);
        }

    }
    public fetchUserDataAsyncTask extends AsyncTask<Void,Void,User>{
        User user;
        GetUserCallback userCallback;
        public fetchUserDataAsyncTask(User user,GetUserCallback userCallback){
            this.user=user;
            this.userCallback = userCallback;
        }
        @Override
                protected User doInBackground(Void... params){
            ArrayList<NameValuePair>dataToSend=new ArrayList<>();
            dataToSend.add(new BasicNameValuePair("username",user.username));
            dataToSend.add(new BasicNameValuePair("password",user.password));

            HttpParams httpRequestParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
            HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

            HttpClient client = new DefaultHttpClient(httpRequestParams);
            HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");

            User returnedUser=null;
            try{
                post.setEntity(new URLEncoderFormEntity(dataToSend));
                HttpResponce httpResponce=client.execute(post);

                HttpEntity entity=httpResponce.getEntity();
                String result= EntityUtils.toString(entity);
                JSONObject jObject=new JSONObject(result);

                if (jObject.length()==0){
                    user=null;
                }else{
                    String name=jObject.getString("name");
                    int age =jObject.getInt("age");

                    returnedUser=new User(name,age,user.username,user.password);
                }

            }catch (Exception e){
                e.printStackTrace();
            }


            return returnedUser;
        }
        @Override
                protected void onPostExecute(User returnedUser){
            progressDialog.dismiss();
            userCallback.done(null);
            super.onPostExecute(returnedUser);
        }
    }
}





  enter code here

      public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
Button blogin;
EditText etusername,etpassword;
TextView tvregister;
UserLocalStore userLocalStore;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    etusername=(EditText)findViewById(R.id.username_edit);
    etpassword=(EditText)findViewById(R.id.password_edit);
    blogin=(Button)findViewById(R.id.login_button);
    tvregister=(TextView)findViewById(R.id.tv_register);
    blogin.setOnClickListener(this);
    tvregister.setOnClickListener(this);
userLocalStore=new UserLocalStore(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.login_button:
            String username=etusername.getText().toString();
            String password=etpassword.getText().toString();

            User user=new User(username,password);

            authenticate(user);

            userLocalStore.storeUserData(user);
            userLocalStore.setUserLoggedIn(true);
            break;

        case R.id.tv_register:
            startActivity(new Intent(this,RegisterActivity.class));
            break;
    }
}
private void authenticate(User user) {
    ServerRequests serverRequests = new ServerRequests(this);
    serverRequests.fetchUserDataInBackground(user, new GetUserCallback() {
        @Override
        public void done(User returnedUser) {
            if (returnedUser == null) {
                showErrorMessage();
            }else {
                logUserIn(returnedUser);
            }

        }

    });
}
    private void showErrorMessage() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LoginActivity.this);
        dialogBuilder.setMessage("Incorrect user details");
        dialogBuilder.setPositiveButton("ok", null);
        dialogBuilder.show();

}
private void logUserIn(User returnedUser){

    userLocalStore.storeUserData(returnedUser);
    userLocalStore.setUserLoggedIn(true);

    startActivity(new Intent(this,MainActivity.class));
}

}

1 个答案:

答案 0 :(得分:-1)

以下是您可以参考从服务器获取数据的链接。

使用PHP创建Web服务 Click here

<?php  

    include("connect.php");


    $result="";

    //get data from users (name for user variable is p1 and p2
    //here I am stroing this value to par1 and par2
    //method i am using is GET
    $par1=$_GET['p1'];
    $par2=$_GET['p2'];


    $eve = "select * from table where field1='$par1' and field2='$par2'";

    $re = mysql_query($eve);

    $response = array();
    $posts = array();

    while($rt = mysql_fetch_array($re))
    {
        $f1=$rt['field1'];
        $f2=$rt['field2'];


        break;
    }

    $posts[] = array('p1'=> $f1,'p2'=> $f2);

    $response['posts'] = $posts;
    echo stripslashes(json_encode( array('item' => $posts)));

?>

对于AsyncTask示例 Click here

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Login extends AppCompatActivity {

    boolean remember;
    private ProgressDialog pDialog;
    public static final String PREFS_NAME = "Preference";


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

        ((Button) findViewById(R.id.btnlogin)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Login Validation

                try {

                    pDialog = new ProgressDialog(Login.this);
                    pDialog.setMessage("Verifying...");
                    pDialog.show();

                    LoginVerifyTask g = new LoginVerifyTask();
                    g.execute(((EditText) findViewById(R.id.mobile)).getText().toString(), ((EditText) findViewById(R.id.password)).getText().toString());

                } catch (Exception e) {
                    Log.e("cs", "catch error");
                }

            }
        });


        ((TextView) findViewById(R.id.newuserregistrationtxtview)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent i = new Intent(getApplicationContext(), Registration1.class);
                startActivity(i);
            }
        });

    }



    public class LoginVerifyTask extends AsyncTask<String, Void, String>
    {
        String u,p;

        void LoginActivity(String s)
        {

        }

        @Override
        protected void onPostExecute(String json) {
            // TODO Auto-generated method stub

            pDialog.dismiss();
            pDialog = null;

            if (json == null)
            {

                return;
            }

            String csv="";

            try {

                JSONObject js = new JSONObject(json);
                JSONArray user = js.getJSONArray("item");

                for(int i=0;i<user.length();i++)
                {
                    JSONObject j2 =  user.getJSONObject(i);

                    //received data
                    String result = j2.get("p1").toString();

                    break;
                }
            }
            catch(JSONException js)
            {

            }

            return;

        }

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub


            u = params[0];
            p = params[1];

            String tempdata="";
            String buffer="";

            try
            {


                URL url = new URL("http://websitename.com/folder/webservice.php?p1=" + params[0].replace(" ", "%20") + "&p2=" + params[1].replace(" ", "%20"));
                HttpURLConnection conn = (HttpURLConnection)  url.openConnection();
                conn.setRequestMethod("GET");
                conn.connect();

                InputStream is = conn.getInputStream();
                //buffer = new String();

                if(is==null)
                {
                    return tempdata;
                }
                else
                {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    String line="";

                    while( (line = reader.readLine())!=null)
                    {
                        buffer += line;
                    }
                    return buffer;

                }

            }
            catch(Exception e)
            {
                Log.e("cs", e.toString());
            }
            return buffer;
        }
    }
}
相关问题