Remove first position of List NameValuePair - android

Hi all I have a List where I add parameters, whcih I use to connect and do operations in a MySQL with the help of PHP script. The PHP script expects a "id", which is a int that retrieves from Android app. However, although I send the intent with the correct id the List NameValuePairs converts it to a especific format in this case. For example, if the id is 2 the final params will be id=2, which is a String that the PHP script does not understand. I would like to know if there is a way of removing the first characters and instead of id=2, only send 2.
Here is the code I use
public void monitorizar() throws Exception{
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", id));
JSONObject json = jsonParser.makeHttpRequest(url_detalles, "GET", params);
Log.d("params", String.valueOf(params));
ArrayList<HashMap<String, String>> temp;
temp = new ArrayList<HashMap<String, String>>();
Obviously, when I send the params to the php script, it gives me an error because the id is not an integer and it is written with this format id="id".

Related

JSON Array with RequestParams in Android Asynchronous Http Client

I have trouble to send a JSON POST Request to my server.
My server accept a POST with application/json as type and an example would be like this:
{
"name": "Group4",
"users": [
{"email": "user#example.org"},
{"email": "user2#example.org"},
]
}
If I send this by a REST client I get 200 OK as response, everything fine.
My Android client uses the Android Async HTTP Library (http://loopj.com/android-async-http/) and a documentation to the RequestParams class is here https://loopj.com/android-async-http/doc/com/loopj/android/http/RequestParams.html
RequestParams params = new RequestParams();
String userName = getUserName();
List<String> userList = getUserList();
params.put("name", userName);
JSONArray users = new JSONArray();
for(String user : userList) {
JSONObject obj = new JSONObject();
try {
obj.put("email", user);
} catch (JSONException e) {
// ...
}
users.put(obj);
}
params.put("users", users);
I thought this will create exactly a JSON like my example. I don't know if I have the possibility to get a JSON string of this RequestParams. I only can access the parameter as a String:
name=Test&users=[{"email":"user#example.org"}, {"email":"user2#example.org"}]
My server don't even accept the request and fails directly with the error:
AttributeError: 'unicode' object has no attribute 'iteritems'
The problem has to be at the point where I create the RequestParams. Can someone tell me what is wrong with that? I thought I have to create an array with name "users" and then add objects in it with key-value items.
Just put List<> to your RequestParams. Here is the example:
RequestParams params = new RequestParams();
List<String> list = new ArrayList<String>(); // Ordered collection
list.add("Java");
list.add("C");
params.put("languages", list);
//above code will generate url params: "languages[0]=Java&languages[1]=C"
So you don't need to add it manually using Loop sequence.
See the docs here
Will recommend to use Volley for Async calls in Android https://developer.android.com/training/volley/index.html

is it possible to Insert data from android to MySQL thorugh PHP But define the namevaluepair inside button onClick?

I've tried to find many post on Stack Overflow question, then I found a useful post about that on here.
But on that link, I found some code like that inside new class :
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
Actually I want to define the data inside button OnClick, Because I got all string through loop for.
For the example :
int size = adapter3.getCount();
for (int i=0;i<size;i++){
id = adapter3.getItem(i).getId();
nilai = String.valueOf(adapter3.getItem(i).getRatingStar());
PostDataTOServer p = new PostDataTOServer(); // call the class insert
p.execute(id, nilai);
}
So, everytime I loop, I need to call the insert class that define the String in button.
Is there any method how to do like I need?
In your class PostDataTOServer you can create a method in which you fill the NameValuePair list, e.g.
public class PostDataTOServer{
private List<NameValuePair> values;
// here I use an HashMap because I need a <K,V> object
public void setDataToSend(HashMap<String,String> datas){
//TODO: make a check on the size of HashMap
values = new ArrayList<NameValuePair>(datas.size());
//iterate the HashMap and fill the valuePair
for(Map.Entry<String, String> entry : datas.entrySet()){
values.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
....
}
and in your for loop you must call
p.setDataToSend(hashMap) // p = new PostDataTOServer();
Then in doInBackground, you can use directly the valuePair created
httppost.setEntity(new UrlEncodedFormEntity(this.values));

How to send an Object as JSON to a Server using NameValuePairs?

I am attempting to add some Book(title, author, year) into my book table in a server using an AsyncTask, but i am getting missing bookobject as JSONfrom the method addBook(from the server). So i made a bookObject like this:
JSONObject jObj = new JSONObject();
jObj.put("title", "JAVA");
jObj.put("author", "me");
jObj.put("year", 2005);
After that, i wanna use(my intention is to send this book Object):
List<NameValuePair> nameValuePairs = new ArrayList<>(1);
nameValuePairs.add(new BasicNameValuePair(jObj)); //Error
new AaaBookAsyncTask(this).execute(new Pair<>(nameValuePairs, httpClient));
The problem is BasicNameValuePaircannot applied to JSONObject, but now how can i send the book Object? - Any help or hints is very appreciated.Thanks, Carl
You could send the JSON as a string and then decode it on your server before storing it in your database.

How to send JSON object over request to web service in android

I would like to pass JSON object as request to web service like i mentioned below.
Result:{
"email":"xxxxxxx",
"password":"xxxxxx",
"Marks":[
{
"mark1":"50",
"mark2":"70"
}
],
"firstname":"xxxx",
"lastname":"xxxxx"
}
My code:
...
HttpPost httppost = new HttpPost("My Url");
httppost.setEntity(new StringEntity(**message**.toString(), "UTF-8"));
Here message should have json object in above format.How could i format JSON object?
Thanks.
If you arer having trouble in implementing above json object at android side then you can construct it like below,
JSONObject message = new JSONObject();
JSONObject mParams = new JSONObject();
mParams.put("email", "xxxx");
mParams.put("password", "xxx");
JSONArray markArray = new JSONArray();
JSONObject markObj = new JSONObject();
markObj.put("mark1", "50");
markObj.put("mark2", "70");
markArray.put(markObj);
mParams.put("Marks", markArray);
mParams.put("FirstName", "xxxx");
mParams.put("lastname", "xxxx");
message.put("Result",mParams);
Now in your code
HttpPost httppost = new HttpPost("My Url");
httppost.setEntity(new StringEntity(**message**.toString(), "UTF-8"));
You can just send it like a String:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", message.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
and
$data = json_decode($json);
First of all, the JSON which you have mentioned above is INVALID.
Now,
Here message should have json object in above format.How could i
format JSON object?
=> There are 2 ways to do that:
1) Create a request structure by using JSONObject or JSONArray classes, something like:
JSONObject objRequest = new JSONObject();
objRequest.putString("email","xxxx");
objRequest.putString("password","xxxx");
while setting entity inside HttpPost object, convert it into the String value.
2) Bad way, simple generate a string value with escape sequences, something like:
String strRequest = "{\"email\":\"xxxxxxx\",\"password\":\"xxxxxx\"}";
This may help you..Use GSON library. GSON is a Google library to parse JSON resources. With regards to the Marshalling, it basically means a way to translate data structures (like objects in an OOP language) to JSON... for instance:
// Java object
class Book {
private String title;
private String isbn;
private Set<author> authors;
}
#Entity
class Author {
private String firstName;
private String lastName;
}
To...
{title: "Vocation Createurs",
isbn: "2829302680",
authors: [{firstName: "Barbara", lastName: "Polla"},
{firstName: "Pascal", lastName: "Perez"}]}
You can also use existing libraries like android-json-rpc

Android POST JSON Array to Server

I am having problems trying to POST a JSON Array.
For my Android code, I pass the JSON Array into the server by doing:
interests = // JSONArray of JSONObjects
final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(PARAM_USERNAME, username));
params.add(new BasicNameValuePair(PARAM_INTERESTS, interests.toString()));
HttpEntity entity = new UrlEncodedFormEntity(params);
final HttpPost post = new HttpPost(UPDATE_INTERESTS_URI);
post.setEntity(entity);
// POST data to server
But when I read it from the server using:
$interests = $_POST["interests"];
echo $interets
It looks like [{\"a\":\"1\"},{\"b\":\"2\"}] instead of [{"a":"1"},{"b":"2"}]. The first one won't decode properly, and the second one works.
So why is it not working?
EDIT:
When I look at on Android before it posts, the JSONArray.toString() looks like [{"a":"1"},{"b":"2"}]
Don't know about android, but that looks like the magic quotes-feature of PHP is adding those slashes, if that's the case you could use this on server-side:
$interests = $_POST["interests"];
if (get_magic_quotes_gpc()) {
$interests = stripslashes($interests);
}
echo $interests;
do it in this way:
JSONObject paramInput = new JSONObject();
paramInput.put(PARAM_USERNAME, username);
paramInput.put(INTERESTS, interests.toString());
StringEntity entity = new StringEntity(paramInput.toString(), HTTP.UTF_8);
You can try to use:
StringEntity params = new StringEntity("your_Data");
instead of your UrlEncodedEntity.

Categories

Resources