Saturday, 26 December 2015

Adapter Class for ListView with Checkbox in Android

Here I have Adapter class for Listview with Checkbox in Android. Many devloper face scroll problem wile using check box in listview. When we scroll the listview the checked items will be unchecked. To overcome this issue we need to use set tag for the check box. Herewith I have attached the Adapter class.


import java.util.ArrayList;

import com.move.R;
import com.move.model.ListItems;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class ListItemsAdapter extends BaseAdapter {

private Activity activity;
public ArrayList<ListItems> data;
private static LayoutInflater inflater = null;
public Resources res;
ViewHolder holder;
ListItems tempValues;
public ListItemsAdapter(Activity a, ArrayList<ListItems> d,
Resources resLocal) {

activity = a;
data = d;
res = resLocal;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public int getCount() {

if (data.size() <= 0)
return 1;
return data.size();
}

public Object getItem(int position) {
return position;
}

public long getItemId(int position) {
return position;
}

public static class ViewHolder {

public CheckBox listItemCheckBox;

}

public View getView(int position, View convertView, ViewGroup parent) {

View vi = convertView;
holder = new ViewHolder();
if (convertView == null) {
vi = inflater.inflate(R.layout.my_bits_list_items, null);

holder.listItemCheckBox = (CheckBox) vi
.findViewById(R.id.listItemChkBox);

holder.listItemCheckBox
.setOnCheckedChangeListener(new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean checked) {
int getPosition = (Integer) buttonView.getTag();
data.get(getPosition).setSelected(
buttonView.isChecked());
}
});

vi.setTag(holder);

vi.setTag(R.id.listItemChkBox, holder.listItemCheckBox);

} else
holder = (ViewHolder) vi.getTag();

if (data.size() <= 0) {
// holder.text.setText("No Data");

} else {

tempValues = null;
tempValues = (ListItems) data.get(position);
holder.listItemCheckBox.setTag(position);
holder.listItemCheckBox.setText(tempValues.getFromAddress());
holder.listItemCheckBox.setChecked(tempValues.isSelected());
}
return vi;
}

}

Now you can use the listview without issue. Here vi.setTag(R.id.listItemChkBox, holder.listItemCheckBox) This is the important line.

Happy coding..

Tuesday, 22 December 2015

Using the OkHttp library for HTTP requests

Now we are going to see how to use OkHttp library for HTTP requests in our project. Using of okHTTP we can call the web service and can get the response from server. Download OKHTTP from the official site (From Here) and follow the steps.

Create one Async Task.

Async Task Class:-

package com.test.project.helper;

import java.util.concurrent.TimeUnit;

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

import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.Request.Builder;
import com.test.project.interfaces.AsyncResponseListener;

import android.os.AsyncTask;

public class WebServiceHelper extends AsyncTask<String, Void, String>{
private Builder requestBuilder = null;
private String requestURL = null;

private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
//private static final MediaType OCTET_STREAM = MediaType.parse("application/octet-stream");
private static final MediaType JAVA_SERIALIZED_OBJECT = MediaType.parse("application/x-java-serialized-object");

OkHttpClient client = new OkHttpClient();
public AsyncResponseListener delegate = null;

public WebServiceHelper(String requestURL){
this.requestURL = requestURL;
this.requestBuilder = new Builder().url(requestURL);
}

protected String doInBackground(String... params) {
try {
Request request = requestBuilder.build();

System.out.println("Request URL: " + request.urlString());
System.out.println("Auth Token: " + request.header("auth_token"));

if(request.body() != null){
System.out.println("Data Type: " + request.body().contentType().toString());
}

client.setConnectTimeout(60, TimeUnit.SECONDS);
Response response = client.newCall(request).execute();
//System.out.println("response ==>"+response.body().string());
return response.body().string();      
}
catch (Exception e) {

System.out.println("Connection Exception:" + e.getLocalizedMessage());

//Create the JSON for response
JSONObject errorResponse = new JSONObject();
   try {
    //Creating JSON object for response_status key
    JSONObject response_status = new JSONObject();
    response_status.put("response_code", 1);
    response_status.put("response_message", "Failed");
   
    //Creating JSON object for response_data key
    JSONObject response_data = new JSONObject();
    response_data.put("error", "Unable to complete the request due to network connection error. Please try again.");
   
    errorResponse.put("response_status", response_status);
    errorResponse.put("response_data", response_data);
   
} catch (JSONException JSONexp) {
JSONexp.printStackTrace();
}
 
   return errorResponse.toString();
   }
}

protected void onPostExecute(String responseString) {
   // TODO: check this.exception
   // TODO: do something with the feed
System.out.println("Response: " + responseString);

delegate.processFinish(this.requestURL, responseString);
}

public void addHeader(String name, String value){
this.requestBuilder.addHeader(name, value);
}

public void setRequestBody(String requestData){
System.out.println("Request Body: " + requestData);
this.requestBuilder.post(RequestBody.create(JSON, requestData));
}

public void setRequestBody(byte[] requestData){
System.out.println("Request Body: " + requestData.toString());
this.requestBuilder.post(RequestBody.create(JAVA_SERIALIZED_OBJECT, requestData));
}
}

Create Interface for process Finish:-

package com.test.project.interfaces;

public interface AsyncResponseListener {

void processFinish(String requestURL, String response);

}

Main Class:-

Then In your main class implements AsyncResponseListener and call this method to call web service.


private ProgressDialog pdia;
private void WebCalls() {
pdia = new ProgressDialog(this);
       pdia.setMessage("Loading...");
       pdia.show();    

JSONObject requestObject = new JSONObject();
//mProgressHUD = ProgressHUD.show(this, getString(R.string.loading), true, false, this);
WebServiceHelper wsHelper = new WebServiceHelper("http://api.openweathermap.org/data/2.5/forecast?q=Chennai&APPID=1eefb31e8b29125236c49903fc5f2c3d");
wsHelper.addHeader("Content-Type",
"application/json");
wsHelper.setRequestBody(requestObject.toString());
wsHelper.delegate = this;
wsHelper.execute();
}

@Override
public void processFinish(String requestURL, String response) {
pdia.dismiss();
// TODO Auto-generated method stub
System.out.println("response==> "+response);
WheatherModel weather =new WheatherModel(response);
System.out.println("weather.getId()==> "+weather.getId());
}

That's all. Now you can call the web service using  WebCalls() method. Just Use this method for all the class where you want to call the web service.