Skip to content Skip to sidebar Skip to footer

How To Send Json Array Containg Jsonobjects To Php Server

Hello everyone I m sorry if this has been asked earlier , i have been searching for this solution since past 3 days.I am new in android and php. I want to know how can i send 'json

Solution 1:

Use StringRequest instead of JsonArrayRequest for example:

privatevoidregister() {

        if (!validate()) {

            onRegistrationFailed("Registration Failed");
            return;

        }
        final String name = et_username.getText().toString();
        final String email = et_email.getText().toString();
        final String phone = et_phone.getText().toString();
        final String password = et_password.getText().toString();

        showDialog();

        StringRequest strRequest = newStringRequest(Request.Method.POST, Config.MAIN_URL + Config.REGISTER,
                newResponse.Listener<String>() {
                    @OverridepublicvoidonResponse(String response) {
                        Log.d(TAG, "Register Response: " + response.toString());
                        hideDialog();
                        try {
                            JSONObject jsonObject = newJSONObject(response);

                            int status = jsonObject.getInt("status");
                            String msg = jsonObject.getString("message");

                            if (status == SUCCESS) {

                                onRegistrationSuccess(name,email);

                            } else {

                                onRegistrationFailed(msg);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                }, newResponse.ErrorListener() {
            @OverridepublicvoidonErrorResponse(VolleyError error) {
                Log.e(TAG, "Registration Error: " + error.getMessage());
                hideDialog();
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
            }
        }) {
            @OverrideprotectedMap<String, String> getParams() {
                // Posting params to register urlMap<String, String> params = newHashMap<String, String>();
                params.put(Config.KEY_USERNAME, name);
                params.put(Config.KEY_EMAIL, email);
                params.put(Config.KEY_PHONE, phone);
                params.put(Config.KEY_PASSWORD, password);
                return params;
            }

        };

        // Adding request to request queueAppController.getInstance().addToRequestQueue(strRequest);

    }

Solution 2:

This is working code for login sample. so try this, and change as per your need.

Login.java

package com.example.volleytest;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
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;

import org.json.JSONException;
import org.json.JSONObject;

publicclassLoginextendsAppCompatActivity{

publicstatic final StringLOGIN_URL = "YOUR_URL";
                                        //"http://192.168.1.100/Login/admin.php";ProgressDialog pDialog;

publicstatic final StringKEY_USERNAME="username";
publicstatic final StringKEY_PASSWORD="password";

privateEditText editTextUsername;
privateEditText editTextPassword; 
privateButton buttonLogin;

privateString username;
privateString password;

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stubsuper.onCreate(savedInstanceState);
    setContentView(R.layout.login);

        editTextUsername = (EditText) findViewById(R.id.editTextUsername);
        editTextPassword = (EditText) findViewById(R.id.editTextPassword);

        buttonLogin = (Button) findViewById(R.id.buttonLogin);

        buttonLogin.setOnClickListener(newView.OnClickListener() {

            @OverridepublicvoidonClick(View v) {
                // TODO Auto-generated method stubif(isNetworkAvailable()){
                userLogin();
                }
                else
                {
                    showMessageDialog("Error", "Check your Internet Connection..!");
                }
            }
        });
}

privatevoiduserLogin() {
    username = editTextUsername.getText().toString().trim();
    password = editTextPassword.getText().toString().trim();

    pDialog = newProgressDialog(this);
    pDialog.setMessage("Loading...");
    pDialog.show(); 

    StringRequest stringRequest = newStringRequest(Request.Method.POST, LOGIN_URL,
            newResponse.Listener<String>() {
                @OverridepublicvoidonResponse(String response) {

                    try {
                        //JSONArray myJSON= new JSONArray(response);JSONObject parentObject = newJSONObject(response);
                            JSONObject childObject = parentObject.getJSONObject("Tracking"); 

                              String status = childObject.optString("status");
                              Stringtype = childObject.optString("type");

                              //System.out.println("status : " + status);//System.out.println("Type : " + type);if(status.trim().equals("success"))
                                {
                                    pDialog.hide();
                                    showMessageDialog("Login", type + " Login Successfully..!");
                                }
                                else
                                {
                                    pDialog.hide();
                                    showMessageDialog("Login", "No Users/Admin were Found..! ");
                                }


                    } catch (JSONException e) {
                        // TODO Auto-generated catch block//e.printStackTrace();
                        pDialog.hide();
                        showMessageDialog("JSON Error", "Server Error..! Try after Some Time..!");//e.getMessage());
                    }

                }
            },
            newResponse.ErrorListener() {
                @OverridepublicvoidonErrorResponse(VolleyError error) 
                {
                    pDialog.hide();
                    //showMessageDialog("Login", "Reponse => " + error.toString());showMessageDialog("Login", "Server Error..! Try after Some Time..!");
                }
            }){
        @OverrideprotectedMap<String, String> getParams() throws AuthFailureError {
            Map<String,String> map = newHashMap<String,String>();
            map.put(KEY_USERNAME,username);
            map.put(KEY_PASSWORD,password);
            return map;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

publicvoidshowMessageDialog(String title , String Message)
{
    AlertDialog dialog = newAlertDialog.Builder(Login.this)
    .setTitle(title)
    .setMessage(Message)
    .setPositiveButton("Ok", newDialogInterface.OnClickListener() {

        @OverridepublicvoidonClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            dialog.dismiss();

        }
    })

    .show();

    //TextView textView = (TextView) dialog.findViewById(android.R.id.message);//textView.setTextSize(25); 

}

  privatebooleanisNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService( CONNECTIVITY_SERVICE );
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

}

login.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"android:orientation="vertical"android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"android:paddingBottom="@dimen/activity_vertical_margin"
>

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textSize="20dp"
    android:text="Login Using Volley Library"
    />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:text="Enter Username"
    />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/editTextUsername" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Enter Password"
    />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPassword"
    android:id="@+id/editTextPassword" />

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Login"
    android:id="@+id/buttonLogin" />

</LinearLayout>

Post a Comment for "How To Send Json Array Containg Jsonobjects To Php Server"