I have build an App in Android Studio that can scan every type of code(like qr code, barcode ect.) and I want to store that Data inside MongoDB.
For that I build an Api with 2 routes post/get to post an item and get all items - tested it with Postman, and it works.
app.get('/items', async (req, res) => {
const collection = client.db('codes').collection('QR');
const items = await collection.find({}).toArray();
res.send(items);
});
app.post('/items', async (req, res) => {
const collection = client.db('codes').collection('QR');
const result = await collection.insertOne(req.body);
res.send(result);
});
My problem is, that it doesnt work when I call my method inside Android Studio
public interface API {
@FormUrlEncoded
@POST("/items")
Call<Void> sendData(
@Field("data") String data
);
}
public void addStuff(String data){
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("data", data);
} catch (JSONException e) {
e.printStackTrace();
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://localhost:3000")
.addConverterFactory(ScalarsConverterFactory.create())
.build();
API api = retrofit.create(API.class);
Call<Void> call = api.sendData(jsonObject.toString());
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) {
if (response.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Successfully added data to the Database", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Error getting data from the database" + response.message(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_LONG).show();
}
});
}
After I scanned a code with my App, I get an dialog that asks me what to do next. One of those options is a Button "Add to Database", where I call the method above.
For Testing purpose I just hard coded an example String that gets passed to my method.
After that, I get the "Failure" Toast.
Tried to attach the debugger to the App, but that didnt really work out, at least Icouldnt figure where the error lies. I tried to to wrap the String into a JSONObject, and send it after I use the toString() Method on the provided data, and I tried to change the data type in the API Interface to JSONObject and send an actual JSONObject, instead of calling the onString() method on the data.
All of it results in failure.
If someone is interested, or might be in the same position as me: I found the solution for my problem.
The problem was that I actually didnt encode my Data .. so I either had to encode it with base64, or use this in the AndroidManifest.xml:
android:usesCleartextTraffic="true"
Hope it helps