Submitting data in an android app using the HTTP POST method and

I need to translate this HTTP POST request from JavaScript to Android.

I'm facing an issue with cids: []. I am unable to create a JsonObject with the square brackets symbol [ ] as it should be an empty array.

This is my original JavaScript code:

var makeAjaxRequest = function () {
        Ext.getBody().mask('Loading...', 'x-mask-loading', false);
        var obj = {
            uid: 1161,
            cids: []        
        };
        Ext.Ajax.request({
            url: 'http://test.com.my',
            method: 'POST',
            params: { json: Ext.encode(obj) },
            success: function (response, opts) {
                Ext.getCmp('content').update(response.responseText);
                Ext.getCmp('status').setTitle('Static test.json file loaded');
                Ext.getBody().unmask();
                var data = Ext.decode(response.responseText);
                Ext.Msg.alert('result::', data.r[1].id, Ext.emptyFn);
            }
        });
    };

And here's my corresponding Android code snippet:

    String[] temp = null; 
JSONObject json = new JSONObject(); 
HttpPost post = new HttpPost(url); 
json.put("uid", 1161); 
json.put("cids", temp); 
List postParams = new ArrayList(); 
postParams.add(new BasicNameValuePair("json", json.toString())); 
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams); 
tv1.setText(postParams.toString()); 
post.setEntity(entity); 
post.setHeader("Accept", "application/json");
response = client.execute(post);

Answer №1

Avoid using String[] temp = null;, it's not the correct approach.

Instead, opt for String[] temp = {};. This signifies an empty array in the code.

Answer №2

Struggling to create a JSONObject using the symbol "[ ]".

