Error inserting Mysql PHP data using Android Volley lib

Asked

Viewed 341 times

4

I am 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);
      }

?>

Of 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 Volley lib.

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 Victoria 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 am testing the url by my server IP.

The error is that when I click the insert button the following message appears

"Unfortunately app has stopped"

And you don’t put anything in the seat.

I’m following this one tutorial

1 answer

2


Analyzing the code posted and based on the tutorial cited, I think the error occurs in the line ConMain2.getInstance().addToReqQueue(postRequest);

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

If you check the code you have implemented you will see that it is not according to the tutorial, in the following aspects:

  • The class Conmain2 shall inherit from Application and not of Appcompatactivity

  • The method should be implemented onCreate(), where the variable is initialized mInstance.

Make the following changes:

Alter

public class ConMain2 extends AppCompatActivity 

for

public class ConMain2 extends Application

Implement the method onCreate():

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

The tutorial does not reference but is necessary, so that the class Conmain2 be created, include in Androidmanifest.xml within the 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 resorting to them.
But there’s always one, but that was only achieved because I’ve always tried to understand how the code works before I use it.
You only learn by understanding.

  • Thank you so much, you fixed my problem this my problem! But it still does not insert data in the database.

  • Is the PHP code correct? Don’t forget to put one ip valid in String url = "000.000.000.000/insert.php";

  • I rephrased the question, with the errors that appears in the logcat

  • The problem ("Unfortunately app has stopped") posed in this question is solved. You should create another question and expose the new problem.

  • Okay, I asked another question that can be found on this link http://answall.com/questions/99499/dados-n%C3%A3o-s%C3%A3o-inserted-do-android-para-o-mysql-using-Volley

Browser other questions tagged

You are not signed in. Login or sign up in order to post.