Can not identify the cause of Application crash - java

I have this following class which when runs and comes to a certain line in the class the application crashes. If i comment out that line the application runs well. When i look at the logcat i don't find any CausedBy Text. So can not figure out the cause of this crash. Someone please help me out to solve this.
public class Secondscreen extends Activity {
int total=0;
final ArrayList<Listitem> arrayList=new ArrayList<Listitem>();
BaseAdapter adapter =null;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
ListView lv= (ListView) findViewById(R.id.listView1);
final TextView showtotal = (TextView) findViewById(R.id.totalprice);
final Button thirdBtn = (Button) findViewById(R.id.third);
final Controller aController = (Controller) getApplicationContext();
final int cartSize = aController.getCart().getCartSize();
//Addition of item to arraylist
if(cartSize >0)
{
for(int i=0;i<cartSize;i++)
{
String pName = aController.getCart().getProducts(i).getProductName();
int pPrice = aController.getCart().getProducts(i).getProductPrice();
int pQuantity = aController.getCart().getProducts(i).getProductQuantity();
String pDisc = aController.getCart().getProducts(i).getProductDesc();
total = total + pPrice;
Listitem item=new Listitem(pName, pPrice, pDisc, pQuantity);
Log.e("quantity", ""+pQuantity);
Log.e("Intem's quantity", ""+item.getQuantity());
arrayList.add(item);
Log.e("Arraylist item quantity", ""+arrayList.get(i).getQuantity());
}
showtotal.setText(""+total);
}
adapter= new BaseAdapter(){
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(final int position, View view, ViewGroup viewgroup) {
if (view == null) {
view=inflater.inflate(R.layout.pattern, null);
}
TextView tv=(TextView) view.findViewById(R.id.nameview);
TextView tv2=(TextView) view.findViewById(R.id.pdesc);
TextView tv3=(TextView) view.findViewById(R.id.priceView);
TextView tv4=(TextView) view.findViewById(R.id.quantityView);
Button btn=(Button) view.findViewById(R.id.patternButton);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int tempstore=arrayList.get(position).getPrice();
total=total-tempstore;
arrayList.remove(position);
showtotal.setText(""+total);
ModelProducts tempProductObject = aController.getProducts(position);
aController.getCart().removeProducts(tempProductObject);
adapter.notifyDataSetChanged();
int cartSize2 = aController.getCart().getCartSize();
}
});
tv.setText(arrayList.get(position).getName());
tv2.setText(""+arrayList.get(position).getPrice());
tv3.setText(arrayList.get(position).getDesc());
tv4.setText(arrayList.get(position).getQuantity()); //<-this is the line which when gets executed causes the application to crash.
return view;
}
};
lv.setAdapter(adapter);
}
}

yes getQuantity() returns an int value
So change this
tv4.setText(arrayList.get(position).getQuantity());
to
tv4.setText(String.valueOf(arrayList.get(position).getQuantity()));
What happens is setText(int) looks for a Resource with the int value if not found you end up getting ResourceNotFoundException
What you want is setText(CharacterSequence) so you need use String.valueof(intvalue)

Related

Need help in Multiplying the edit text value with a text view value from a custom list view in android