Remember, when using JSON, {} represents a JSONObject and [] represents a JSONArray.

    public void generateJSON() {
    JSONObject user = new JSONObject();
    JSONObject user2;
    user2 = new JSONObject();
    try {
        user.put("dish_id", "1");
        user.put("dish_custom", "2");
        user.put("quantity", "2");
        user.put("shared", "2");

        user2.put("dish_id", "2");
        user2.put("dish_custom", "2");
        user2.put("quantity", "4");
        user2.put("shared", "3");
    } catch (JSONException e) {
        // Handle exception
        e.printStackTrace();
    }

    JSONArray userArray = new JSONArray();
    userArray.put(user);
    userArray.put(user2);
    System.out.println("Generated JSON Array: "+userArray);

By following this code snippet, you will get a JSON array containing user and user2 utilizing the symbols "[]".

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Modify the Image Shown When Sharing the Website on Facebook?

When you post a link or website on Facebook, the platform scrapes images from the link to visually represent the story. However, since Facebook has a white background, images with white backgrounds don't display well in this context. I'm wonderi ...

Creating HTML code using Django and JavaScript

Greetings world! I am relatively new to Python and JavaScript, so my coding techniques might seem unconventional to seasoned developers. However, I am eager to learn and improve. I have an HTML page where Django generates some code for a calendar: Here&a ...

CSV data organized in a nested JSON format

I am looking to generate a nested JSON structure based on the provided CSV file snippet. Datum,Position,Herkunft,Entscheidungen insgesamt,Insgesamt_monat,Asylberechtigt,Asylberechtigt monat,Asylberechtigt Prozent,Flüchtling,Flüchtling monat,Flüchti ...

How to assign a specific class to a list item in AngularJS based on its attribute value

Having some difficulties with this code: .directive('mydirective', function() { return { template: '<ul>\ <li priority="500"><a href="#"><i></i>Inbox</a></li>\ ...

Overlapping parameters in Express.js routes can lead to conflicts and unexpected

My website has a route named date where I display all posts from a specific date, for example: /date/26-12-2015 I also added basic pagination to prevent displaying all data at once. For instance, /date/26-12-2015/2 would show the second page of posts. Ho ...

Reposition buttons using JavaScript

I attempted to modify the button that appears at the top of an HTML page. <div class='play'> <input id="play" type="button" value="Play" onclick="mode('play');startSlideshow();" /> </div> <div class='pause ...

Transferring a list of files from Callback folder

I am struggling with a function that is supposed to retrieve and list all the files in a specific folder. However, I am facing issues when trying to push out these files through an array. Something seems to be going wrong in my code as I receive an error w ...

Creating an Ndef message for vcard/vcal on Android: Step-by-step guide

I'm diving into the world of Android programming and my focus is on NFC technology. Specifically, I am interested in learning about Tag reading and writing modes. However, I am struggling to find comprehensive information on working with Vcard/Vcal MI ...

Using the JSON.stringify function in node.js C++ add-ons

Currently, I am working on creating node.js bindings and my goal is to produce a JSON string from v8::Object instances. My plan is to accomplish this task using C++. Given that node.js already includes JSON.stringify, I would prefer to leverage it for th ...

Tips for resolving the issue of receiving a warning about passing "onClick" to a "<Link>" component with an `href` of `#` while having "legacyBehavior" enabled in Next.js

My current project is displaying a lot of warnings in the browser console and I'm unsure about the reasons behind it. The warnings include: "onClick" was passed to with href of /discovery/edit but "legacyBehavior" was set. The l ...

Automatically start playing HTML5 audio/video on iOS 5 devices

Currently, I am facing a challenge with implementing sound effects in my HTML5 web-app on iOS5. Despite trying various methods, the sound effects are not working as expected. Are there any creative solutions available to gain JavaScript control over an HT ...

What steps can I take to address the jolting and slow movement issues in this multiplayer application that relies on ajax

EDIT: It is important to note that examples must be compatible with Firefox 3+ due to the presence of HTML5 elements. Greetings! I am currently exploring the potential of AJAX in a browser-based multiplayer game. In order to do so, I am experimenting wit ...

Updating several JSON nodes by using a JOIN operation

My SQL Server stored procedure requires a JSON parameter called @ChangeSet, here is an example: DECLARE @ChangeSet varchar(MAX) = '{ "Acts": [ {"ActId":100,"ActText":"Intro","ActNumber":1}, {"ActId":0, "ActText":"Beginning" ...

How can I retrieve data from a script tag in an ASP.NET MVC application?

I'm struggling to figure out how to properly access parameters in a jQuery call. Here is what I currently have: // Controller code public ActionResult Offer() { ... ViewData["max"] = max; ViewData["min"] = min; ... return View(paginatedOffers ...

Creating a nested JSON response with an Array in a Stored Procedure

I have extracted a dataset from a stored procedure result +------+--------+---------------------+------------+ | Line |Status | Consent | tid | +------+--------+---------------------+------------+ | 1001 | 1 | Yes | ...

Unleashing the power of Angular's ng-repeat: merging data across multiple arrays

Is it possible to merge two arrays in Angular's ng-repeat functionality? For instance, let's say we have arrays containing book titles and author names. How can we display the book titles along with their corresponding author names? One array h ...

Unique title for hyperlinks on contact details

I have been developing an application that allows users to save their social network links in the default contacts app on Android OS. Although I can successfully save the link, I am struggling to customize the title as shown in the image of the Def ...

How can I retrieve the value of a specific JSON attribute in Cloud Functions?

Inside the text box for my pubsub message, there is a json file that appears like this: { "message": "Good morning", "sender": "Joe Schmoe" } I've made several attempts to retrieve the value of "sender", but have been unsuccessful in the following w ...

Customize the color of text in the ActionBarSherlock menu on Android

I am looking to update the white text color to orange. Here is an illustration. ...

What is the best way to show distinct items and their frequencies from an array of objects in Vue.js/JavaScript?

I have been developing an inventory management application using Vuejs, and I am facing a JavaScript-related challenge in my project. The issue revolves around handling data that includes user information retrieved from a form, as well as static categories ...