how to use Webservice in android studio
content_mian.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorAccent"
android:orientation="vertical"
tools:context="nc.example.com.parsebeckone.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="10dp"
android:textSize="20sp"
android:textColor="#000"
android:text="Data from JSON Parsing"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/lv"/>
</LinearLayout>
Lv_item.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:padding="10dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000"
android:orientation="vertical">
<TextView
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#fff"
android:layout_marginTop="10dp"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingLeft="10dp"
android:text="Name" />
<TextView
android:id="@+id/country"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#fff"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingLeft="10dp"
android:text="Country" />
<TextView
android:id="@+id/city"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#fff"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingLeft="10dp"
android:text="City" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@color/colorAccent"/>
</LinearLayout>
MainActivity.java
package nc.example.com.parsebeckone;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private ParseContent parseContent;
private final int jsoncode = 1;
private ListView listView;
private ArrayList<PlayersModel> playersModelArrayList;
private CustomeAdapter customeAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
parseContent = new ParseContent(this);
listView = (ListView) findViewById(R.id.lv);
try {
parseJson();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void parseJson() throws IOException, JSONException {
if (!AndyUtils.isNetworkAvailable(MainActivity.this)) {
Toast.makeText(MainActivity.this, "Internet is required!", Toast.LENGTH_SHORT).show();
return;
}
AndyUtils.showSimpleProgressDialog(MainActivity.this);
new AsyncTask<Void, Void, String>(){
protected String doInBackground(Void[] params) {
String response="";
HashMap<String, String> map=new HashMap<>();
try {
HttpRequest req = new HttpRequest(AndyConstants.ServiceType.URL);
response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
} catch (Exception e) {
response=e.getMessage();
}
return response;
}
protected void onPostExecute(String result) {
//do something with response
Log.d("newwwss",result);
onTaskCompleted(result,jsoncode);
}
}.execute();
}
public void onTaskCompleted(String response, int serviceCode) {
Log.d("responsejson", response.toString());
switch (serviceCode) {
case jsoncode:
if (parseContent.isSuccess(response)) {
AndyUtils.removeSimpleProgressDialog(); //will remove progress dialog
playersModelArrayList = parseContent.getInfo(response);
customeAdapter = new CustomeAdapter(this,playersModelArrayList);
listView.setAdapter(customeAdapter);
}else {
Toast.makeText(MainActivity.this, parseContent.getErrorCode(response), Toast.LENGTH_SHORT).show();
}
}
}
}
AndyConstants .java
package nc.example.com.parsebeckone;
/**
* Created by nc on 6/7/2017.
*/
public class AndyConstants {
public class ServiceCode {
public static final int HOME = 1;
}
// web service url constants
public class ServiceType {
public static final String URL = "http://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php";
}
// webservice key constants
public class Params {
public static final String ID = "id";
public static final String NAME = "name";
public static final String COUNTRY = "country";
public static final String CITY = "city";
}
}
AndyUtils.java
package nc.example.com.parsebeckone;
/**
* Created by nc on 6/7/2017.
*/
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class AndyUtils {
private static ProgressDialog mProgressDialog;
public static void showSimpleProgressDialog(Context context, String title,
String msg, boolean isCancelable) {
try {
if (mProgressDialog == null) {
mProgressDialog = ProgressDialog.show(context, title, msg);
mProgressDialog.setCancelable(isCancelable);
}
if (!mProgressDialog.isShowing()) {
mProgressDialog.show();
}
} catch (IllegalArgumentException ie) {
ie.printStackTrace();
} catch (RuntimeException re) {
re.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void showSimpleProgressDialog(Context context) {
showSimpleProgressDialog(context, null, "Loading...", false);
}
public static void removeSimpleProgressDialog() {
try {
if (mProgressDialog != null) {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
mProgressDialog = null;
}
}
} catch (IllegalArgumentException ie) {
ie.printStackTrace();
} catch (RuntimeException re) {
re.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
CustomeAdapter.java
package nc.example.com.parsebeckone;
/**
* Created by nc on 6/7/2017.
*/
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Parsania Hardik on 03-Jan-17.
*/
public class CustomeAdapter extends BaseAdapter {
private Context context;
private ArrayList<PlayersModel> playersModelArrayList;
public CustomeAdapter(Context context, ArrayList<PlayersModel> playersModelArrayList) {
this.context = context;
this.playersModelArrayList = playersModelArrayList;
}
@Override
public int getViewTypeCount() {
return getCount();
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getCount() {
return playersModelArrayList.size();
}
@Override
public Object getItem(int position) {
return playersModelArrayList.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.lv_item, null, true);
holder.tvname = (TextView) convertView.findViewById(R.id.name);
holder.tvcountry = (TextView) convertView.findViewById(R.id.country);
holder.tvcity = (TextView) convertView.findViewById(R.id.city);
convertView.setTag(holder);
}else {
// the getTag returns the viewHolder object set as a tag to the view
holder = (ViewHolder)convertView.getTag();
}
holder.tvname.setText("Name: "+playersModelArrayList.get(position).getName());
holder.tvcountry.setText("Country: "+playersModelArrayList.get(position).getCountry());
holder.tvcity.setText("City: "+playersModelArrayList.get(position).getCity());
return convertView;
}
private class ViewHolder {
protected TextView tvname, tvcountry, tvcity;
}
}
HttpRequest.java
package nc.example.com.parsebeckone;
/**
* Created by nc on 6/7/2017.
*/
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* Since HttpClient,BasicNameValuePairs, etc... are deprecated.
* I've searched for a good alternative, and couldn't find any. Eventually ended up writing my own solution, so I decided to share to those who needs it.
* Main goals: to make it intuitive, short, clean and reasonable.
* NOTE methods: .prepare(), preparePost(), withData(map) & withData(string) are build to allow caller to chain in different variations, examples:
*HttpRequest req=new HttpRequest("http://host:port/path");
*
*Example 1: //prepare Http Post request and send to "http://host:port/path" with data params name=Bubu and age=29, return true - if worked
*req.preparePost().withData("name=Bubu&age=29").send();
*
*Example 2: //prepare http get request, send to "http://host:port/path" and read server's response as String
*req.prepare().sendAndReadString();
*
*Example 3: //prepare Http Post request and send to "http://host:port/path" with name=Bubu and age=29 and read server's response as JSONObject
*HashMap<String, String>params=new HashMap<>();
params.put("name", "Groot");
params.put("age", "29");
*req.preparePost().withData(params).sendAndReadJSON();
*/
public class HttpRequest {
//Supported HttpRequest methods
public static enum Method{
POST,PUT,DELETE,GET;
}
private URL url;
private HttpURLConnection con;
private OutputStream os;
//After instantiation, when opening connection - IOException can occur
public HttpRequest(URL url)throws IOException{
this.url=url;
con = (HttpURLConnection)this.url.openConnection();
}
//Can be instantiated with String representation of url, force caller to check for IOException which can be thrown
public HttpRequest(String url)throws IOException{ this(new URL(url)); Log.d("parameters", url); }
/**
* Sending connection and opening an output stream to server by pre-defined instance variable url
*
* @param //isPost boolean - indicates whether this request should be sent in POST method
* @throws IOException - should be checked by caller
* */
private void prepareAll(Method method)throws IOException{
con.setDoInput(true);
con.setRequestMethod(method.name());
if(method==Method.POST||method==Method.PUT){
con.setDoOutput(true);
os = con.getOutputStream();
}
}
//prepare request in GET method
//@return HttpRequest this instance -> for chaining method @see line 22
public HttpRequest prepare() throws IOException{
prepareAll(Method.GET);
return this;
}
/**
* Prepares HttpRequest method with for given method, possible values: HttpRequest.Method.POST,
* HttpRequest.Method.PUT, HttpRequest.Method.GET & HttpRequest.Method.DELETE
*
* @param method HttpRequest.Method - nested enum HttpRequest.Method constant
* @return HttpRequest this instance -> for chaining method @see line 22
* @throws IOException - should be checked by caller
* */
public HttpRequest prepare(HttpRequest.Method method)throws IOException{
prepareAll(method);
return this;
}
/**
* Adding request headers (standard format "Key":"Value")
*
* @param headers String variadic params in standard format "Key":"Value"
* @return HttpRequest this instance -> for chaining method @see line 22
* */
public HttpRequest withHeaders(String... headers){
for(int i=0,last=headers.length;i<last;i++) {
String[]h=headers[i].split("[:]");
con.setRequestProperty(h[0],h[1]);
}
return this;
}
/**
* Writes query to open stream to server
*
* @param query String params in format of key1=v1&key2=v2 to open stream to server
* @return HttpRequest this instance -> for chaining method @see line 22
* @throws IOException - should be checked by caller
* */
public HttpRequest withData(String query) throws IOException{
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.close();
return this;
}
/**
* Builds query on format of key1=v1&key2=v2 from given hashMap structure
* for map: {name=Bubu, age=29} -> builds "name=Bubu&age=29"
* for map: {Iam=Groot} -> builds "Iam=Groot"
*
* @param params HashMap consists of key-> value pairs to build query from
* @return HttpRequest this instance -> for chaining method @see line 22
* @throws IOException - should be checked by caller
* */
public HttpRequest withData(HashMap<String,String> params) throws IOException{
StringBuilder result=new StringBuilder();
for(Map.Entry<String,String>entry : params.entrySet()){
result.append((result.length()>0?"&":"")+entry.getKey()+"="+entry.getValue());//appends: key=value (for first param) OR &key=value(second and more)
Log.d("parameters",entry.getKey()+" ===> "+ entry.getValue());
}
withData(result.toString());
return this;
}
//When caller only need to send, and don't need String response from server
public int send() throws IOException{
return con.getResponseCode(); //return HTTP status code to indicate whether it successfully sent
}
/**
* Sending request to the server and pass to caller String as it received in response from server
*
* @return String printed from server's response
* @throws IOException - should be checked by caller
* */
public String sendAndReadString() throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder response=new StringBuilder();
for(String line;(line=br.readLine())!=null;)response.append(line+"\n");
Log.d("ressss",response.toString());
return response.toString();
}
/**
* Sending request to the server and pass to caller its raw contents in bytes as it received from server.
*
* @return byte[] from server's response
* @throws IOException - should be checked by caller
* */
public byte[] sendAndReadBytes() throws IOException{
byte[] buffer = new byte[8192];
InputStream is = con.getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
for (int bytesRead;(bytesRead=is.read(buffer))>=0;)output.write(buffer, 0, bytesRead);
return output.toByteArray();
}
//JSONObject representation of String response from server
public JSONObject sendAndReadJSON() throws JSONException, IOException{
return new JSONObject(sendAndReadString());
}
}
Parsecontent.java
package nc.example.com.parsebeckone;
/**
* Created by nc on 6/7/2017.
*/
import android.app.Activity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class ParseContent {
private final String KEY_SUCCESS = "status";
private final String KEY_MSG = "message";
private Activity activity;
ArrayList<HashMap<String, String>> arraylist;
public ParseContent(Activity activity) {
this.activity = activity;
}
public boolean isSuccess(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.optString(KEY_SUCCESS).equals("true")) {
return true;
} else {
return false;
}
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
public String getErrorCode(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
return jsonObject.getString(KEY_MSG);
} catch (JSONException e) {
e.printStackTrace();
}
return "No data";
}
public ArrayList<PlayersModel> getInfo(String response) {
ArrayList<PlayersModel> playersModelArrayList = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString(KEY_SUCCESS).equals("true")) {
arraylist = new ArrayList<HashMap<String, String>>();
JSONArray dataArray = jsonObject.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
PlayersModel playersModel = new PlayersModel();
JSONObject dataobj = dataArray.getJSONObject(i);
playersModel.setName(dataobj.getString(AndyConstants.Params.NAME));
playersModel.setCountry(dataobj.getString(AndyConstants.Params.COUNTRY));
playersModel.setCity(dataobj.getString(AndyConstants.Params.CITY));
playersModelArrayList.add(playersModel);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return playersModelArrayList;
}
}
PlayersModel.java
package nc.example.com.parsebeckone;
/**
* Created by nc on 6/7/2017.
*/
public class PlayersModel {
private String name, country, city;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nc.example.com.parsebeckone">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Comments
Post a Comment