Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android截击如何接收和发送json_Android_Json_Android Studio_Android Volley - Fatal编程技术网

Android截击如何接收和发送json

Android截击如何接收和发送json,android,json,android-studio,android-volley,Android,Json,Android Studio,Android Volley,我制作了一个应用程序,在特定的部分我发送一个字符串并接收一个json。我用截击 它工作得很好,但现在我需要发送一个json 这是我的密码: public static final String DATA_URL = "http://unynote.esy.es/cas/read_allorder.php?id="; // THIS HAVE TO CHANGE JUST TO LOCALHOST:8080/LOGIN 在这里: 这是截击代码的一部分 public class TabsAct

我制作了一个应用程序,在特定的部分我发送一个字符串并接收一个json。我用截击 它工作得很好,但现在我需要发送一个json

这是我的密码:

 public static final String DATA_URL = "http://unynote.esy.es/cas/read_allorder.php?id=";  // THIS HAVE TO CHANGE JUST TO LOCALHOST:8080/LOGIN
在这里:

这是截击代码的一部分

public class TabsActivity extends AppCompatActivity implements  
 View.OnClickListener {

private EditText editTextId;
private Button buttonGet;
private TextView textViewResult;

private ProgressDialog loading;

int cont=1;
String[ ] contenido = new String[7];
String f="";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mainint);

    editTextId = (EditText) findViewById(R.id.editTextId);
    buttonGet = (Button) findViewById(R.id.buttonGet);
    textViewResult = (TextView) findViewById(R.id.textViewResult);

    buttonGet.setOnClickListener(this);
}

private void getData() {
    String id = editTextId.getText().toString().trim();
    if (id.equals("")) {
        Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
        return;
    }
    loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);

    String url = Config.DATA_URL+editTextId.getText().toString().trim();

    StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            loading.dismiss();
            Toast.makeText(getBaseContext(), "si", Toast.LENGTH_LONG).show();

            showJSON(response);
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(TabsActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
                }
            });

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

