I need to send data to the database, and I'm using PHP. I was trying through the Ion library, but because it was asynchronous, the application featured NullPointerExceptions when I had more than one data being sent. I tried to implement okHttp, but also to no avail.
EDIT: I tried to implement with Retrofit, as I was suggested, but I did not succeed. Here is the code below:
RetrofitClient
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseURL) {
if (retrofit == null) {
retrofit = new Retrofit.Builder().baseUrl(baseURL).addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
PersonService
public interface PessoaService {
@POST("/sync_pessoas")
@FormUrlEncoded
Call<Pessoa> savePost(@Body Pessoa post);
}
AppUtils
public class ApiUtils {
private ApiUtils() {}
public static PessoaService getPessoaService(String url) {
return RetrofitClient.getClient(url).create(PessoaService.class);
}
}
MainActivity.java
private void sendPost(Pessoa p) {
pessoaService.savePost(p).enqueue(new retrofit2.Callback<Pessoa>() {
@Override
public void onResponse(retrofit2.Call<Pessoa> call, retrofit2.Response<Pessoa> response) {
if (response.isSuccessful()) {
Log.i("RESPONSE", response.body().toString());
}
}
@Override
public void onFailure(retrofit2.Call<Pessoa> call, Throwable t) {
Log.e("ERROR", "Incapaz de submeter API");
}
});
}
private void syncTablePessoasWithRetrofit() {
pessoaService = ApiUtils.getPessoaService("http://"+Preferences.getString(MainActivity.this, "ip")+"/PesquisaPet/");
final ProgressDialog dialog = ProgressDialog.show(MainActivity.this, "Sincronizando", "Por favor, aguarde", true, false);
new Thread(new Runnable() {
ArrayList<Pessoa> pessoas = (new Pessoa()).getAllNotSincronized(MainActivity.this);
@Override
public void run() {
for (int i = 0; i < pessoas.size(); i++) {
sendPost(pessoas.get(i));
}
dialog.dismiss();
}
}).start();
}
Person.java
public class Pessoa {
private SQLiteDatabase db;
private Cursor cursor;
@SerializedName("id")
@Expose
private long id;
@SerializedName("nome")
@Expose
private String nome;
@SerializedName("bairro")
@Expose
private String bairro;
@SerializedName("telefone")
@Expose
private String telefone;
@SerializedName("cadastrado_por")
@Expose
private String cadastradoPor;
@SerializedName("data_cadastro")
@Expose
private long dataCadastro;
}
Script php that would receive the data and send it to the bank
<?php
include_once('database/Database.class.php');
$db = new Database();
$stmt = $db->query("SELECT MAX(pessoa_id) AS pessoa_id FROM Controle_id");
$controleIDs = $stmt->fetch();
$values = array(
":id" => $controleIDs->pessoa_id,
":nome" => $obj->{'nome'},
":bairro" => $obj->{'bairro'},
":telefone" => $obj->{'telefone'},
":cadastrado_por" => $obj->{'cadastrado_por'},
":data_cadastro" => $obj->{'data_cadastro'}
);
//echo json_encode(array("success" => true, "id" => $_POST['id']));
$stmt = $db->query("INSERT INTO Pessoas (id, nome, bairro, telefone, cadastrado_por, data_cadastro) VALUES (:id, :nome, :bairro, :telefone, :cadastrado_por, :data_cadastro)", $values);
if ($stmt->rowCount() > 0) {
$statement = $db->query("UPDATE Controle_id SET pessoa_id = pessoa_id + 1");
if ($statement->rowCount() > 0) {
echo json_encode(array("success" => true, "id" => $_POST['id'], "controle_id" => $controleIDs->pessoa_id));
} else {
echo json_encode(array("success" => true, "id" => $_POST['id']));
}
} else {
echo json_encode(array("success" => false));
}
?>
My Log shows the following errors:
Process: br.com.ufrn.marceloaugusto.pesquisapet, PID: 28476
java.lang.StackOverflowError: stack size 1037KB
at com.google.gson.internal.$Gson$Types.checkNotPrimitive($Gson$Types.java:434)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:551)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:546)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:553)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:546)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:553)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:546)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:553)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:546)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:553)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:546)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:553)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:546)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:553)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:546)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:553)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:546)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:553)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:546)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:553)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:546)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:553)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:546)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:553)
at com.google.gson.internal.$Gson$Types.canonicalize($Gson$Types.java:111)
at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.<init>($Gson$Types.java:546)
at
07-31 09:36:44.017 28476-28476/br.com.ufrn.marceloaugusto.pesquisapet E/WindowManager: android.view.WindowLeaked: Activity br.com.ufrn.marceloaugusto.pesquisapet.MainActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{afd68b9 V.E...... R......D 0,0-684,321} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:368)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:299)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:86)
at android.app.Dialog.show(Dialog.java:319)
at android.app.ProgressDialog.show(ProgressDialog.java:116)
at android.app.ProgressDialog.show(ProgressDialog.java:104)
at br.com.ufrn.marceloaugusto.pesquisapet.MainActivity.syncTablePessoasWithRetrofit(MainActivity.java:131)
at br.com.ufrn.marceloaugusto.pesquisapet.MainActivity.onOptionsItemSelected(MainActivity.java:95)
at android.app.Activity.onMenuItemSelected(Activity.java:2986)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:368)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:65)
at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:202)
at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:780)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:963)
at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:624)
at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:150)
at android.view.View.performClick(View.java:5217)
at android.view.View$PerformClick.run(View.java:21198)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5451)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
EDIT 2: I tried to implement also with Volley, following a tutorial, but I could not make the request synchronous.
MainActivity.java
private void syncTablePessoasWithVolley() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Suncronizando..");
progressDialog.show();
final ArrayList<Pessoa> pessoas = (new Pessoa()).getAllNotSincronized(this);
for (int i=0; i < pessoas.size(); i++) {
final int finalI = i;
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://" + Preferences.getString(MainActivity.this, "ip") + "/PesquisaPet/sync_pessoas.php", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
Log.i("STRING_RESPONSE", "["+response+"]");
JSONObject obj = new JSONObject(response);
if (!obj.getBoolean("success")) {
Log.d("RESPONSE_ID", obj.getString("id"));
} else {
Log.d("JSON_RESPONSE", "Erro");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.d("JSON_RESPONSE", "ErroResponse");
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("id", String.valueOf(pessoas.get(finalI).getId()));
params.put("nome", pessoas.get(finalI).getNome());
params.put("bairro", pessoas.get(finalI).getBairro());
params.put("telefone", pessoas.get(finalI).getTelefone());
params.put("cadastrado_por", pessoas.get(finalI).getCadastradoPor());
params.put("data_cadastro", String.valueOf(pessoas.get(finalI).getDataCadastro()));
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
}
VolleySingleton.java
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class VolleySingleton {
private static VolleySingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mCtx;
private VolleySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
}
public static synchronized VolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
}