I have created a custom list view with a image view, 2 text view,one edit text one is for displaying brand names a string value another for displaying loyalty points, edit text for entering the quantity by the user which will be multiplied with loyalty point from text view.I have tried to multiplying the user entered value in each list item (from edit text)with the text view loyalty points value,I have implemented my own logic for multiplying it but it is not working, I have posted my code here for your reference correct me if any thing wrong in the code
MainActivity.java
public class MainActivity extends Activity {
ListView lv;
Context context;
static TextView ttv;
ArrayList prgmName;
public static int [] prgmImages={R.drawable.images,R.drawable.images1,R.drawable.images2,R.drawable.images3,R.drawable.images4,R.drawable.images5,R.drawable.images6,R.drawable.images7,R.drawable.images8};
public static String [] prgmNameList={"Britania","Rin","Goodrej","ITC","Nestle","Wheel","Ariel","Tide"};
public static String [] loyal_pts={"10","5","15","25","20","18","30","32"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
ttv= (TextView) findViewById(R.id.tot_point);
lv=(ListView) findViewById(R.id.listView);
lv.setAdapter(new CustomAdapter(this, prgmNameList,prgmImages,loyal_pts));
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter{
String [] result;
String [] Pts;
Context context;
int [] imageId;
int total_points;
String con_pts;
int lyl_pts;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, int[] prgmImages, String[] loyal_pts) {
// TODO Auto-generated constructor stub
result=prgmNameList;
Pts=loyal_pts;
context=mainActivity;
imageId=prgmImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
TextView tv1;
ImageView img;
EditText etxt;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder=new Holder();
View rowView;
// final int total_points,con_pts,lyl_pts;
rowView = inflater.inflate(R.layout.item_list, null);
try{
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.etxt= (EditText) rowView.findViewById(R.id.edit_txt);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.tv1= (TextView) rowView.findViewById(R.id.textView2);
holder.tv.setText(result[position]);
holder.tv1.setText(" " + Pts[position] + "pts");
holder.img.setImageResource(imageId[position]);
System.out.println("total points"+total_points);
holder.etxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
lyl_pts = Integer.parseInt(String.valueOf(Pts[position]));
con_pts = holder.etxt.getText().toString().trim();
total_points = lyl_pts * Integer.parseInt(con_pts);
Toast.makeText(context,total_points,LENGTH_LONG).show();
System.out.println("heyy"+total_points);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
catch(Exception e){
e.printStackTrace();
}
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
Toast.makeText(context, "You Clicked " + result[position], LENGTH_LONG).show();
}
catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
});
return rowView;
}
}
getView() is called whenever a new item is displayed on screen. at the initial phase nothing will be in your EditText so that you are not getting expected result from this line in getView() method.
con_pts=holder.etxt.getText().toString().trim();
I suggest either putting some initial value at etxt Or moving the logic in afterTextChanged like here
#Override
public void afterTextChanged(Editable s) {
lyl_pts=Integer.parseInt(String.valueOf(Pts[position]));
con_pts=holder.etxt.getText().toString().trim();
total_points = lyl_pts * Integer.parseInt(con_pts);
System.out.println("total points"+total_points);
}

Fix Number Of Column And Row in Grid View

I am Listing all the Apps installed on device in Fragment which having gridview inside. what i want to do is, i want 4 col * 5 rows(20 App in one fragment only) , if i install new app (app count 21) it must set on the next fragment and set at the top left of new fragment , fragment should generate dynamically , and add to viewpager.
here is my code. MainActivity :
public class MainActivity extends FragmentActivity {
ViewPager pager;
AppViewAdapter adapter;
GridFrag gridFrag;
FragmentManager fragmentManager;
FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindView();
init();
addListener();
}
private void bindView() {
pager = (ViewPager) findViewById(R.id.slideingpager);
}
private void init() {
adapter = new AppViewAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
}
}
GridFragment.java :
public class GridFrag extends android.support.v4.app.Fragment implements
OnItemClickListener {
GridView gridView;
ViewAdapter viewAdapter;
PackageManager packageManager;
int columnsOfGridView;
public class AppDetails {
Drawable icon;
String label;
}
AppDetails packages[];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.gridfrag, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
packageManager = getActivity().getPackageManager();
gridView = (GridView) getActivity().findViewById(R.id.grid);
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> packList = packageManager.queryIntentActivities(
mainIntent, 0);
packages = new AppDetails[packList.size()];
for (int i = 0; i < packList.size(); i++) {
packages[i] = new AppDetails();
packages[i].icon = packList.get(i).loadIcon(packageManager);
packages[i].label = packList.get(i).loadLabel(packageManager)
.toString();
}
viewAdapter = new ViewAdapter(getActivity(), packages);
gridView.setAdapter(viewAdapter);
int totalApps = gridView.getCount();
Toast.makeText(getActivity(), "Total "+ totalApps + " App(s)Found",Toast.LENGTH_SHORT).show();
gridView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(),
"You Clicked on : " + packages[position].label,
Toast.LENGTH_SHORT).show();
}
}
ViewAdapter.java (GridAdapter)
public class ViewAdapter extends BaseAdapter {
private Context context;
AppDetails setPacksForAdapter[];
public ViewAdapter(Context c, AppDetails apps[]) {
context = c;
setPacksForAdapter = apps;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return setPacksForAdapter.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder {
ImageView imgDefaultAppIcon;
TextView tvDefaultAppLabel;
}
#Override
public View getView(int pos, View v, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = new ViewHolder();
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.grid_view, null);
holder.imgDefaultAppIcon = (ImageView) v
.findViewById(R.id.ivAppIcon);
holder.tvDefaultAppLabel = (TextView) v
.findViewById(R.id.tvAppLabel);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imgDefaultAppIcon.setImageDrawable(setPacksForAdapter[pos].icon);
holder.tvDefaultAppLabel.setText(setPacksForAdapter[pos].label);
return v;
}
}
AppViewAdepter.java (For ViewPager)
public class AppViewAdapter extends FragmentPagerAdapter {
List<Fragment> fragmentsList;
public AppViewAdapter(FragmentManager fm) {
super(fm);
this.fragmentsList = new ArrayList<Fragment>();
for (int i = 0; i <= 2; i++) {
if (i % 2 == 0)
fragmentsList.add(new GridFrag());
else
fragmentsList.add(new FragTwo());
}
}
#Override
public Fragment getItem(int arg0) {
return fragmentsList.get(arg0);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return fragmentsList.size();
}
}
Set Layoutparams dynamically height of rootview of single grid in Adapter in getView() Method
(Device height / 5) - statusBarHieght
Some code : in getView() of Adapter
int grid_height = ((Helper.get_device_height(context)) / 5) - statusBarHeight;
GridView.LayoutParams layoutParams = (android.widget.AbsListView.LayoutParams) view.getLayoutParams();
layoutParams.height = grid_height;
view.setLayoutParams(layoutParams);
and,
gridview XML set columns=4
It will solve your problem.
Hope it will help you !
in your layout.xml by default <android:columnCount="auto_fit"> is set, you have to change it to as 4 by dong this <android:columnCount="4"> and to set rows similarly also in java you can do this like following setColumnCount(4) and setRowCount(5)

