logo
down
shadow

Volley: How to extract JSONObject from String Response? Is it possible?


Volley: How to extract JSONObject from String Response? Is it possible?

By : user2956382
Date : November 22 2020, 10:56 AM
it should still fix some issue I've spent a few days trying to figure out volley & finally managed to find out ways to use the Method.POST. I'm using StringRequest to pass email_address parameter to my PHP. Now it's returning a JSON string:
code :
            @Override
            public void onResponse(String response) {
                Log.d(TAG, response.toString());

                try {
                    //Do it with this it will work
                    JSONObject person = new JSONObject(response);
                    String name = person.getString("user_id");
                    String email = person.getString("email_address");

                    //Store session
                    session.createLoginSession(name, email);

                    // Staring MainActivity
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(intent);
                    finish();
                    //}

                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();              
                }

            }


Share : facebook icon twitter icon
Volley-Lib -> String cannot be converted to JSONObject with a real JSONObject

Volley-Lib -> String cannot be converted to JSONObject with a real JSONObject


By : user3580634
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , I don't know why it's append but I got the same issue with volley with the same type of request (HTTP POST + HEADER + PARAMS)
I fix it using StringRequest and parsing it manually. Try in this way
code :
    StringRequest postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {

            Log.d(TAG, "Success "+ s.toString());

            try {
                JSONObject data = new JSONObject(s);
                String dir = data.getString("dir");
                Log.d("dir", dir);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    },
            new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, "Error response " + error.getMessage());
        }
    }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>(); 
            params.put("tag", "login");
            params.put("name", name);
            params.put("password", password);
            return params;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String,String> params = new HashMap<String, String>();
            params.put("Content-Type","application/x-www-form-urlencoded");
            return params;
        }
    };
Android Volley POST JsonObject and get JsonArray or JsonObject or Other response

Android Volley POST JsonObject and get JsonArray or JsonObject or Other response


By : GeoArdilla
Date : March 29 2020, 07:55 AM
will be helpful for those in need in volley we have some ability to retrieve data from server such as jsonObject,jsonArray and String. in this below sample we can get simply jsonObject or jsonArray response from server,
code :
public class RetreiveData {

    public static final String TAG = RetreiveData.class.getSimpleName();

    public static void POST(String localhost, final HashMap<String, String> params, final Listeners.ServerResponseListener listener) {
        StringRequest post = new StringRequest(Request.Method.POST, localhost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (listener != null)
                        listener.onResponse(response.toString());
                    else
                        Log.e(TAG, "Error: SetServerResponse interface not set");
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d("Error: ", e.getMessage());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("Error: ", error.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = params;
                return map;
            }

            @Override
            public RetryPolicy getRetryPolicy() {
                setRetryPolicy(new DefaultRetryPolicy(
                        5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                return super.getRetryPolicy();
            }
        };
        ApplicationController.getInstance().addToRequestQueue(post);
    }
}
using volley connecting to php to get jsonobject response

using volley connecting to php to get jsonobject response


By : Kotsu
Date : March 29 2020, 07:55 AM
hop of those help? You need to start your Volley by calling the following code before passing in the request:
code :
// Instantiate the cache
Cache cache = new DiskBasedCache(mContext.getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
mRequestQueue = new RequestQueue(cache, network);
// Start the queue
mRequestQueue.start();
// Add request to queue
mRequestQueue.add(postRequest)
How to get String response from JSONObject in Volley

How to get String response from JSONObject in Volley


By : zulian zue
Date : March 29 2020, 07:55 AM
will be helpful for those in need I have created JSONRequest by using volley, It successfully hits the service, I checked the service end, It receives the data, and send "Success" in return. , You can use StringRequest instead JSONRequest.
code :
StringRequest stringRequest = new StringRequest(methodType, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {

                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    return headers == null ? super.getHeaders() : headers;
                }

                @Override
                public byte[] getBody() throws AuthFailureError {
                    return "Your JSON body".toString().getBytes();
                }
            };
Get HttpResponse object as response from Volley api in android not jsonobject or string

Get HttpResponse object as response from Volley api in android not jsonobject or string


By : Pradeep k
Date : March 29 2020, 07:55 AM
I hope this helps . Although I am not totally clear with the question or the problem you have been facing . Let me guess you want the Http response from the request and post it to server with another API call ? if this is your problem , Simple solution is to override parseNetworkResponse in makeStringReq()
Related Posts Related Posts :
  • New to PHP, trying to extract information from another website
  • JavaScript AmChart to Image for Email
  • Is javascript validation enough to keep my forms secure?
  • Regex extract variables from [shortcode]
  • Download a .mp3 link and save it to computer with PHP
  • Error with the ereg_replace
  • Getting the fields attached to a bundle of an entity in Drupal
  • Php how to check multiple times (within `foreach`) if values from array exists in mysql?
  • MySQL and PHP parsing strange string
  • Pull specific data from multidimensional associative array
  • How to get the original URI extension using PHP Tonic?
  • Upload videos and images from Android to PHP server?
  • Unset a multidimensional array with another multidimensional array with values than key
  • Calling a user e-mail to add to a mailto link PHP
  • Why is override_function coming back as an undefined function
  • PHP mySQLi_fetch_all: iterate through each row
  • Using pow in php
  • What's wrong with my PHP Script? T_String issue
  • how to call a function of another file without including that file
  • is_rgb function in php
  • transform the numbers to letters using php
  • How to catch an exception from another class method PHP
  • PHP exec is blocked by ISP
  • PHP4 to PHP5 migration character encoding. latin1 vs utf8
  • Begin Transaction not defined
  • How much harm can a user do with xss on a page unique to them?
  • How to import data from a php file to javascript variable
  • PHP and Javascript - log complete workflow
  • When I echo !!! 0 it gives me a strange result
  • jquery ajax post dies after submit
  • How to upload file with curl on sftp server
  • Advanced search using a text input to search through only one category
  • Why do I get "Non-static method App\Models\Category::products() should not be called statically" in laravel
  • Stop notices from undefined indexes in arrays
  • PHP Excel Error when entering SUM function to a cell
  • laravel 4 eloquent eager load relation count
  • click submit in html and run php code
  • Extremely frustrating behavior with Internet Explorer, Bootstrap and Respond.js
  • Vkontakte vtag issues
  • Divide the number to a correct decimal
  • mysqli_insert_query not working
  • How to make a sitemap using zend framework 1
  • Laravel: array to Model with relationship tree
  • $_SERVER['DOCUMENT_ROOT'] vs $path = $_SERVER['DOCUMENT_ROOT']
  • What is the best way to store multiple checkbox values in the database and work with it later on
  • Why does foreach copy the array when we did not modify it in the loop?
  • Receive Jquery/Ajax Post Request in PHP
  • How to better use the if(!empty()){ //codes} statement
  • PHP error mysql_close() boolean given
  • Move an image file from one server to another using PHP
  • PHP: Encoding non ISO-8859-1 charactrers into utf8
  • Handling MySQL errors in PHP
  • Object orientated mysql num_rows query in one line
  • Remove not closed html elements from end of text
  • Generate random ENUM value [PHP, MySQL]
  • Deleting data from table using jQuery and SQL
  • How to make sure the constructor is executed when I'm trying to reach a static property?
  • Trying to understand arrow next to PHP function
  • Form using external php file to show "Sucess"
  • WooCommerce - new shipping method - how to query individual product weights
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org