gpt4 book ai didi

java - 使用 Android 应用程序中的 post req 将数据保存到 mongodb

转载 作者:行者123 更新时间:2023-12-02 01:45:43 25 4
gpt4 key购买 nike

我的暑假作业遇到一些问题。这是一个 Android 应用程序,可将设备的位置和 IMEI 保存到数据库中。我已经完成了 Android 应用程序,可以获取纬度、经度和 IMEI,但是我在将这些信息像结构一样保存到数据库中时遇到一些问题。

这是我的 android 应用程序代码

package com.example.locatieimei;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import androidx.core.app.ActivityCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.CircularProgressDrawable;

import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

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.Iterator;

public class MainActivity extends AppCompatActivity {

private FusedLocationProviderClient client;
private TextView imei;

public double latitude;
public double longitude;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imei = findViewById(R.id.imei);
loadIMEI();

client = LocationServices.getFusedLocationProviderClient(this);
Button button = findViewById(R.id.Chk);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then
overriding
// public void onRequestPermissionsResult(int
requestCode, String[] permissions,
// int[]
grantResults)
// to handle the case where the user grants the
permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
client.getLastLocation().addOnSuccessListener(new
OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location!=null){
TextView textView = findViewById(R.id.textView);

longitude = location.getLongitude();
latitude = location.getLatitude();

textView.setText(String.valueOf("latitudine"+longitude+
"\n"+"longitutine"+latitude));

}
}
});
}
});
}

public void loadIMEI() {
// Check if the READ_PHONE_STATE permission is already available.
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_PHONE_STATE)) {
// get_imei_data();
} else {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
}
} else {

TelephonyManager mngr =
(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);//
IMEI = mngr.getDeviceId();

imei.setText(mngr.getDeviceId());
// READ_PHONE_STATE permission is already been granted.
}
}

private String device_unique_id;

private static String IMEI;
private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 0;

public class SendPostRequest extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
}

@Override
protected String doInBackground(String... arg0) {
URL url = null;
try {
url = new URL("http://myIp/postdata");
InputStream inp = (InputStream) url.getContent();
Log.e("Stream", inp.toString());
JSONObject postDataParamas = new JSONObject();
postDataParamas.put("longitute", longitude);
postDataParamas.put("latitute", latitude);
postDataParamas.put("imei", imei);
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
int responseCode;
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"))) {
String encoded_string =
getPostDataString(postDataParamas);
writer.write(postDataParamas.toString());
writer.flush();
writer.close();
}
os.close();

responseCode = conn.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";

while ((line == in.readLine()) != false)
sb.append(line);

in.close();
return sb.toString();

} else {
return new String("false : "+responseCode);
}
} catch (Exception e) {
return new String("exception"+e.getMessage());
}
}

@Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
public String getPostDataString(JSONObject params) throws Exception
{
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()) {
String key = itr.next();
Object value = params.get(key);

if(first)
first = false;
else
result.append("&");

result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(),"UTF-8"));

}
return result.toString();
}
}
}

这是 server.js

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');


//connect to mongodb:

mongoose.connect('mongodb+srv://dbUser:dbPassword@test-
srqul.mongodb.net/test?retryWrites=true&w=majority', {useNewUrlParser:
true} );

var app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

//routes:

app.use('/api', require('./routes/api'));
app.post('/postdata',function(req,res){
console.log(req.body);
if (!req.body)
return res.sendStatus(400)
res.send('welcome, ' + req.body)
});

//start server:

app.listen(3000);

console.log('serverul porneste pe port 3000');

这是 api.js

//dependencies

var express = require('express');
var router = express.Router();

//models

var Status = require('../models/status');

//routes

Status.methods(['get', 'post', 'put']);
Status.register(router, '/status');

//return router

module.exports = router;

这是 status.js

var restful = require('node-restful');
var mongoose = restful.mongoose;

var statusSchema = new mongoose.Schema({
latitudine: String,
longitudine: String,
imei: String
});

//return models

module.exports = restful.model('tblstatus', statusSchema);

我没有任何代码错误,但在数据库中它没有显示任何内容。有谁知道我缺少什么来将这些数据保存到 mongodb

最佳答案

在您的代码示例中,我们看到您创建了与 mongodb 的连接,创建了架构,但实际将数据放入数据库的部分似乎丢失了。

作为引用,请查看 Introduction to Mongoose for MongoDB ,“创建记录”一章。

关于java - 使用 Android 应用程序中的 post req 将数据保存到 mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57458418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com