Error inserting PHP MySql data using the Android volley lib

4

I'm developing an application that will have to send data to a server.

My php source code is this:

connection.php

<?php
    $mysql_hostname = "localhost";
    $mysql_user = "root";
    $mysql_password = "";
    $mysql_database = "app";

    $db = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong");
    mysql_select_db($mysql_database, $db) or die("Opps some thing went wrong");

?>

insert.php

<?php
        error_reporting(0);
        include("connection.php");

       // vetor response
       $response = array();

       if( !(empty($_POST['matricula']))){
           //variaveis recebendo os valores pelo método POST
           $matricula=$_POST['matricula'];
           $cpf=$_POST['cpf'];
           $placa=$_POST['placa'];

           $result = mysql_query("INSERT INTO myorder(idUser,matricula,cpf,placa) VALUES('','$matricula','$cpf','$placa')");   
           if($result>0){
              $response["success"] = 1;
           }   
           else{
              $response["success"] = 0;
           }

        echo json_encode($response);
      }

?>

xml :

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/et_cad_matr_car"
    android:hint="@string/text_view_matricula_cad"
    android:layout_below="@+id/textView_cad_main2"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"
    android:id="@+id/et_cad_cpf"
    android:hint="@string/texte_view_cpf"
    android:layout_below="@+id/et_cad_matr_car"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/et_placa_car"
    android:hint="@string/et_placa_car"
    android:inputType="text"
    android:layout_below="@+id/et_cad_cpf"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_cad_ok"
    android:id="@+id/button2"
    android:layout_below="@+id/et_placa_car"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:onClick="insert"/>

So I created a class called ConMain2.java to put various methods of lib volley.

The methods getInstance() , getReqQueue() , addToReqQueue() .

package br.fepi.caronasfepi;
import android.support.v7.app.AppCompatActivity;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class ConMain2 extends AppCompatActivity {

private RequestQueue mRequestQueue;
private static ConMain2 mInstance;

public static synchronized ConMain2 getInstance() {
    return mInstance;
}

public RequestQueue getReqQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public <T> void addToReqQueue(Request<T> req, String tag) {

    getReqQueue().add(req);
}

public <T> void addToReqQueue(Request<T> req) {

    getReqQueue().add(req);
}

public void cancelPendingReq(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
 }

}

And finally my activity Main2.java

package br.fepi.caronasfepi;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;


public class Main2 extends AppCompatActivity {


   EditText matricula;
   EditText cpf;
   EditText placa;
   String item_matricula;
   String item_cpf;
   String item_placa;
   RequestQueue requestQ;
   ProgressDialog PD;
   String url = "000.000.000.000/insert.php";

   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main2);//chamando o arquivo xml para a classe


    PD = new ProgressDialog(this);
    PD.setMessage("Carregando.....");
    PD.setCancelable(false);

    matricula = (EditText) findViewById(R.id.et_cad_matr_car);
    cpf = (EditText) findViewById(R.id.et_cad_cpf);
    placa = (EditText) findViewById(R.id.et_placa_car);
}
    public void insert(View v){

        PD.show();
        item_matricula = matricula.getText().toString();
        item_cpf = cpf.getText().toString();
        item_placa = placa.getText().toString();
            StringRequest postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    PD.dismiss();
                    matricula.setText("");
                    cpf.setText("");
                    placa.setText("");
                    Toast.makeText(getApplicationContext(),
                            "Data Inserted Successfully",
                            Toast.LENGTH_SHORT).show();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    PD.dismiss();
                    Toast.makeText(getApplicationContext(),
                            "Fail", Toast.LENGTH_SHORT).show();
                }
            }) {
                @Override
                protected Map<String, String> getParams(){
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("matricula", item_matricula);
                    params.put("cpf", item_cpf);
                    params.put("placa", item_placa);
                    return params;
                }
            };
        ConMain2.getInstance().addToReqQueue(postRequest);
        }




public void back_tb(View View) {
    finish();
}
}

I'm testing the url by the IP of my server.

The error is that when I click the button to enter data the following message appears

  

"Unfortunately app has stopped"

And do not insert anything into the bank.

I'm following this tutorial

    
asked by anonymous 30.10.2015 / 20:55

1 answer

2

By analyzing the posted code and based on the above mentioned tutorial, I think the error occurs in the line ConMain2.getInstance().addToReqQueue(postRequest);

The first reason is that the ConMain2 class does not initialize the mInstance variable that is returned by the ConMain2.getInstance() method.

If you check the code you have implemented you will find that it does not conform to the tutorial in the following ways:

    The ConMain2 class should inherit from Application and not from AppCompatActivity
  • The onCreate() method must be implemented, where the mInstance variable is initialized.

Make the following changes:

Change

public class ConMain2 extends AppCompatActivity 

for

public class ConMain2 extends Application

Implement method onCreate() :

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}

The tutorial does not reference but it is necessary for the ConMain2 class to be created, include in the AndroidManifest.xml tag <application> the following attribute:

android:name=".ConMain2"

Allow me a small note:
The use of tutorials is very useful. Everything I learned related to Android was appealing to them. But, there is always one, but this was only achieved because I always tried to understand how the code works before using it. You only learn by understanding.

    
07.11.2015 / 16:29