Android: Get data insert in custom listview - android

enter image description here
I want to display the user on the custom listview, each line listview has 2 textview and social network url, when click on the listview will lead to social networking site. I tried but failed, can you suggest me? Thank you very much.

First take a list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" />
</LinearLayout>
list_row.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="wrap_content"
android:background="#dedbdc"
android:orientation="horizontal"
android:padding="5dip" >
<!-- User Name-->
<TextView
android:id="#+id/userName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rama"
android:textColor="#040404"
android:typeface="sans"
android:textSize="15dip"
android:textStyle="bold"/>
<!-- age -->
<TextView
android:id="#+id/age"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/userName"
android:textColor="#343434"
android:textSize="10dip"
android:layout_marginTop="1dip"
android:text="Just gona stand there and ..." />
<!-- Rightend info -->
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_dialog_info"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
DataModel.java
public class DataModel {
private String name;
private String age;
private String website;
public DataModel(String name, String age, String website) {
this.name = name;
this.age = age;
this.website = website;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
}
CustomAdapter.java:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends ArrayAdapter<DataModel> {
private ArrayList<DataModel> dataSet;
Context mContext;
// View lookup cache
private static class ViewHolder {
TextView txtName;
TextView txtAge;
}
public CustomAdapter(ArrayList<DataModel> data, Context context) {
this.dataSet = data;
this.mContext = context;
}
private int lastPosition = -1;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
DataModel dataModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.list_row, parent, false);
viewHolder.txtName = (TextView) convertView.findViewById(R.id.userName);
viewHolder.txtAge = (TextView) convertView.findViewById(R.id.age);
result = convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result = convertView;
}
lastPosition = position;
viewHolder.txtName.setText(dataModel.getName());
viewHolder.txtAge.setText(dataModel.getAge());
// Return the completed view to render on screen
return convertView;
}
}
MainActivity.java:
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toolbar;
import com.geeklabs.rssprarthana.DataModel;
import com.geeklabs.rssprarthana.R;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<DataModel> dataModels;
ListView listView;
private static CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView=(ListView)findViewById(R.id.list);
dataModels= new ArrayList<>();
// TO DO add your list data here for example
dataModels.add(new DataModel("Shylendra", "25","http://facebook.com"));
adapter= new CustomAdapter(dataModels,getApplicationContext());
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DataModel dataModel= dataModels.get(position);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(dataModel.getWebsite()));
startActivity(browserIntent);
}
});
}
}

Related

How to pass adapter text from model category?

I have text in the model. Must carry adapter. public int cid = -1; public String category_name; I want to transfer text only to the adapter. When I transfer some errors occur.I have tried to transfer from text model many times in adapter but I am not getting text i am new devloper How to fix this error
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.kannada.newspaper.india.R;
import com.kannada.newspaper.india.activities.MainActivitym;
import com.kannada.newspaper.india.model.Category;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class GalleryAdapter extends BaseAdapter {
private Context context;
private List<Category> mensWears;
public GalleryAdapter(Context context, List<Category> mensWears) {
this.context = context;
this.mensWears = mensWears;
}
#Override
public int getCount() {
return mensWears.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i,View view,ViewGroup viewGroup) {
final Category mensWear = mensWears.get(i);
if (view == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.custom_gallery_layout, null);
}
//For text
// TextView prdId = view.findViewById(R.id.name);
// prdId.setText(prdId.toString());
// //For images
// final ImageView imageView = view.findViewById(R.id.name);
// if(!TextUtils.isEmpty(mensWear.getItemName())){
//
//// Picasso.with(context).load(imageUrlFromServer+mensWear.category_image())
//// .into(imageView);
return view;
}
}
this model
public class Category implements Serializable {
public int cid = -1;
public String category_name;
public String category_image;
public String recipes_count;
public Category(String name, String profession, int photo) {
}
public String getItemName() {
return this.category_name;
}
public String category_image() {
return this.category_image;
}
}
layout
<com.kannada.newspaper.india.utils.SquareFrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/ll_main"
android:padding="#dimen/nav_header_vertical_spacing"
android:orientation="vertical">
<ImageView
android:background="#drawable/bg_google"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageView"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:layout_width="100dp"
android:layout_height="100dp"
android:alpha="1"
android:background="#drawable/bg_roundiconimg"
android:gravity="center"
android:orientation="vertical">
<!-- <ImageView-->
<!-- android:id="#+id/photo"-->
<!-- android:layout_width="60dp"-->
<!-- android:layout_height="60dp"-->
<!-- android:layout_gravity="center" />-->
</LinearLayout>
<TextView
android:id="#+id/name"
android:layout_width="347dp"
android:layout_height="263dp"
android:layout_marginTop="#dimen/margin10"
android:fontFamily="#font/sfprodisplayregular"
android:text="Facebook"
android:textColor="#color/colorWhite"
android:textSize="#dimen/primeryText" />
</LinearLayout>
</com.kannada.newspaper.india.utils.SquareFrameLayout>
You are doing wrong you have to get the value from models not from the textview as in your sample you are doing below
TextView prdId = view.findViewById(R.id.name);
prdId.setText(prdId.toString());
you need to get the value from the model like below
prdId.setText(mensWears.get(i).getItemName());

How do I add the value from textview to list view

I m trying to add the value from textview dynamically to listview.For that I have created another layout to take the values from user. but I'm not able to do that. I have tried many things. Kindly help.. Here is my code.
package com.example.chetan.assignment;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// String[] name= {"Apple","Banana","Mango","PineApple"};
//String[] price = {"Rs.40","Rs.60","Rs.70","Rs.80"};
List<String> names = new ArrayList<String>();
//String[] names = {"names"};
List<String> prices = new ArrayList<String>();
//String[] prices = {"prices"};
String name = getIntent().getStringExtra("name");
String price = getIntent().getStringExtra("price");
if(count==0) {
names.add(0, "name");
prices.add(0, "price");
}
if (count>0) {
names.add(count, name);
prices.add(count,price);
}
count++;
ListAdapter MyAdapter = new MyAdapter(names, prices, this);
ListView theList = (ListView) findViewById(R.id.listView);
theList.setAdapter(MyAdapter);
}
public void buttonClick(View view) {
Intent i = new Intent(this, Addlayout.class);
startActivity(i);
}
}
package com.example.chetan.assignment;
package com.example.chetan.assignment;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
class MyAdapter extends BaseAdapter {
String[] name;
String[] price;
Context context;
private static LayoutInflater myInflater = null;
public MyAdapter(String[] name, String[] price, Context context) {
this.name = name;
this.price = price;
this.context = context;
myInflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return name.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder
{
TextView nametext;
TextView pricetext;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder myholder = new Holder();
View myViews = myInflater.inflate(R.layout.myview,parent,false);
myholder.nametext= (TextView) myViews.findViewById(R.id.textView);
myholder.pricetext= (TextView) myViews.findViewById(R.id.textView2);
myholder.nametext.setText(name[position]);
myholder.pricetext.setText(price[position]);
return myViews;
}
}
package com.example.chetan.assignment;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Addlayout extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addlayout);
}
public void Onclickbutton(View view){
EditText nametext = (EditText)findViewById(R.id.editText);
EditText pricetext = (EditText)findViewById(R.id.editText2);
String namedata = nametext.getText().toString();
String pricedata = pricetext.getText().toString();
Intent intent = new Intent(this,MainActivity.class);
intent.putExtra("name",namedata);
intent.putExtra("price",pricedata);
startActivity(intent);
}
}
Here you can do something like this:
Instead of simple listview I have used RecyclerView as it has better performance.
//First create a Data class for name and price
public class Data implements Serializable {
private String name,price;
public Data(){}
public Data(String name,String price){
this.name = name;
this.price = price;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//your Addlayout class
public class Addlayout extends AppCompatActivity {
List<Data> dataList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addlayout);
}
public void Onclickbutton(View view){
EditText nameText = (EditText)findViewById(R.id.editText);
EditText priceText = (EditText)findViewById(R.id.editText2);
String nameData = nameText.getText().toString();
String priceData = priceText.getText().toString();
Data data = new Data(nameData, priceData);
dataList.add(data);
Intent intent = new Intent(this,MainActivity.class);
intent.putExtra("List", (Serializable) dataList);
startActivity(intent);
}
}
//add layout xml
//change layout according to you
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_addlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.mmc.testproject.Addlayout">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:hint="name"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="13dp"
android:id="#+id/editText" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:hint="price"
android:layout_below="#+id/editText"
android:layout_alignEnd="#+id/editText"
android:layout_marginTop="18dp"
android:id="#+id/editText2" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_alignStart="#+id/editText2"
android:layout_marginStart="43dp"
android:layout_marginTop="36dp"
android:onClick="Onclickbutton"
android:id="#+id/button" />
</RelativeLayout>
//Then your Listview Adapter
public class ListViewAdaptor extends RecyclerView.Adapter<ListViewAdaptor.MyViewHolder> {
private List<Data> mDataList;
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView name,price;
public MyViewHolder(View view){
super(view);
name = (TextView) view.findViewById(R.id.name);
price= (TextView) view.findViewById(R.id.price);
}
}
public ListViewAdaptor(List<Data> dataList){
this.mDataList = dataList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_view_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Data data = mDataList.get(position);
holder.name.setText(data.getName());
holder.price.setText(data.getPrice());
}
#Override
public int getItemCount() {
return mDataList.size();
}
}
//your Listview layout to show name and price
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/name"
android:text="name"
android:gravity="center"
android:textSize="26sp"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/price"
android:text="price"
android:gravity="center"
android:textSize="26sp"
android:layout_weight="1"/>
</LinearLayout>
//And finally the main Activity
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ListViewAdaptor mAdapter;
private List<Data> mDataList;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
Intent i = getIntent();
mDataList = (List<Data>) i.getSerializableExtra("List");
Log.e(TAG,"Datalist size : "+mDataList.size());
mAdapter = new ListViewAdaptor(mDataList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(mAdapter);
}
}
//and main Activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.mmc.testproject.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recycler_view">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Hope it helps!!!

I am new in android,i want to delete a row on clicking delete button that are shown in front of each row in list view

This is may XML class random values in which we make a row that I want to delete
randomvalues.xml
<LinearLayout
android:id="#+id/linear"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#+id/addbtn">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/img"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/img1"
/>
<LinearLayout
android:layout_width="255dp"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#339966"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/adress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:textColor="#606060" />
</LinearLayout>
</LinearLayout>
<ImageButton
android:id="#+id/removebtn"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/remove"/>
</LinearLayout>
</LinearLayout>
this is my activity_main XML in which i used a list view to show a row that I make in random values XML file
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.chaqeel.taskviews.MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linear">
<ImageButton
android:id="#+id/addbtn"
android:layout_width="30dp"
android:layout_height="40dp"
android:src="#drawable/add"
android:layout_marginLeft="280dp"/>
</LinearLayout>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/linear"
>
</ListView>
</RelativeLayout>
This is MainActivity.java in which we used a array to show the values
MainActivity.java
package com.example.chaqeel.taskviews;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
public class MainActivity extends Activity {
ListView lv;
String[] Names = {"Aqeel", "Ali", "Ansar", "Usama", "Farhad"};
String[] Address = {"Chakwal", "Rawalpindi", "Islamabad", "Lahore",
"Multan"};
int[] Images = {R.drawable.img1, R.drawable.img2, R.drawable.img3,
R.drawable.img4, R.drawable.img5};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listview);
lv.setAdapter(new dataListAdapter(Names, Address, Images));
}
class dataListAdapter extends BaseAdapter {
String[] Name, Addres;
int[] imge;
/*dataListAdapter() {
Name = null;
Addres = null;
imge=null;
}*/
public dataListAdapter(String[] text, String[] text1, int[] text3) {
Name = text;
Addres = text1;
imge = text3;
}
public int getCount() {
return Name.length;
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup
parent) {
LayoutInflater inflater = getLayoutInflater();
final View row;
row = inflater.inflate(R.layout.randomvalues, parent, false);
final TextView Name, Addres;
ImageView imge;
Name = (TextView) row.findViewById(R.id.name);
Addres = (TextView) row.findViewById(R.id.adress);
imge = (ImageView) row.findViewById(R.id.img);
Name.setText(Names[position]);
Addres.setText(Address[position]);
imge.setImageResource(Images[position]);
final ArrayList<String> lvv= new ArrayList<>();
Collections.addAll(lvv,Names);
// Collection.addAll(lvv,Address);
ImageButton dltbutton = (ImageButton) findViewById(R.id.removebtn);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
lvv.remove(Names);
lvv.remove(Address);
notifyDataSetChanged();
}
});
return (row);
}
}
}
In the onClickListener try the following code
youradapter.notifyDataSetChanged();
In the deletebutton onClickListener try this
Names = ArrayUtils.removeElement(Names,Names[position]);
Address = ArrayUtils.removeElement(Address,Address[position]);
notifyDataSetChanged();
Though it is advised to use OOP concept like a class to hold the Arrays of Names,Address and Images.
Try below code:
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Name = ArrayUtils.removeElement(Names, Names[position]);
Address = ArrayUtils.removeElement(Address, Address[position]);
imge = ArrayUtils.removeElement(imge, imge[position]);
notifyDataSetChanged();
}
});
change this:
ImageButton dltbutton = (ImageButton) findViewById(R.id.removebtn);
dltbutton.setTag(position);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer index = (Integer) view.getTag();
lvv.remove(index.intValue());
notifyDataSetChanged();
}
});
Are you from Chakwal? I am Chakwalian. Again StackOverflow is telling me that my answer does not meet thier quality requirements.
You need to better idea to use Model class as below:-
create a model class MyModel.class
import java.util.ArrayList;
import java.util.List;
public class MyModel {
String Name, Address;
int image;
public MyModel(String name, String address, int image) {
Name = name;
Address = address;
this.image = image;
}
public String getName() {
return Name;
}
public String getAddress() {
return Address;
}
public int getImage() {
return image;
}
}
and then add with adapter class see below:
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
ListView lv;
String[] Names = {"Aqeel", "Ali", "Ansar", "Usama", "Farhad"};
String[] Address = {"Chakwal", "Rawalpindi", "Islamabad", "Lahore",
"Multan"};
int[] Images = {R.drawable.ic_menu_camera, R.drawable.ic_menu_gallery, R.drawable.ic_menu_manage,
R.drawable.ic_menu_send, R.drawable.ic_menu_share};
private List<MyModel> myModel=new ArrayList<>();
private DataListAdapter dataListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
lv = (ListView) findViewById(R.id.listview);
for(int i=0;i<Names.length;i++){
myModel.add( new MyModel(Names[i],Address[i],Images[i]));
}
dataListAdapter=new DataListAdapter(myModel);
lv.setAdapter(dataListAdapter);
}
class DataListAdapter extends BaseAdapter {
private List<MyModel> myModel=new ArrayList<>();
public DataListAdapter(List<MyModel> myModel) {
this.myModel=myModel;
}
public int getCount() {
return myModel.size();
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, final ViewGroup
parent) {
LayoutInflater inflater = getLayoutInflater();
final View row;
row = inflater.inflate(R.layout.randomevalue, parent, false);
final TextView Name, Addres;
ImageView imge;
Name = (TextView) row.findViewById(R.id.name);
Addres = (TextView) row.findViewById(R.id.adress);
imge = (ImageView) row.findViewById(R.id.img);
Name.setText(myModel.get(position).getName());
Addres.setText(myModel.get(position).getAddress());
imge.setImageResource(myModel.get(position).getImage());
ImageButton dltbutton = (ImageButton) row.findViewById(R.id.removebtn);
dltbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myModel.remove(position);
notifyDataSetChanged();
}
});
return (row);
}
}
public void addMore(View v)
{
myModel.add( new MyModel("Mahesh","India",R.drawable.ic_menu_share));
dataListAdapter.notifyDataSetChanged();
}
}
public void addMore(View v)
{
myModel.add( new MyModel("Mahesh","India",R.drawable.ic_menu_share));
dataListAdapter.notifyDataSetChanged();
}
add android:onClick="addMore" to your add button
it will fine Happy Coding :)
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterContextMenuInfo info =(AdapterContextMenuInfo) item.getMenuInfo();
pos=info.position;
deleteditem=myList.get(pos);
if(item.getTitle()=="Delete")
{
String delete = myList.get(pos);
File f = new File(path + "/"+ delete);
if (f != null && f.exists())
{
f.delete();
}
myList.remove(pos);
adapter. notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "item has deleted",Toast.LENGTH_LONG).show();
}

Inflate ListView with TreeMap data (Custom Adapter)

Solved: I have created an adapter based on #JJV 's suggestion. I am aware that there is plenty of room for improvement, but it works for now.
I have updated this simplified version of my program, with the working code; I hope it will be useful to others:
MainActivity.java:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.Map;
import java.util.TreeMap;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Map<Integer, Object> m = new TreeMap<Integer, Object>();
int key = 123;
Item obj1 = new Item("abc", "xyz", 888);
m.put(key, obj1);
key = 456;
Item obj2 = new Item("def", "zyx", 999);
m.put(key, obj2);
ListAdapter adapter = new TreeMapAdapter(this, (TreeMap<Integer, Object>) m);
ListView itemListView = (ListView) findViewById(R.id.itemListView);
itemListView.setAdapter(adapter);
}
public class Item {
private String name;
private String thing;
private int number;
Item(String name, String thing, int number) {
this.name = name;
this.thing = thing;
this.number = number;
}
public String getName() {
return this.name;
}
public String getThing() {
return this.thing;
}
public int getNumber() {
return this.number;
}
}
}
main_activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemListView" />
</LinearLayout>
listview_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/thing" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/number" />
</LinearLayout>
TreeMapAdapter.java:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.TreeMap;
public class TreeMapAdapter extends ArrayAdapter<String> {
private Context context;
private TreeMap<Integer, Object> treeMap;
private Integer[] mapKeys;
public TreeMapAdapter(Context context, TreeMap<Integer, Object> data) {
super(context, R.layout.listview_row);
this.context = context;
this.treeMap = data;
mapKeys = treeMap.keySet().toArray(new Integer[getCount()]);
}
public int getCount() {
return treeMap.size();
}
public String getItem(int position) {
return String.valueOf(treeMap.get(mapKeys[position]));
}
public long getItemId(int position) {
return mapKeys[position];
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater deviceInflater = LayoutInflater.from(getContext());
View listViewRow = deviceInflater.inflate(R.layout.listview_row, parent, false);
MainActivity.Item test = (MainActivity.Item) treeMap.get(mapKeys[position]);
String nameString = test.getName() + ", ";
String thingString = test.getThing() + ", ";
String numberInt = String.valueOf(test.getNumber());
TextView name = (TextView) listViewRow.findViewById(R.id.name);
TextView thing = (TextView) listViewRow.findViewById(R.id.thing);
TextView number = (TextView) listViewRow.findViewById(R.id.number);
name.setText(nameString);
thing.setText(thingString);
number.setText(numberInt);
return listViewRow;
}
}
Result:
I cannot embed a screenshot of the result in this post, because I do not have 10 reputation, but you can see the result of running the code here: http://i.stack.imgur.com/QoXX1.png
do something like this:
public class TreeMapAdapter extends ArrayAdapter<String> {
private Context context
private TreeMap<Integer, Object> treeMap;
private int mapKeys[];
public TreeMapAdapter(Context context,TreeMap<Integer, Object> treeMap)
this.context=context;
this.treeMao=treeMap;
mapKeys=treemap.keySet().toArray();
}
public int getCount() {
return treeMap.size();
}
public String getItem(int position) {
return treeMap.get(mapKeys[position]);
}
public long getItemId(int position) {
return mapKeys[position];
}
//your getView method....
}

Android GridView flip animation on each cell?

I am fairly new to android development and i'm creating a few simple applications for myself.
I have ran into a problem in relation to animations, in particular a flip animation on each individual cell of a gridview when that cell is clicked.
What my application does so far is retrieves the contacts from the phone and displays the contact photo and the name in a gridview using an array adapter.
What i want to happen is when the user clicks on the grid cell of a contact it will perform a flip animation and display the contacts phone number on the back.
When the user clicks on that cell again it will flip back to the previous view of the name and photo.
I have searched the internet and tried a few tutorials but none that have been of any great help, must of them infact confuse me, so if someone could help that would be great.
I'll post my current code below!
Thanks in advance.
This code is used to retrieve the information of the contacts!
package content;
import android.provider.MediaStore.Images;
public class ContactBean {
private String name;
private String phoneNo;
private String proPic;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getProPic() {
return proPic;
}
public void setProPic(String proPic) {
this.proPic = proPic;
}
}
ViewContatcsActivity
package viewContacts;
import com.example.contactflipper.R;
import content.ContactBean;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ViewContactsActivity extends Activity implements
OnItemClickListener {
private GridView listView;
private List<ContactBean> list = new ArrayList<ContactBean>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_viewcon_grid);
listView = (GridView) findViewById(R.id.gridview);
listView.setOnItemClickListener(this);
String image_uri = "";
Bitmap bitmap = null;
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
while (phones.moveToNext()) {
String name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
image_uri = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
ContactBean objContact = new ContactBean();
objContact.setName(name);
objContact.setPhoneNo(phoneNumber);
list.add(objContact);
}
phones.close();
GridAdapter objAdapter = new GridAdapter(
ViewContactsActivity.this, R.layout.card_front, list);
listView.setAdapter(objAdapter);
if (null != list && list.size() != 0) {
Collections.sort(list, new Comparator<ContactBean>() {
#Override
public int compare(ContactBean lhs, ContactBean rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
AlertDialog alert = new AlertDialog.Builder(
ViewContactsActivity.this).create();
alert.setTitle("");
alert.setMessage(list.size() + " Contact Found!!!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
} else {
showToast("No Contact Found!!!");
}
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onItemClick(AdapterView<?> listview, View v, int position,
long id) {
ContactBean bean = (ContactBean) listview.getItemAtPosition(position);
//implement something on the click of each listed item - bean
}
}
GridAdapter
package viewContacts;
import java.util.List;
import com.example.contactflipper.R;
import com.example.contactflipper.R.id;
import content.ContactBean;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class GridAdapter extends ArrayAdapter<ContactBean> {
private Activity activity;
private List<ContactBean> items;
private int row;
private ContactBean objBean;
public GridAdapter(Activity act, int row, List<ContactBean> items) {
super(act, row, items);
this.activity = act;
this.row = row;
this.items = items;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(row, null);
holder = new ViewHolder();
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
if ((items == null) || ((position + 1) > items.size()))
return view;
objBean = items.get(position);
holder.tvname = (TextView) view.findViewById(R.id.profileName);
//holder.tvPhoneNo = (TextView) view.findViewById(R.id.tvphone);
if (holder.tvname != null && null != objBean.getName()
&& objBean.getName().trim().length() > 0) {
holder.tvname.setText(Html.fromHtml(objBean.getName()));
}
if (holder.tvPhoneNo != null && null != objBean.getPhoneNo()
&& objBean.getPhoneNo().trim().length() > 0) {
holder.tvPhoneNo.setText(Html.fromHtml(objBean.getPhoneNo()));
}
if (holder.ivPic != null && null != objBean.getProPic()
&& objBean.getProPic().trim().length() > 0) {
holder.ivPic.setBackground((Drawable) Html.fromHtml(objBean.getProPic()));
}
return view;
}
public class ViewHolder {
public TextView tvname, tvPhoneNo;
public ImageView ivPic;
}
}
ViewContactsFragment
package viewContacts;
import com.example.contactflipper.R;
import com.example.contactflipper.R.id;
import com.example.contactflipper.R.layout;
import content.AppDetails;
import android.app.Activity;
import android.app.Fragment;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
public class VCGridFragment extends Fragment {
public static GridView mGridview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.menu_viewcon_grid, container, false);
Log.d("Called", "on Create View");
return view;
}
//super.onCreateView(inflater, container, savedInstanceState);
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
Log.d("Called", "created Grid");
mGridview = (GridView) view.findViewById(R.id.gridview);
Configuration config = getResources().getConfiguration();
if(AppDetails.isTablet){
if(config.orientation == Configuration.ORIENTATION_LANDSCAPE){
mGridview.setNumColumns(4);
}else{
mGridview.setNumColumns(3);
}
}else{
if(config.orientation == Configuration.ORIENTATION_LANDSCAPE){
mGridview.setNumColumns(3);
}else{
mGridview.setNumColumns(2);
}
}
/*
mGridview.setOnItemClickListener(new onItemClickLitener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
onGridItemClick((GridView) parent, view, position, id);
}
});
}
public void onGridItemClick(GridView g, View v, int position, long id){
Activity activity = getActivity();
}
*/
}
}
GridView xml -
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/contact_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#ffffff"
android:scrollbars="none"
tools:context=".MainActivity" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#drawable/gradient"
android:padding="10dp" >
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp"
android:numColumns="2"
android:horizontalSpacing="8dp"
android:scrollbars="none"
android:verticalSpacing="8dp" >
</GridView>
<Button
android:id="#+id/backButton"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="top|right"
android:background="#8043BFC7"
android:text="#string/edit_contacts"
android:textColor="#ffffff"
android:textStyle="bold" />
</FrameLayout>
</RelativeLayout>
FRONT OF CARD XML -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="180dp"
android:layout_height="180dp"
android:orientation="vertical" >
<ImageView
android:id="#+id/profileThumb"
android:layout_width="match_parent"
android:layout_height="140dp"
></ImageView>
<TextView
android:id="#+id/profileName"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_gravity="bottom"
android:background="#40000000"
android:textColor="#ffffff"
android:textSize="22sp">
</TextView>
</LinearLayout>
BACK OF CARD XML -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="180dp"
android:layout_height="180dp"
android:orientation="vertical"
android:background="#a6c"
android:padding="10dp"
android:gravity="bottom"
>
<TextView
android:id="#+id/infoName"
style="?android:textAppearanceLarge"
android:textStyle="bold"
android:textColor="#fff"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="HCKDAHOIW"
></TextView>
<TextView
android:id="#+id/infoLocality"
style="?android:textAppearanceSmall"
android:textAllCaps="true"
android:textStyle="bold"
android:textColor="#80ffffff"
android:lineSpacingMultiplier="1.2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="convoy"
></TextView>
<TextView
android:id="#+id/infoEmail"
style="?android:textAppearanceSmall"
android:textColor="#80ffffff"
android:lineSpacingMultiplier="1.2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="fowfow#email.com"
></TextView>
<TextView
android:id="#+id/infoNumber"
style="?android:textAppearanceSmall"
android:textColor="#80ffffff"
android:lineSpacingMultiplier="1.2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="(086) 123 4567"
></TextView>
</LinearLayout>
I would go about it something like this.
Let's say this is the layout you're going to inflate in your gridview and it's named view_flipper_layout. Of course you'd have to add all your textview components etc. to either the front or back linearlayout.
<?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" >
<ViewFlipper
android:id="#+id/my_view_flipper"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/front"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<LinearLayout
android:id="#+id/back"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</ViewFlipper>
</LinearLayout>
Now let's say this is the adapter
public GridAdapter(Activity act, int row, List<ContactBean> items) {
super(act, row, items);
this.activity = act;
this.row = row;
this.items = items;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//here is where you inflate your layout containing your viewflipper
view = inflater.inflate(R.layout.view_flipper_layout, null);
} else {
holder = (ViewHolder) view.getTag();
}
//reference the viewFlipper
ViewFlipper flipper = (viewFlipper) holder.findViewById(R.id.my_view_flipper);
//your front layout should be set to displayed be default
//now you can get get references to your textview or ImageViews contained within the layout
TextView name = (TextView) holder.findViewById(R.id.name);
name.setText("your text");
ImageView picture = (ImageView) holder.findViewById(R.id.picture);
//now you set your onclick and pass it the current viewflipper to control the displayed child
flipper.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View click) {
flipViewFlipper(flipper);
}
});
return view;
}
private void flipViewFlipper(ViewFlipper flipper){
if(flipper.getDisplayedChild() == 0){
flipper.setDisplayedChild(1);
}
else{
flipper.setDisplayeChild(0);
}
}
}
I'm typing this from my head, so just use it as a guide if you attempt to go this way.

Categories

Resources