简体   繁体   English

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

[英]Saving data into mongodb using post req from android app

I am having some problems with my summer holiday homework. 我的暑假作业遇到一些问题。 It's about an android app that save location and imei of the device into database. 这是关于一个将应用程序的位置和imei保存到数据库中的Android应用。 i have done the android app that get me the lat and long and the imei, but i have some problems saving those information into database like a structure. 我已经完成了获取lat和long以及imei的android应用,但是我在将这些信息保存到数据库(如结构)中时遇到了一些问题。

This is my android-app code 这是我的android-app代码

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();
      }
  }
 }

this is the server.js 这是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');

this is the api.js 这是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;

this is the status.js 这是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);

I don't have any code error, but in database it doesn't show anything. 我没有任何代码错误,但是在数据库中它什么都不显示。 Does anyone know what i'am missing to save those data into mongodb 有谁知道我想要将那些数据保存到mongodb中缺少什么

In your code examples we see you create connection to the mongodb, create the Schema but the part where you actually put your data in to the database seems to be missing. 在代码示例中,我们看到您创建了与mongodb的连接,创建了Schema,但实际上缺少将数据放入数据库中的部分。

As a reference, have a look at the Introduction to Mongoose for MongoDB , chapter 'Create Record'. 作为参考,请查看MongoDB的Mongoose简介章节“创建记录”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM