Contoh kode mengambil data php dari android dalam bentuk json dengan menggunakan volley

Berikut ini kode untuk mengambil data php dari android dalam bentuk json dengan menggunakan volley.

File MainActivity.java

package com.example.basicandroid;

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

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.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
	Button button;
	String server_url = "http://192.168.1.100/myvolley.php";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		button = (Button) findViewById(R.id.b_id_ok);
		button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
                // TODO Auto-generated method stub
				final RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
				JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
						server_url, null, new Response.Listener<JSONObject>() {		 
	                @Override
	                public void onResponse(JSONObject response) {
	                	try {    
                    		Toast.makeText(MainActivity.this, response.getString("pesan"), Toast.LENGTH_LONG).show();
                    		requestQueue.stop();
 
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(),
                                    "Error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }
					}		
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Toast.makeText(MainActivity.this, "Error ...", Toast.LENGTH_LONG).show();
						error.printStackTrace();
						requestQueue.stop();
					}
				});
				requestQueue.add(jsonObjReq);
			}
		});
	}

}

myvolley.php

$lt;?php

echo json_encode( array("pesan" => " Selamat datang ... " ));

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s