Json parsing using volly

By ukmodak | March 31st 2024 10:30:09 AM | viewed 876 times

create a main.xml layout and Add a button to show json data in the location: layout(android studio)

<?xml version="1.0" encoding="utf-8"? >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >


        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="426dp" >

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:text="Welcome to main activity "
                android:textColor="#ffffff"
                android:textSize="15sp" />

            <Button
                android:id="@+id/btnServiceJson"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBaseline="@+id/btnServiceTest"
                android:layout_alignBottom="@+id/btnServiceTest"
                android:layout_toRightOf="@+id/btnListView"
                android:text="ServiceByJsonParsingWithAsyncTask"
                android:textSize="8sp" />
          

        </RelativeLayout>

    </LinearLayout>

</LinearLayout>

create a ProjectonOverallClassMainActivity activity to send request to lifyCycle activity

package com.uk.modak;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class ProjectonOverallClassMainActivity extends Activity {
   
	
	public Button btnServiceJson;
		
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
               
         btnServiceJson = (Button) findViewById(R.id.btnServiceJson);           
        btnServiceJson.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Intent a = new Intent(ProjectonOverallClassMainActivity.this,JsonparserByVolly.class);
				startActivity(a);
			}
		});                    
    }
    
    public void onStart(){
    	super.onStart();
    	 	
    }
      
    
}

create a jsonparsinglayout.xml layout to view json data in the location: layout(android studio)

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  android:fillViewport="true"
  android:background="#FFFFFF"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" >
   
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:paddingTop="30px"
        android:id="@+id/GetServerData"
        android:text="Restful Webservice Call"
        android:cursorVisible="true"
        android:clickable="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:layout_gravity="center_horizontal"
    /> 
    <TextView
        android:paddingTop="20px"
        android:textStyle="bold"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Server Response (JSON): " />
    <TextView
        android:paddingTop="16px"
        android:id="@+id/output"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Output : Click on button to get server data." />
     
    <TextView
        android:paddingTop="20px"
        android:textStyle="bold"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Parsed JSON : " />

    <TextView
        android:id="@+id/jsonParsed"
        android:layout_width="fill_parent"
        android:layout_height="492dp"
        android:paddingTop="16px"/>
 
</LinearLayout>
</ScrollView>

create an activity in the location: src/main/java/com/uk/modak/JsonparserByVolly (android studio)


package com.uk.modak;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonparserByVolly extends Activity {


    private String URLstring = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php";
    TextView uiUpdate ;
    TextView jsonParsed ;
    EditText serverText;
    private ProgressDialog pDialog;
    String OutputData = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jsonparsinglayout);
        uiUpdate = (TextView) findViewById(R.id.output);
        jsonParsed = (TextView) findViewById(R.id.jsonParsed);



        final Button GetServerData = (Button) findViewById(R.id.GetServerData);

        GetServerData.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                displayLoader();
                requestJSON();
            }
        });

    }

    private void displayLoader(){
        pDialog = new ProgressDialog(JsonparserByVolly.this);
        pDialog.setMessage("Loading Data.. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();

    }

    private void requestJSON(){

        StringRequest stringRequest = new StringRequest(Request.Method.GET, URLstring, new Response.Listener() {

                    public void onResponse(String response) {

                        pDialog.dismiss();

                        Log.d("strrrrr",">>"+response);

                        try {
                            //getting the whole json object from the response
                            JSONObject obj = new JSONObject(response);
                            if(obj.optString("status").equals("true")){


                                JSONArray dataArray  = obj.getJSONArray("data");

                                for (int i = 0; i < dataArray.length(); i++) {


                                    JSONObject dataobj = dataArray.getJSONObject(i);

                                    OutputData += " id : "+ dataobj.getString("id")+"\n"
                                            + "name : "+ dataobj.getString("name")+"\n"
                                            + "country : "+ dataobj.getString("country") +"\n"
                                            + "city : "+ dataobj.getString("city") +"\n"
                                            +"-------------------------"+"\n";


                                    jsonParsed.setText(OutputData);



                                }



                            }else {
                                Toast.makeText(JsonparserByVolly.this, obj.optString("message")+"", Toast.LENGTH_SHORT).show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {

                    public void onErrorResponse(VolleyError error) {
                        //displaying the error in toast if occurrs
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

        //creating a request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //adding the string request to request queue
        requestQueue.add(stringRequest);

    }
}

Go to menifeast and setup activity that we use

<application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".ProjectonOverallClassMainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
        <activity
            android:name=".JsonparserByVolly"
            android:label="@string/app_name" >
        </activity>
        
        <receiver android:name=".ConnectionReceive">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>
        
    </application>
bONEandALL
Visitor

Total : 20973

Today :27

Today Visit Country :

  • Germany
  • United States
  • Singapore
  • China
  • United Kingdom
  • South Korea
  • Czechia