Contoh kode android untuk menampilkan data json array di listview multi column dari php dengan volley library

Berikut kode android untuk menampilkan data json array di listview multi column dari php dengan volley library.

File Proses .java

package com.example.test;

import java.util.ArrayList;
import java.util.HashMap;

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

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


public class Penjualan extends Activity {
	String server_url = "http://192.168.1.11/api/penjualan.php";
	
	private ListView list_view;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.penjualan);
		
		makeJsonArrayRequest();		
	}

	private void makeJsonArrayRequest() {
		 
		final RequestQueue requestQueue = Volley.newRequestQueue(Penjualan.this);
 
        JsonArrayRequest req = new JsonArrayRequest(server_url,
		    new Response.Listener<JSONArray>() {
	        @Override
	        public void onResponse(JSONArray response) {
	            try {

                	list_view = (ListView) findViewById(R.id.lv_id_penjualan);
                	
                	ArrayList<HashMap<String, String>> feedList= new ArrayList<HashMap<String, String>>();
                    HashMap<String, String> map = new HashMap<String, String>();
                    
                    for (int i = 0; i < response.length(); i++) {                    	
                   		JSONObject person = (JSONObject) response.get(i);
	            		//al_nama_customer.add(person.getString("nama_customer"));
                    	map = new HashMap<String, String>();
	            		map.put("penjualan_id", person.getString("penjualan_id"));
	                    map.put("nama_customer", person.getString("nama_customer"));
	                    feedList.add(map);
                    }                    
                     
                    SimpleAdapter simpleAdapter = new SimpleAdapter(Penjualan.this, feedList, 
                    		R.layout.penjualanlist, 
                    		new String[]{"penjualan_id", "nama_customer"}, 
                    		new int[]{R.id.tv_id_penjualan_id, R.id.tv_id_nama_customer});

                    list_view.setAdapter(simpleAdapter);
                    
                	list_view.setAdapter(simpleAdapter);
                	list_view.setOnItemClickListener(new OnItemClickListener() {
            			@Override
            			public void onItemClick(AdapterView<?> parent, View view,
            				int position, long id) {
            				// TODO Auto-generated method stub
            				String value = ((TextView) view.findViewById(R.id.tv_id_penjualan_id)).getText().toString(); 
            						//(String) list_view.getItemAtPosition(position);
            				Toast.makeText(Penjualan.this, "Position : " + position + " Value : " + value, 
            						Toast.LENGTH_LONG).show();
            			}    		
            		});                
	 				
                	
                } 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(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();                        
            }
        });
		 
        // Adding request to request queue        
        requestQueue.add(req);
    }
 
}

File Layout Utama .xml

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

    <TextView
        android:id="@+id/tv_id_penjualan"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/tv_penjualan"
        android:textSize="20sp" 
    />

    <ListView
        android:id="@+id/lv_id_penjualan"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_id_penjualan" >
    </ListView>

</RelativeLayout>

 

File Layout List.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
 
    <TextView
        android:id="@+id/tv_id_penjualan_id"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:layout_weight="1"
          android:gravity="center" 
        android:textAppearance="?android:attr/textAppearanceMedium"  />
  
     <TextView
        android:id="@+id/tv_id_nama_customer"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:layout_weight="1"
        android:gravity="center" 
        android:textAppearance="?android:attr/textAppearanceMedium" />
 
</LinearLayout>

 

Advertisements

Contoh kode untuk mengambil data jsonArray dari android ke PHP dengan menggunakan library volley

Berikut contoh untuk mengambil data jsonArray dari android ke PHP dengan menggunakan library volley, silahkan di pelajari dan dikembangkan. Awalnya sulit kesananya mudah.

File MainActivity.java

package com.example.test;

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

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;


public class MainActivity extends Activity {
	String server_url = "http://192.168.1.101/api/user.php";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.penjualantambah);
		
		makeJsonArrayRequest();		
	}

	private void makeJsonArrayRequest() {
		 
		final RequestQueue requestQueue = Volley.newRequestQueue(PenjualanTambah.this);
 
        JsonArrayRequest req = new JsonArrayRequest(server_url,
		    new Response.Listener<JSONArray>() {
	        @Override
	        public void onResponse(JSONArray response) {
	    		
	            try {
	                // Parsing json array response
	            	// loop through each json object                            
                   for (int i = 0; i < response.length(); i++) {

                        JSONObject person = (JSONObject) response.get(i);

                        String username = person.getString("username");
                        Toast.makeText(PenjualanTambah.this, username, Toast.LENGTH_LONG).show();
                    
                    }                            
	 
                } 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(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();                        
            }
        });
		 
        // Adding request to request queue        
        requestQueue.add(req);
    }
 
}

Josh smoga bermanfaat gan.

Contoh kode sederhana untuk mangambil tanggal terkini dari system android

Berikut kode untuk mangambil tanggal terkini dari system android dan menampilkannya di dalam edit text.

File MainActivity.java

package com.example.test;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;

public class PenjualanTambah extends Activity {
	
	EditText tanggal;
	int mYear,mMonth,mDay;
	
	@SuppressLint("SimpleDateFormat") @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.penjualantambah);
		
		tanggal = (EditText) findViewById(R.id.et_id_tanggal);

		Calendar c=Calendar.getInstance();
        mYear=c.get(Calendar.YEAR);
        mMonth=c.get(Calendar.MONTH);
        mDay=c.get(Calendar.DAY_OF_MONTH);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        tanggal.setText( sdf.format(c.getTime()));

	}

}

Contoh kode login android dan php dengan volley

Berikut ini adalah contoh untuk membuat login di android ke php dengan menggunakan volley library, silahkan di pelajari dan di kembangkan sendiri.

File MainActivity.java

package com.example.testlogin;

import java.util.HashMap;
import java.util.Map;

import com.android.volley.AuthFailureError;
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 android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	Button button;
	EditText username, password;
	
	String server_url = "http://192.168.1.100/api/login.php";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		button = (Button) findViewById(R.id.b_id_ok);
        username = (EditText) findViewById(R.id.et_id_username);
        password = (EditText) findViewById(R.id.et_id_password);
        
		button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
                // TODO Auto-generated method stub
				final RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
				final String Username, Password;
				
				Username = username.getText().toString();
				Password = password.getText().toString();
				
				StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url, 
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						if(response.equals("1")) {
							Toast.makeText(MainActivity.this, "Login success ...", Toast.LENGTH_LONG).show();
						} else {
							Toast.makeText(MainActivity.this, response + "Invalid username or password ...", Toast.LENGTH_LONG).show();							
						}						
						requestQueue.stop();						
					}		
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Toast.makeText(MainActivity.this, "Error ...", Toast.LENGTH_LONG).show();
						error.printStackTrace();
						requestQueue.stop();
					}
				}){
					@Override
					protected Map<String, String> getParams() throws AuthFailureError{
						Map<String, String> params = new HashMap<String, String>();
						params.put("username", Username);
						params.put("password", Password);
						return params;
					}

				};
				requestQueue.add(stringRequest);
			}
		});
	}

}

 

File activity_main.xml

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

    <TextView
        android:id="@+id/tv_id_login"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/tv_login"
        android:textSize="20sp" />
    
    <TextView
    	android:id="@+id/tv_id_username"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="@string/tv_username" 
	    android:layout_below="@id/tv_id_login"
    />

    <EditText
	    android:id="@+id/et_id_username"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:inputType="text"
	    android:layout_below="@id/tv_id_username"
    />

    <TextView
	    android:id="@+id/tv_id_password"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="@string/tv_password"
	    android:layout_below="@id/et_id_username"
    />

    <EditText
	    android:id="@+id/et_id_password"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:inputType="textPassword"
	    android:layout_below="@id/tv_id_password"
    />

    <Button
	    android:id="@+id/b_id_ok"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:layout_below="@id/et_id_password"
	    android:text="@string/b_ok" 
    />