private void showJSON(String response){

   // Toast.makeText(getBaseContext(), response, Toast.LENGTH_LONG).show();

    String name="";
    String address="";
    String grupo = "";
    String aula = "";
    String dia = "";
    String inicio = "";
    String fin = "";



    try {
        Toast.makeText(getBaseContext(), "LOGIN... ", Toast.LENGTH_LONG).show();
        JSONObject jsonObject = new JSONObject(response);

        JSONArray ja = jsonObject.getJSONArray("orders");
        // JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
        for (int i = 0; i < ja.length(); i++) {
            JSONObject collegeData = ja.getJSONObject(i);
            name = collegeData.getString("id");
            address = collegeData.getString("item");
             grupo = collegeData.getString("GRUPO_SECCION");
             aula = collegeData.getString("AULA");
             dia = collegeData.getString("DIA");
             inicio = collegeData.getString("INICIO");
             fin = collegeData.getString("FIN");

            ///database
            DBAdapter db= new DBAdapter(this);

            db.open();
            long id = db.insertContact(address, aula,dia,inicio,fin );
            db.close();

            db.open();
            Cursor c = db.getAllContacts();
            if (c.moveToFirst())
            { do{
                contenido=getcontenido(c);

            }while (c.moveToNext());
            }
            db.close();
            cont= Integer.parseInt( contenido[0]);
            /// database

            /// alarms
            int [] time;
            time = parsetime(inicio);

            int horai = time[0];
            int minutoi = time[1];
            int diaa = getDay(dia);

            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(System.currentTimeMillis());
            cal.set(Calendar.HOUR_OF_DAY, horai);
            cal.set(Calendar.MINUTE, minutoi);
            cal.set(Calendar.DAY_OF_WEEK, diaa);
            cal.add(Calendar.SECOND, 2);


            Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
            intent.putExtra("name", address);
            //intent.putExtra("curos bn",1);
            PendingIntent pendingIntent =
                    PendingIntent.getBroadcast(getBaseContext(),
                            cont+1, intent, PendingIntent.FLAG_UPDATE_CURRENT );




            AlarmManager alarmManager =
                    (AlarmManager)getSystemService(Context.ALARM_SERVICE);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    cal.getTimeInMillis(), 24 * 7 * 60 * 60 * 1000 , pendingIntent);


            ////alarms



            f=f+"codigo alumno:\t"+name+"\ncodigo/nombre curso:\t" +address+ "\ngrupo:\t"+grupo+"\naula:\t"
            +aula+"\ndia:\t"+dia+"\ninicio:\t"+inicio+"\nfin:\t"+fin+"\n:\t";

        }
        //  Toast.makeText(getBaseContext(),  collegeData.length(), Toast.LENGTH_LONG).show();
        //collegeData.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    textViewResult.setText(f);
}
public类TabsActivity扩展了AppCompativity实现
View.OnClickListener{
私有EditText-editTextId;
私人按钮按钮;
私有文本视图文本视图结果;
私有对话框加载;
int cont=1;
String[]contenido=新字符串[7];
字符串f=“”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u maiint);
editTextId=(EditText)findViewById(R.id.editTextId);
buttonGet=(按钮)findViewById(R.id.buttonGet);
textViewResult=(TextView)findViewById(R.id.textViewResult);
setOnClickListener(这个);
}
私有void getData(){
字符串id=editTextId.getText().toString().trim();
if(id.equals(“”){
Toast.makeText(这是“请输入id”,Toast.LENGTH_LONG.show();
返回;
}
loading=ProgressDialog.show(这是“请稍候…”、“正在获取…”、false、false);
String url=Config.DATA_url+editTextId.getText().toString().trim();
StringRequest StringRequest=新的StringRequest(url,new Response.Listener()){
@凌驾
公共void onResponse(字符串响应){
loading.dispose();
Toast.makeText(getBaseContext(),“si”,Toast.LENGTH_LONG.show();
showJSON(响应);
}
},
新的Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Toast.makeText(TabsActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG.show();
}
});
RequestQueue RequestQueue=Volley.newRequestQueue(this);
添加(stringRequest);
}
私有void showJSON(字符串响应){
//Toast.makeText(getBaseContext(),response,Toast.LENGTH_LONG.show();
字符串名称=”;
字符串地址=”;
字符串grupo=“”;
字符串aula=“”;
字符串直径=”;
字符串inicio=“”;
字符串fin=“”;
试一试{
Toast.makeText(getBaseContext(),“LOGIN…”,Toast.LENGTH_LONG.show();
JSONObject JSONObject=新JSONObject(响应);
JSONArray ja=jsonObject.getJSONArray(“订单”);
//JSONArray result=jsonObject.getJSONArray(Config.JSON_数组);
对于(int i=0;i
我只是发送了字符串editTextId.getText()。这是每个用户的代码,但现在我需要发送一个带有该字符串的json

“CCODUSU”“45875621”


CCODUSU是标识符

我想看看StringRequests。下面是一个如何将内容发送到PHP文件的示例,该文件可以更新数据库,也可以执行任何操作:

SetMyStuff.java:

package com.example.your_app.database_requests;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

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

public class SetMyStuff extends StringRequest {

    private static final String LOGIN_REQUEST_URL = "http://example.com/SetMyStuff.php";
    private Map<String, String> params;

    public SetMyStuff(String username, String password, Response.Listener<String> listener) {
        super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
        params = new HashMap<>();
        params.put("username", username);
        params.put("password", password);
    }

    @Override
    public Map<String, String> getParams() {
        return params;
    }

}
package com.example.your_app.database_请求;
导入com.android.volley.Request;
导入com.android.volley.Response;
导入com.android.volley.toolbox.StringRequest;
导入java.util.HashMap;
导入java.util.Map;
公共类SetMyStuff扩展了StringRequest{
私有静态最终字符串登录\u请求\u URL=”http://example.com/SetMyStuff.php";
私有映射参数;
public SetMyStuff(字符串用户名、字符串密码、Response.Listener){
super(Request.Method.POST,LOGIN\u Request\u URL,listener,null);
参数=ne
package com.example.your_app.database_requests;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

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

public class SetMyStuff extends StringRequest {

    private static final String LOGIN_REQUEST_URL = "http://example.com/SetMyStuff.php";
    private Map<String, String> params;

    public SetMyStuff(String username, String password, Response.Listener<String> listener) {
        super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
        params = new HashMap<>();
        params.put("username", username);
        params.put("password", password);
    }

    @Override
    public Map<String, String> getParams() {
        return params;
    }

}
Response.Listener<String> listener = new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);

                        boolean success = jsonResponse.getBoolean("success");

                        if (!success) {
                            Log.e(TAG, "Could not update stuff.");
                        } else {
                            Log.e(TAG, "Updated stuff.");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };
            SetMyStuff setMyStuffRequest = new SetMyStuff(username, password, listener);
            RequestQueue requestQueue = Volley.newRequestQueue(context);
            requestQueue.add(setMyStuffRequest);
<?php

    $password = $_POST["password"];
    $username = $_POST["username"];

    $con = mysqli_connect("website.com", "dbusername", "dbpassword", "dbtable");

    $response = array();
    $response["success"] = false;

    /* Do something */
    $response["success"] = true;

    echo json_encode($response);
?>
'CCODUSU' '45875621'
{"CCODUSU": "45875621"}
public class AppJSONObjectRequest extends JsonObjectRequest{

private Response.Listener<JSONObject> listener;
private Map<String, String> headers;

public AppJSONObjectRequest(int method, String url, JSONObject jsonObject, Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener, Map<String, String> headers) {
    super(method, url, jsonObject, reponseListener, errorListener);
    this.headers = headers;
    this.listener = reponseListener;
}

@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
    try {
        String jsonString = new String(response.data,
                HttpHeaderParser.parseCharset(response.headers));
        return Response.success(new JSONObject(jsonString),
                HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    }
}

@Override
protected void deliverResponse(JSONObject response) {
    listener.onResponse(response);
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    return headers;
}
}
JSONObject parameters = new JSONObject();
    try {

        parameters.put("f_name", "name1");
        parameters.put("l_name", "name2");
        .......


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

    AppJSONObjectRequest objectRequest = new AppJSONObjectRequest(Request.Method.PUT, url, parameters, RequestSuccessListener, RequestErrorListener, getHeaders); //headers if u have
    //url: your request base url

    VolleySingleton volleySingleton = VolleySingleton.getInstance(this);
    volleySingleton.addToRequestQueue(objectRequest);
Response.Listener<JSONObject> RequestSuccessListener = new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {

        Log.i(TAG, "Response" + " " + response);

    }
};

Response.ErrorListener RequestErrorListener = new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        error.printStackTrace();

    }
};
public Map<String, String> getHeaders() {

    Map<String, String> headers = new HashMap<>();
    headers.put("x-auth-token", Constant.API_KEY_X_AUTH_TOKEN);
    return headers;
}
public class VolleySingleton {
private static VolleySingleton mInstance;
private Context mContext;
private RequestQueue mRequestQueue;


private VolleySingleton(Context context){
    this.mContext = 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) {
        // getApplicationContext() is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
    }
    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req){
    getRequestQueue().add(req);
}
}