Отправка user_id и получение записей пользователя

Привет, я новичок в Android, и мне было интересно, как я могу отправить user_id в мой php-файл, а затем заставить его получать информацию о пользователе (представление переработчика), например, я хочу получить заимствованные книги (BookName, dateBorrowed, Pages и т. Д.) из таблицы «Заимствованные книги». Вот мой 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);
?>

1

Решение

На стороне 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);
0

Другие решения

использование Okhttp или залп андроид.

На Android с Охтттп:

    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);
-1

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector