Wednesday, May 13, 2015

Pass data from fragment to activity using interface

Any fragment that should pass data back to its containing activity should declare an interface to handle and pass the data. Then make sure your containing activity implements those interfaces. For example:


In your fragment, declare the interface...
public interface OnDataPass {
    public void onDataPass(String data);
}
Then, connect the containing class' implementation of the interface to the fragment in the onAttach method, like so: where a is containers activities reference .
OnDataPass dataPasser;

@Override
public void onAttach(Activity a) {
    super.onAttach(a);
    dataPasser = (OnDataPass) a;
}
Within your fragment, when you need to handle the passing of data, just call it on the dataPasser object:
public void passData(String data) {
    dataPasser.onDataPass(data);
}
Finally, in your containing activity which implements OnDataPass...
@Override
public void onDataPass(String data) {
    Log.d("LOG","hello " + data);
}
This way you can have event in another activity or fragment.
Happy coding !!!

Saturday, May 9, 2015

Android TCP stream socket data Send/Receive methods

In this post we will see how to do interaction with TCP server data using socket in simple steps.

Step 1 : Connect with TCP server .
To connect with TCP server we need IP address and port number .

 private void startConnection() throws UnknownHostException, IOException {  
           Socket client = new Socket("Your IP address", "TCP_SERVER_PORT");  
           BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()));  
           BufferedWriter output = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));  
      }  


Step 2 : After connection we can send data to server.

 private void sendDataOverServer() throws IOException {  
           String outMsg = "TCP connecting to " + TCP_SERVER_PORT+ System.getProperty("line.separator");  
           output.write(outMsg);  
           output.flush();  
           Log.v("TcpClient", "sent: " + outMsg);  
      }  

Step 3 : When we send data to server we get response using following method.

 private String receiveDataFromServer() throws IOException {  
           String inmsg = input.readLine() + System.getProperty("line.separator");  
           Log.i(getTag(), "received: " + inmsg);  
           return inmsg;  
      }  

Step 4 : To send commands to server we can use following method.

  PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client  
               .getOutputStream())), true);  
         // WHERE YOU ISSUE THE COMMANDS  
         out.println(etCommand.getText().toString());  
'

Step 5 : Close the socket connection after use.

 private void closeConnection() throws IOException {  
           if(client != null)   
                client.close();  
      }  

I will edit in depth details for socket connection over TCP stream soon.

Happy coding !

Tuesday, May 5, 2015

Android MVC pattern for listview


In this post, we will see how to implement custom listview in MVC pattern.

Steps to create custom listview using mvc pattern.

Step 1:  Create a listview in your layout 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="wrap_content"  
   android:orientation="vertical" >  
    <ListView  
     android:id="@+id/lv_data"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:dividerHeight="1dp" >  
   </ListView>  
 </LinearLayout>  

Step 2:  Create data_list_item.xml  and add  it in layout folder.

<?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="vertical" >

    <TextView
        android:id="@+id/tv_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Step 3:  Create a init adapter method in your fragment or in activity.

public void initAdapter(List<User> users) {
        lvData = (ListView) rootView.findViewById(R.id.lv_data);
        
        DataListAdapter adapter = new DataListAdapter(users,getActivity());
        lvData.setAdapter(adapter);
    }
I have used fragment here.

Step 4:  create an Adapter , here we will create a DataListAdapter.java

public class DataListAdapter extends BaseAdapter {

    private List<User> users;
    private UserHolder holder;
    private Activity mActivity ;
    
    public DataListAdapter(List<User> users,Activity activity) {
        this.users = users;
        this.mActivity = activity;
    }

    @Override
    public int getCount() {
        return users.size();
    }

    @Override
    public Object getItem(int position) {
        return users.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView != null) {
            holder = (UserHolder) convertView.getTag();
        }else {
            holder = new UserHolder(mActivity);
            convertView = holder.getConvertView();
            convertView.setTag(holder);
        }
        
        holder.initializeData(users.get(position));
        holder.applyData();
        
        return convertView;
    }
}


Step 5:  Create a Viewholder , Here we will create UserHolder.java

public class UserHolder extends BaseViewHolder {

    private TextView tvData;
    private User userItem;

    public UserHolder(Activity activity) {
        super(activity);
    }

    @Override
    public View getConvertView() {
        mView = mLayoutInflater.inflate(R.layout.data_list_item, null);
        tvData = (TextView) mView.findViewById(R.id.tv_data);
        return mView;
    }

    @Override
    public void applyData() {
        tvData.setText(userItem.getFirstname());
    }

    @Override
    public void initializeData(Object data) {

        userItem = (User) data;
    }
}


Using above five steps we can create 3 different classes to follow MVC pattern.
ViewHolder inflate data_list_item.xml as list item As View
Adapter acts as a Controller.
MainActivity acts as a Model.


Happy coding !!!


Thursday, April 30, 2015

Parse GET webservice using GSON library


In this post, We will see steps to parse GET web service.

Step 1 : Create GETservice method . This method will send HTTP get request to server. and we will get HttpResponse in InputStream format.

public String GETService(String url) {
  HttpClient httpclient = new DefaultHttpClient();
  HttpGet httpget = new HttpGet(url);

  String line = "";
  try {
   HttpResponse response = httpclient.execute(httpget);

   if (response != null) {
    InputStream inputstream = response.getEntity().getContent();
    line = convertStreamToString(inputstream);
   } else {
    Toast.makeText(mContext, "Unable to complete your request",
      Toast.LENGTH_LONG).show();
   }
  } catch (ClientProtocolException e) {
   Toast.makeText(mContext, "Caught ClientProtocolException",
     Toast.LENGTH_SHORT).show();
  } catch (IOException e) {
   Toast.makeText(mContext, "Caught IOException", Toast.LENGTH_SHORT)
     .show();
  } catch (Exception e) {
   Toast.makeText(mContext, "Caught Exception", Toast.LENGTH_SHORT)
     .show();
  }
  return line;
 }



Step 2 :  Below method will convert input stream format data into String format.

private String convertStreamToString(InputStream is) {
  String line , tempResponse = "" , respoString = "" ;
  
  BufferedReader rd = new BufferedReader(new InputStreamReader(is));
  try {
   while ((line = rd.readLine()) != null)
    tempResponse = tempResponse + line;
   respoString = tempResponse;
   if (TextUtils.isEmpty(respoString))
    return null;
  } catch (IOException e1) {
   e1.printStackTrace();
  }
  Log.d(TAG, "JSON-->" + respoString);
  return respoString.toString();
 }


Step 3:  Once we get data in string format we can use Gson libraries.
This library will help us to convert string json data into java objects .

public ResAndroid resAndroid() {
  String URL = HttpUtils.URL;
  String result = mHttpUtil.GETService(URL);

  if (!TextUtils.isEmpty(result)) {
   return new Gson().fromJson(result, ResAndroid.class);
  }
  return null;
 }
Here ResAndroid is java pojo class having fields same as json response.

We can create Pojo classes from json response using  http://www.jsonschema2pojo.org/ website.


Happy coding !!