</RelativeLayout>

 

File login.php

<?php
// database
include_once("../db.php");

if($_POST) {

	$result = mysql_query("select * " . 
		" from user " .
		" and username = '" . $_POST['username'] . "' " .
		" and password = '" . md5($_POST['password']) . "' " );
        
	if(mysql_num_rows($result)>0) {
		while($row = mysql_fetch_array($result)) {
            echo "1";
		}
	} else {
        echo "";
    }
}

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 ... " ));

Contoh kode mengirimkan data post dari android ke server PHP dengan menggunakan volley

Berikutnya adalah kode untuk mengirimkan data post dari android ke server PHP  dengan menggunakan volley.

File MainActivity.java

package com.example.basicandroid;

import java.util.HashMap;
import java.util.Map;

import com.android.volley.AuthFailureError;
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 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);
				
				StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url, 
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
						requestQueue.stop();
					}		
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Toast.makeText(MainActivity.this, "Error ...", Toast.LENGTH_LONG).show();
						error.printStackTrace();
						requestQueue.stop();
					}
				}){
					@Override
					protected Map<String, String> getParams() throws AuthFailureError{
						Map<String, String> params = new HashMap<String, String>();
						params.put("data", "Foo bars");
						return params;
					}
				
				};
				requestQueue.add(stringRequest);
			}
		});
	}

}

File MainActivity.java

<?php
echo $_POST["data"];

Contoh sederhana penggunaan volley di dalam project android

 

Posting sebelumnya sudah di bahas tatacara memasang library volley di project android dengan eclipse. berikut contoh kode sederhana untuk penggunaan volley, dimana program akan memanggil url server, dan mengambil isi dari content, kemudian menampilkannya dengan alert isi dari content tersebut.

Kode file MainActivity.java

package com.example.basicandroid;

import java.util.HashMap;
import java.util.Map;

import com.android.volley.AuthFailureError;
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 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);
				
				StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url, 
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
						requestQueue.stop();
					}		
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Toast.makeText(MainActivity.this, "Error ...", Toast.LENGTH_LONG).show();
						error.printStackTrace();
						requestQueue.stop();
					}
				}){
					@Override
					protected Map<String, String> getParams() throws AuthFailureError{
						Map<String, String> params = new HashMap<String, String>();
						params.put("data", "Foo bars");
						return params;
					}
				
				};;
				requestQueue.add(stringRequest);
			}
		});
	}

}

code myvolley.php

<?php
echo "Hallo world ...";
?>

Menambahkan file jar volley kedalam project di eclipse

Setelah mendownload file volley di posting sebelumnya, untuk mengaktifkan dalam project harus di copykan terlebih dahulu file-file tersebut kedalam project di eclipse.penempatannya adalah sebagai berikut.

 

endang-eclipse-volley-libs
hal lainnya yang perlu diubah adalah pada file Androidmanifest.xml. tambahkan kode berikut.

<uses-permission android:name=”android.permission.INTERNET” ></uses-permission>

dan jika ada error atau tanda warning, masukan external jar file yang terdapat diposting alamat sebelumnya. semoga berhasil, wassalam.

File pendukung volley android – httpcomponents-client-451 dari apache

Selain file volley, ternyata diperlukan juga file jar pendukung lainnya yang pernah saya masukan dalam posting sebelummnya yaitu httpcomponents-client-451-bin dari apache. silahkan download di link berikut.

http://www.4shared.com/rar/1AxyE1QTce/httpcomponents-client-451-bint.html

file-file jar tersebut nanti di add kan sebagai external jar di dalam sebuah project android.

add-external-jars-eclipse-android-endangcahyapermana

semoga sukses dan bahagia, wassalam..