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. 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.
This is my android-app code
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
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
//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
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
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.
As a reference, have a look at the Introduction to Mongoose for MongoDB , chapter 'Create Record'.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.