Reputation: 87
I making an app and in a specific part I send a string and receive a json. I USE VOLLEY It works good, but now i need to send a json.
HERE IS MY CODE:
public static final String DATA_URL = "http://unynote.esy.es/cas/read_allorder.php?id="; // THIS HAVE TO CHANGE JUST TO LOCALHOST:8080/LOGIN
HERE:
public class Config {
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 static final String KEY_NAME = "COD_ALUMNO";
public static final String KEY_ADDRESS = "COD_ASIGNATURA";
public static final String KEY_VC = "GRUPO_SECCION";
public static final String KEY_AULA = "AULA";
public static final String KEY_DIA = "DIA";
public static final String KEY_INICIO = "INICIO";
public static final String KEY_FIN = "FIN";
public static final String JSON_ARRAY = "result";
}
AND HERE IS THE PART OF VOLLEY CODE
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);
}
I JUS SENT THE STRING editTextId.getText() . That is a code for each user , but now i need to send a json with that string .
'CCODUSU' '45875621'
CCODUSU is the identifier
Upvotes: 1
Views: 545
Reputation: 2949
I also came up with this same issue.On the course of finding way I have developed a way that might help you. If you want to post json to the server then you can create JsonObjectRequest as:
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;
}
}
And then you can use this jave file in your activity or fragment to send json and recieve response like this below:
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);
And you can receive json as :
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();
}
};
you can get headers as:
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("x-auth-token", Constant.API_KEY_X_AUTH_TOKEN);
return headers;
}
VolleySingleton class
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);
}
}
Just you can implement above sample... then hope you will get what you want.it may be copy paste code but it covers overall enough to solve your problem.
Upvotes: 0
Reputation: 725
I would take a look at StringRequests. Here is an example of how to send things to a PHP file, which updates a database, or can do whatever:
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;
}
}
To call this StringRequest:
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);
The PHP file that recieves this:
<?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);
?>
Upvotes: 2
Reputation: 3237
Do you mean you need send a JSON
which contains the editTextId.getText().toString().trim()
, if you want to do this, you must spell out a complete and correct JSON
.
'CCODUSU' '45875621'
The string you post is not a json
, you need to modify it into this:
{"CCODUSU": "45875621"}
Once you give this string after your Config.DATA_URL
, the server will receive the id
parameter and it is the JSON
.
Upvotes: 0