发送user_id并检索用户记录

时间:2016-09-05 11:10:11

标签: php android mysql android-recyclerview

嗨我是Android的新手,我想知道如何将user_id发送到我的php文件,然后让它检索有关用户的信息(回收者视图),例如我想要检索借来的书籍(BookName,dateBorrowed,Pages来自表" BorrowedBooks" 。这是我的MainActivity user_id是表" BorrowedBooks"。

的外键
package com.androidcss.jsonexample;


public class MainActivity extends AppCompatActivity {

// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFishPrice;
private AdapterNotif mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_notifmainactivity);
    //Make call to AsyncTask
    new AsyncLogin().execute();
}

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

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

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

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

            // Enter URL address where your json file resides
            // Even you can make call to php file which returns json data
            url = new URL("http://192.168.1.7/notif.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        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("GET");

            // setDoOutput to true as we recieve data from json file
            conn.setDoOutput(true);

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

        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 e.toString();
        } finally {
            conn.disconnect();
        }


    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread

        pdLoading.dismiss();
        List<DataNotif> data=new ArrayList<>();

        pdLoading.dismiss();
        try {

            JSONArray jArray = new JSONArray(result);

            // Extract data from json and store into ArrayList as class objects
            for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i);
                DataNotif fishData = new DataNotif();

                fishData.NotifTitle= json_data.getString("notif_Title");
                fishData.NotifMessage= json_data.getString("notif_Message");
//                    fishData.sizeName= json_data.getString("size_name");
                fishData.Date= json_data.getString("notif_date");
                data.add(fishData);
            }

            // Setup and Handover data to recyclerview
            mRVFishPrice = (RecyclerView)findViewById(R.id.fishPriceList);
            mAdapter = new AdapterNotif(MainActivity.this, data);
            mRVFishPrice.setAdapter(mAdapter);
            mRVFishPrice.setLayoutManager(new LinearLayoutManager(MainActivity.this));

        } catch (JSONException e) {
            Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
        }

    }

}
}

这是我的PHP代码

<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","jmilibrary") or die("Error " . mysqli_error($connection));

//fetch table rows from mysql db
$sql = "select * from notification";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
    $emparray[] = $row;
}
echo json_encode($emparray);

//close the db connection
mysqli_close($connection);
?>

2 个答案:

答案 0 :(得分:0)

在PHP端编写与上面相同的脚本,并用新命令替换$sql,如

$sql = "select book_information from table where id = " . $_GET["id"];


在客户端提出与上述相同的请求,只需将id添加到URL,如

url = new URL("http://192.168.1.7/notif.php?id="+UserID);

答案 1 :(得分:-1)

使用Okhttp或排球安卓。

在Android上使用Okhtttp:

    buildernew.addFormDataPart("user_id","YOUR USER ID");

    MultipartBody requestBody = buildernew.build();
    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();
    okhttp3.Request request = new okhttp3.Request.Builder()
            .url(url)
            .post(requestBody)
            .build()
            ;

    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.e("respons is error", "Registration error: " + e.getMessage());
        }
        @Override
        public void onResponse(Call call, okhttp3.Response response) throws IOException {
            try {
                String jsonData = response.body().string();
                JSONObject Jobject = new JSONObject(jsonData);
                JSONArray jr = Jobject.getJSONArray("notification");
                for (int i = 0; i < jr.length(); i++) {
                    DataNotif fishData = new DataNotif();
                    JSONObject object = jr.getJSONObject(i);
                    fishData.NotifTitle(object.getString("notif_Title"));
                    fishData.NotifMessage(object.getString("notif_Message"));
                    fishData.Date(object.getString("notif_date"));
                    data.add(personal);
                }
                response.body().close();

            } catch (IOException e) {
                Log.e("respons is not Ok", "Exception caught: ", e);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
}

在PHP上:     

function connectToDatabase(){
$connection=mysqli_connect("localhost", "root", "", "jmilibrary");
  mysqli_set_charset($connection, 'utf8');
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
return $connection;
}

$connection = connectToDatabase();
$user_id = $_REQUEST['user_id'];
$result = mysqli_query($connection, "SELECT * FROM book_information WHERE id=$user_id");
while($row = mysqli_fetch_array($result)) {
  $record['id'] = $row['id'];
  $record['notif_Title'] = $row['notif_Title'];
  $record['notif_Message'] = $row['notif_Message'];     
$record['notif_date'] = $row['notif_date'];
   $notification['notification'][] = $record;
}
echo json_encode($notification);
mysqli_close($connection);