Hide items in GridView if two items have same images using Android

i am developing a project using GridView where i need to hide items if a user click such two items having same images then both item should be hide.
First time when project will load it will have one Question Marks image on all item.
when user click item the background image will show then if he click another item having the same picture then both item should be hide if not, it again show the Question Marks image.
How this is possible?
here is my MainActivity.java
public class MainActivity extends Activity {
Context ctx;
int imagesArray[];
GridViewContent adapter;
List<Integer> pictures;
boolean flage=false;
int img1=-1,img2=-1;
public int OriginalArray[] = { R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3 };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
shuffleArray();
adapter= new GridViewContent(this);
final GridView grid = (GridView) findViewById(R.id.gv_memory);
grid.setAdapter(new GridViewContent(this));
}
private void shuffleArray() {
// TODO Auto-generated method stub
pictures= new ArrayList<Integer>();
for (int index = 0; index < OriginalArray.length; index++)
{
pictures.add(OriginalArray[index]);
}
Collections.shuffle(pictures);
}
public class GridViewContent extends BaseAdapter {
private Context context;
//abstract change();
public int pictureArray[]={
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
R.drawable.question,
};
public GridViewContent(Context c){
context=c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return (pictureArray.length);
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return pictureArray[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
convertView=LayoutInflater.from(context).inflate(R.layout.main, null);
final ImageView myimage=new ImageView(context);
myimage.setImageResource(pictureArray[position]);
//myimage.setImageResource(pictures.get(pictureArray[position]));
myimage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
myimage.setLayoutParams(new GridView.LayoutParams(70, 70));
myimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// int post1,post2;
myimage.setImageResource(pictures.get(position));
if(flage==false)
{
img1=pictures.get(position);
flage=true;
}else if(flage==true){
//post2=position;
img2=pictures.get(position);
checkResult();
//notifyDataSetChanged();
flage=false;
}
//else if(f)
}
});
return myimage;
}
}
public void checkResult() {
if(img1==img2)
{
//pictures.remove(post2);
adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "Congratualatin !!!!", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(MainActivity.this, "Sorry!!!!", Toast.LENGTH_LONG).show();
final GridView grid = (GridView) findViewById(R.id.gv_memory);
grid.setAdapter(new GridViewContent(this));
}
}
}
You could try and remember the index of a GridView item you clicked. When a second click occurs, check the remembered index. If it is populated (meaning the user already clicked on an arbitrary image once), extract both drawables from the adapter and check if they are equal. If they are, remove them from the adapter and update it. Do not forget to reset the remembered index.
In code, this might look something like this:
int firstClickIndex = -1;
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView <? > parent, View view, int position, long id) {
if (-1 == firstClickIndex) {
firstClickIndex = position;
} else {
final int fstDrawable = adapter.get(firstClickIndex);
final int sndDrawable = adapter.get(position);
if (fstDrawable == sndDrawable) {
// Remove stuff, then reset firstClickIndex.
} else {
// Reset firstClickIndex.
}
}
}
});

Custom ListView is not updated when items are inserted

I have a custom listview with custom adapter extending BaseAdapter if i add items to this list view in OnCreate method they show up in list, but if i add them from other methods like a packet listener method then items do not show up , on the screen below this listview there is a textbox if i select textbox to entertext using virtual keyboard immediately the listview gets populated with previousely inserted items which didnt show up. This activity is a chat window basically
I have tried calling notifyDataSetChanged, invalidate on Layout or on listview but nothing helped.
What i think is i need to have a way to refresh activity , as same thing must be happening when the virtual keyboard pops up .
Help will be highly appreciated
Thanks
Code:
package com.arounds;
public class ChatActivity extends Activity implements OnClickListener,PacketListener{
private ListView chatView;
private ChatListViewCustomAdapter adapter;
private String user;
private XMPPConnection connection;
private Conversation conv;
private ChatActivity selfRef = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_win);
AroundApplication app = (AroundApplication) this.getApplicationContext();
connection = app.getConnection();
chatView = (ListView) findViewById(R.id.conversationList);
adapter = new ChatListViewCustomAdapter(this);
chatView.setAdapter(adapter);
// set send btn listener
ImageButton send = (ImageButton)findViewById(R.id.imgBtnSend);
send.setOnClickListener(this);
ImageButton smiley = (ImageButton)findViewById(R.id.imgBtnSmiley);
smiley.setOnClickListener(this);
// get the parameter passed by previouse activity
Bundle b = this.getIntent().getExtras();
String temp = b.getString("user");
user = temp;
TextView v = (TextView)this.findViewById(R.id.txtViewTitle_chat);
v.setText(temp);
v = (TextView)this.findViewById(R.id.txtViewDescription_chat);
temp = b.getString("status");
v.setText(temp);
//chatView.setOnItemClickListener(this);
HashMap convs = app.getConversations();
if(convs.containsKey(user) == true)
conv = (Conversation) convs.get(user);
else {
conv = new Conversation();
convs.put(user,conv);
}
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(this,filter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.imgBtnSend)
{
EditText msg = (EditText)this.findViewById(R.id.editChat);
String s = msg.getText().toString();
Message message = new Message(user, Message.Type.chat);
message.setBody(s);
connection.sendPacket(message);
ArrayList<ChatMessage> m = conv.messages;
String currentDate = DateFormat.getDateInstance().format(new Date());
m.add(new ChatMessage(s,currentDate));
adapter.addItem("I said",s,currentDate,Constants.SEND_LIST_TYPE);
//adapter.notifyDataSetChanged();
}
else
{
//View view = this.findViewById(R.id.linerLayoutChat);
chatView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void processPacket(Packet packet) {
// TODO Auto-generated method stub
System.out.println("in");
Message message = (Message) packet;
if (message.getBody() != null) {
System.out.println("in1");
String fromName = StringUtils.parseBareAddress(message.getFrom());
ArrayList<ChatMessage> m = conv.messages;
String currentDate = DateFormat.getDateInstance().format(new Date());
m.add(new ChatMessage(message.getBody(),currentDate));
adapter.addItem(fromName+" said",message.getBody(),currentDate,Constants.REC_LIST_TYPE);
//chatView.postInvalidate();
}
}
}
Adapter class:
public class ChatListViewCustomAdapter extends BaseAdapter
{
public ArrayList<ChatListItem> items;
public Activity context;
public LayoutInflater inflater;
public Boolean temp=false;
public ChatListViewCustomAdapter(Activity context) {
super();
this.context = context;
this.items = new ArrayList<ChatListItem>();
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
TextView txtViewTitle;
TextView txtViewDescription;
TextView txtViewDate;
}
public void addItem(String title,String desc,String d,int type)
{
ChatListItem item = new ChatListItem(title,desc,d,type);
items.add(item);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ChatListItem item = items.get(position);
ViewHolder holder;
System.out.println("Title:"+item.title+" type:"+item.type);
if(convertView==null)
{
holder = new ViewHolder();
int type = this.getItemViewType(position);
if(type == 0)
{
convertView = inflater.inflate(R.layout.list_item_even, null);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitleEven);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.txtViewDescriptionEven);
holder.txtViewDate = (TextView) convertView.findViewById(R.id.txtViewDateEven);
}
else
{
convertView = inflater.inflate(R.layout.list_item_odd, null);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitleOdd);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.txtViewDescriptionOdd);
holder.txtViewDate = (TextView) convertView.findViewById(R.id.txtViewDateOdd);
}
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
holder.txtViewTitle.setText(item.title);
holder.txtViewDescription.setText(item.desc);
holder.txtViewDate.setText(item.date);
return convertView;
}
#Override
public int getItemViewType(int position) {
ChatListItem item = items.get(position);
return item.type;
}
#Override
public int getViewTypeCount() {
return 2;
}
}
Handle all the updates within your Adapter and ensure you invoke notifyDataSetChanged() after you update it (within your Adapter)?
In cases where notifyDataSetChanged() does not work, re-set the adapter on the ListView by calling ListView.setAdapter() with the same Adapter again. This should refresh the view.
the only thing I can see not right are these methods:
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
These methods should return proper values.
items.get(position) and position respectively.

Adding a new row on button click to a list view

I want to add a new row on clicking add button in a list view in android.
Can someone help me out?
Here is the code I have so far:
public class prsnlhstry<EventArgs> extends Activity implements OnItemClickListener {
public static ArrayList<String> arr_sort_textview1= null;
public static ArrayList<String> arr_sort_textview2=null;
public static ArrayList<String> arr_sort_textview3=null;
public Resources ApptResources= null;
private ContextWrapper mycontext;
tododata todo;
int clickcounter = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView lv= (ListView)findViewById(R.id.listview);
todo = new tododata(this);
List<listObject> List = new ArrayList<listObject>();
for(int i = 0; i <= 5; i++){
listObject lo = new listObject();
lo.grade = Integer.toString(i);
lo.reason = Integer.toString(i);
lo.school = Integer.toString(i);
List.add(lo);
}
CustomAdapter ca = new CustomAdapter(this);
lv = (ListView)findViewById(R.id.listview);
lv.setAdapter(ca);
lv.setOnItemClickListener(this);
ca.notifyDataSetChanged();
Button button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Toast.makeText(prsnlhstry.this, "Row Added Successfully", Toast.LENGTH_SHORT).show();
}
});
}
private class listObject {
String grade;
String school;
String reason;
}
public class CustomAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public CustomAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return todo.getLength();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
String temp = null;
// to reinflate it. We only inflate a new View when the convertView supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.grid_item, null);
// Creates a ViewHolder and store references to the views
// we want to bind data to.
holder = new ViewHolder();
holder.textview1 = (TextView) convertView.findViewById(R.id.item2);
holder.textview2 = (TextView) convertView.findViewById(R.id.item3);
holder.textview3 = (TextView) convertView.findViewById(R.id.item4);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textview1.setText(todo.getgrade(position));
holder.textview2.setText(todo.getschool(position));
holder.textview3.setText(todo.getreason(position));
return convertView;
}
}
static class ViewHolder {
TextView textview1;
TextView textview2;
TextView textview3;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
}
Just add the item to your list and refresh the adapter, nothing special.
You need to increment your "tododata" data structure on button click and then call to notifyDataSetChanged() method:
Button button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
todo.addNewRow();
ca.notifyDataSetChanged();
Toast.makeText(prsnlhstry.this, "Row Added Successfully", Toast.LENGTH_SHORT).show();
}
});
To compile the above code you will need to define "ca" variable as the final one, or make it class member.
I hope it helps.

Categories

Resources