如何将包含jsonobjects的JSON数组发送到php服务器 [英] How to send JSON array containg jsonobjects to php server

查看:106
本文介绍了如何将包含jsonobjects的JSON数组发送到php服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,很抱歉,这是我早些时候问到的,因为过去3天以来我一直在寻找这种解决方案. 我想知道如何将"jsonArray"(如下所示)发送到我的php服务器,然后提取php中收到的jsonobject值. 我尝试了jsonarrayrequest和hashmap,但无法发送.请帮忙.

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 "jsonArray"(shown below) to my php server and then extract jsonobject values recieved in php. I have tried jsonarrayrequest and hashmap but was not able to send. Please help.

String url="http://192.168.43.210/jjj.php";
JSONArray list;
RequestQueue requestQueue;
final JSONArray jsonArray=new JSONArray();

for (int i=0;i<valu;i++)
{
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("comptext",smslist.get(i).completeText);
jsonObject.put("amount",smslist.get(i).amount);
jsonObject.put("txntype",smslist.get(i).txnType);
jsonObject.put("party",smslist.get(i).party);
jsonObject.put("from",smslist.get(i).fromNo);
jsonObject.put("datetime",smslist.get(i).dateTime);
jsonArray.put(jsonObject);

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


 JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.POST, url, new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {

                    result.append("Successfully sent");
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                protected Map<JSONArray,JSONArray> getparams() throws AuthFailureError{
                    Map<JSONArray,JSONArray> parameters = new HashMap<JSONArray, JSONArray>();
                    parameters.put(list,jsonArray);
                    return parameters;

                }
            };
            requestQueue.add(jsonArrayRequest);

        }


    });

推荐答案

这是登录示例的工作代码.因此,请尝试此操作,然后根据需要进行更改.

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

Login.java

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;

public class Login extends AppCompatActivity{

public static final String LOGIN_URL = "YOUR_URL";
                                        //"http://192.168.1.100/Login/admin.php";
ProgressDialog pDialog;

public static final String KEY_USERNAME="username";
public static final String KEY_PASSWORD="password";

private EditText editTextUsername;
private EditText editTextPassword; 
private Button buttonLogin;

private String username;
private String password;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.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(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                if(isNetworkAvailable()){
                userLogin();
                }
                else
                {
                    showMessageDialog("Error", "Check your Internet Connection..!");
                }
            }
        });
}

private void userLogin() {
    username = editTextUsername.getText().toString().trim();
    password = editTextPassword.getText().toString().trim();

    pDialog = new ProgressDialog(this);
    pDialog.setMessage("Loading...");
    pDialog.show(); 

    StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {
                        //JSONArray myJSON= new JSONArray(response);

                            JSONObject parentObject = new JSONObject(response);
                            JSONObject childObject = parentObject.getJSONObject("Tracking"); 

                              String status = childObject.optString("status");
                              String type = 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());
                    }

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) 
                {
                    pDialog.hide();
                    //showMessageDialog("Login", "Reponse => " + error.toString());
                    showMessageDialog("Login", "Server Error..! Try after Some Time..!");
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> map = new HashMap<String,String>();
            map.put(KEY_USERNAME,username);
            map.put(KEY_PASSWORD,password);
            return map;
        }
    };

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

public void showMessageDialog(String title , String Message)
{
    AlertDialog dialog = new AlertDialog.Builder(Login.this)
    .setTitle(title)
    .setMessage(Message)
    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            dialog.dismiss();

        }
    })

    .show();

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

}

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

}

login.xml

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>

这篇关于如何将包含jsonobjects的JSON数组发送到php服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