Friday 10 July 2015

adding more than two different layouts to listview

         I have searched a lot for adding different layouts to listview but I found same example code in so many websites i.e adding two different layouts to listview. I didn't find how can we add more than 2 different layouts to the listview any where.So i am postng this.

Now you can add any number of layouts to list view.

We want to have something like the pic shown given below:


We want to have something like the pic shown below: - See more at: http://www.survivingwithandroid.com/2014/08/android-listview-with-multiple-row.html#sthash.c32Jcba8.dpu
We want to have something like the pic shown below: - See more at: http://www.survivingwithandroid.com/2014/08/android-listview-with-multiple-row.html#sthash.c32Jcba8.dpuf
We want to have something like the pic shown below: - See more at: http://www.survivingwithandroid.com/2014/08/android-listview-with-multiple-row.html#sthash.c32Jcba8.

Basically, you have to follow these steps:
  • Create the custom layouts.
  • Create a custom adapter.
  • Override getViewTypeCount() method in your custom adapter with the amount of layouts you're gonna use in your listview.
  • Override getItemViewType(int position) method also in your custom adapter to return the current item's view type.
  • Additionally, it's essential to use a view holder to avoid memory leaks.
Take a look in the codebelow:
      first we have to create custom layouts.In this example i am adding the 3 layouts.one for TextView, one for ImageView and one more for ImageView.
text_layout.xml
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/resulttext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:background="@drawable/bubble_a" />

</LinearLayout>

image_layout.xml
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/resultimage2"
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:layout_gravity="bottom|right"
        android:background="@drawable/popup"
        android:scaleType="fitXY" />
</FrameLayout>
image_layout2.xml
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/resultimage2"
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:layout_gravity="bottom|right"
        android:background="@drawable/popup"
        android:scaleType="fitXY" />
</FrameLayout>
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="6dp"
        android:layout_marginRight="6dp"
        android:divider="@android:color/transparent"
        android:dividerHeight="5.0sp"
        android:layout_weight="0.55"/>


    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="10">

        <EditText
            android:id="@+id/one"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="8"
            android:singleLine="true"
            android:ems="10"
            android:hint="enter message"/>

        <Button
            android:id="@+id/button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.4"
            android:text="send" />


        <Button
            android:id="@+id/button2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.8"
            android:text="image" />
        <Button
            android:id="@+id/button3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.8"
            android:text="small" />

    </LinearLayout>
</LinearLayout>
Then, we create the list item. In our case, with a string and Drawables.
public class ListItem {

    String name;
    Drawable image;
    Drawable image2;
    
    public ListItem(Drawable image, String name) {
        super();

        this.image = image;
        this.name = name;
    }
    public ListItem() {

    }
    public ListItem(String name) {
        super();
        this.name = name;

    }

    public ListItem(Drawable image) {
        super();
        this.image = image;
    }

    public ListItem(Drawable image2, int i) {
        super();
        this.image2=image2;
    }

    public Drawable getImage2() {
        return image2;
    }

    public void setImage2(Drawable image2) {
        this.image2 = image2;
    }

    public Drawable getImage() {
        return image;
    }

    public void setImage(Drawable image) {
        this.image = image;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
} 
 then we create our custom adapter overriding getViewTypeCount() and getItemViewType(int position).
public class MyCustomAdapter extends BaseAdapter {

    private static final int LAYOUT_0 = 0;
    private static final int LAYOUT_1 = 1;
    private static final int LAYOUT_2 = 2;
    private static final int MAX_LAYOUT_COUNT = 3;

    private ArrayList<ListItem> mData = new ArrayList<ListItem>();
    private LayoutInflater mInflater;
    private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
    private TreeSet<Integer> mSeparatorsSet2 = new TreeSet<Integer>();

    MyCustomAdapter adapter;
    Context context;
    int flag = -1;

    public MyCustomAdapter(Context context) {

        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.context = context;
        //Toast.makeText(this.context,"i am adapter",Toast.LENGTH_SHORT).show();
    }

    public void addItem(final ListItem listItem) {
        //Toast.makeText(this.context,"i am addItem",Toast.LENGTH_SHORT).show();
        mData.add(listItem);
        notifyDataSetChanged();
    }

    public void addSeparatorItem(final ListItem listItem) {
        mData.add(listItem);
        // save separator position
        mSeparatorsSet.add(mData.size() - 1);
        notifyDataSetChanged();

    }

    public void addSeparatorItem2(ListItem listItem) {
        mData.add(listItem);
        mSeparatorsSet2.add(mData.size() - 1);
        notifyDataSetChanged();
    }

    @Override
    public int getItemViewType(int position) {
        if (mSeparatorsSet2.contains(position))
            return LAYOUT_2;
        else if (mSeparatorsSet.contains(position))
            return LAYOUT_1;
        else
            return LAYOUT_0;
    }

    @Override
    public int getViewTypeCount() {
        return MAX_LAYOUT_COUNT;
    }

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

    @Override
    public ListItem getItem(int position) {
        return mData.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //Toast.makeText(this.context,"i am getVIew",Toast.LENGTH_SHORT).show();
        ViewHolder holder = null;
        ListItem myImage = mData.get(position);
        int type = getItemViewType(position);
        if (convertView == null) {
            holder = new ViewHolder();
            switch (type) {
                case LAYOUT_0:
                    convertView = mInflater.inflate(R.layout.text_layout, null);
                    holder.textView = (TextView) convertView.findViewById(R.id.resulttext);
                    holder.textView.setText(myImage.getName());
                    break;
                case LAYOUT_1:
                    convertView = mInflater.inflate(R.layout.image_layout, null);
                    holder.img = (ImageView) convertView.findViewById(R.id.resultimage);
                    holder.img.setImageDrawable(myImage.getImage());
                    break;
                case LAYOUT_2:
                    convertView = mInflater.inflate(R.layout.image_layout2, null);
                    holder.img2 = (ImageView) convertView.findViewById(R.id.resultimage2);
                    holder.img2.setImageDrawable(myImage.getImage2());
                    break;
            }
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        switch (type) {
            case LAYOUT_0:
                holder.textView.setText(myImage.getName());
                break;
            case LAYOUT_1:
                holder.img.setImageDrawable(myImage.getImage());
                break;
            case LAYOUT_2:
                holder.img2.setImageDrawable(myImage.getImage2());
                break;
        }
        convertView.setTag(holder);
        return convertView;
    }

    public static class ViewHolder {
        public TextView textView;
        public ImageView img;
        public ImageView img2;
    }
}

finally our CustomListView.java
public class CustomListView extends ActionBarActivity {
    private static final int PICK_IMAGE_REQUEST = 1;
    private static final int PICK_IMAGE2_REQUEST = 1;
    private MyCustomAdapter mAdapter;

    Button text_button, image_button,image2_button;
    EditText text;
    String result;
    ListView dataList;
    int image=0,image2=0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        text = (EditText) findViewById(R.id.one);
        text_button = (Button) findViewById(R.id.button);
        image_button = (Button) findViewById(R.id.button2);
        image2_button =(Button)findViewById(R.id.button3);
        dataList=(ListView)findViewById(R.id.list);
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#2196f3")));

        mAdapter = new MyCustomAdapter(CustomListView.this);
        text_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                result = text.getText().toString();
                text.setText("");
                mAdapter.addItem(new ListItem(result));
                scrollMyListViewToBottom();
            }
        });
        image_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                image=1;
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"),PICK_IMAGE_REQUEST);

            }
        });
        image2_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                image2=1;
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select image2"),PICK_IMAGE2_REQUEST);
            }
        });

        dataList.setAdapter(mAdapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null && image==1) {
            image=0;
            Uri uri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                Drawable d = new BitmapDrawable(getResources(), bitmap);
                mAdapter.addSeparatorItem(new ListItem(d));
                scrollMyListViewToBottom();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null&& image2==1) {
            image2=0;
            Uri uri2 = data.getData();

            try {
                Bitmap bitmap2 = MediaStore.Images.Media.getBitmap(getContentResolver(), uri2);
                Drawable dd = new BitmapDrawable(getResources(), bitmap2);
                mAdapter.addSeparatorItem2(new ListItem(dd, 1));
                scrollMyListViewToBottom();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    private void scrollMyListViewToBottom(){

        dataList.post(new Runnable() {
            @Override
            public void run() {
                // Select the last row so it will scroll into view...
                dataList.setSelection(mAdapter.getCount() - 1);
            }
        });
    }
}


Clic Here To Download Code

is it helpful to you or not?

Friday 3 July 2015

Introduction to json data in Android/Java


Introduction:
        JSON is an XML alternative. It is the communication and data exchange protocol, created mainly to use in JavaScript (JSON = JavaScript Object Notation), however it is also widely used in Java or Android apps to exchange data over the internet. Basic JSON message (JSONObject) consists of  key-value pairs, like this one:
eg:1
{ 
     "userid":238,
     "username":"Pavan",
     "password":"password",
     "isgoodprogrammer":1
} 
JSON is fat-free, compared to XML, because there is significant difference in amount of metadata attached to message. Just compare XML to JSON message. This XML has exactly the same user data as JSON in the example above(more example clic here)
eg:2 
<user>
        <userid>238</userid> 
        <username>Pavan</username>
        <password>password</password>
        <isgoodprogrammer>1</isgoodprogrammer>
</user> 

Android/Java

         Android has built-in JSON utils,and for java, there is jar to include to application(for example json-org.jar).Add jar to Build Path.
Using JSON in Java code is the same for both Android and Java.

Simple JSON Object
         JSONObject is the simpliest key-value pair structure in JSON. Creating JSONObject like in eg:1 is done by this code:
JSONObject user = new JSONObject();
user.put("userid", 238);
user.put("username", "Pavan");
user.put("password", "password");
user.put("isgoodprogrammer", 1); 
Reading value from JSONObject is done by:
int userId = user.getInt("userid");
String userName = user.optString("userName");
getString() – returns String containing firstName or throws JSONException
if there was no object with key = “firstName”

optString() – returns String containing firstName or empty String (“”)
if there was no object with key = “firstName”

Simple JSON Array of objects:
         Another structure is JSONArray. This is a set of JSONObjects (note that JSONArray is also a JSONobject). 
here is sample of Java code how to create JSONArray of users:
JSONObject user = new JSONObject();
user.put("userid", 238);
user.put("username", "Pavan");
user.put("password", "password");
user.put("isgoodprogrammer", 1);

JSONObject user2 = new JSONObject();
user2.put("userid",282);
user2.put("username", "Bob");
user2.put("password", "security");
user2.put("isgoodprogrammer", 1);

JSONArray clients = new JSONArray();
clients.put(user);
clients.put(user2);
and the JSON message produced by this code is: 
[
 {
       "userid":238,
       "username":"Pavan",
       "password":"password",
       "isgoodprogrammer":1
 },
 {
       "userid":282,
       "username":"Bob",
       "password":"security",
       "isgoodprogrammer":1
 }
]  
(note that keys are not ordered as in Java code. Order does not matter)
here order is not important. 
Reading JSONObject from JSONArray is done by:
for (int i = 0; i<clients.length();i++) {
 JSONObject usr = clients.getJSONObject(i);
}
JSON features:
1. JSONObjects and Arrays can be nested as many times as needed. JSONArray can be added to JSONObject as element with its id by:
JSONObject.put("key", new JSONArray); 
2. JSONObject can be easily serialized to String in order to write to file or send over the Internet. The library also reads JSONObject from String (remember to handle JSONException, that is thrown when String input is not well formatted). See sample here:
JSONObject user = new JSONObject();
user.put("userid", 238);
String JsonString = user.toString();
JSONObject object = new JSONObject(JsonString);
3. There are utils that enables to convert Java objects, like Hashtables to JSON just by one line of code(see  GSON)