TachesFragment.java
package com.example.johnwalls.projet;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
*/
public class TachesFragment extends Fragment {
private DB base;
private ListView sp ;
public TachesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_taches, container, false);
TextView text2 = view.findViewById(R.id.ta);//Find textview Id
TextView t1 = view.findViewById(R.id.t1);
TextView de1= view.findViewById(R.id.de1);
TextView em1= view.findViewById(R.id.em1);
String getArgument = getArguments().getString("main");
text2.setText(getArgument);
base=new DB(getActivity());
text2.setText(getArgument);
sp=(ListView) view.findViewById(R.id.ta);
ArrayList<Mission> empList=base.MissionList();
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,android.R.id.text1,empList);
sp.setAdapter(adapter);
return view;
}
}
fragment_taches
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
android:gravity="bottom"
android:orientation="vertical"
android:background="#drawable/ee63"
tools:context="com.example.johnwalls.projet.TachesFragment">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="100dp"
android:layout_marginBottom="15dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:id="#+id/ta"
/>
</android.support.v4.widget.DrawerLayout>
simple_list_item_1
<?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"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/t1"
android:textSize="20dp"
android:text=""
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/de1"
android:textSize="10dp"
android:text=""
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/em1"
android:textSize="10dp"
android:text=""
/>
</LinearLayout>
What are you trying to achieve what are you expecting to get out What did you get out (include error messages) What else have you tried? What do you think is causing it? Why do you need to make a new question for it? Why is your problem different to other, similar questions on here?
I believe that your issue is that you are telling the ArrayAdapter to expect an Array of String objects (ArrayAdapter<String>) but you are providing an array of Mission objects as per ArrayList<Mission> emplist=base.MissionList();.
i.e. you have
ArrayList<Mission> empList=base.MissionList();
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,android.R.id.text1,empList);
Instead I think you need :-
ArrayList<Mission> empList=base.MissionList(); //<<<< NOT CHANGED
ArrayAdapter<Mission> adapter=new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1,android.R.id.text1,empList);
Note the mission's toString method will be used to provide the data for the list, if you haven't overridden the toString method the result may be not what you expect. e.g.
com.example.johnwalls.projet.Mission#546789
Note it will be like the above certainly the numeric will be different.
Why it comes out like this is explained by :-
How do I print my Java object without getting “SomeType#2f92e0f4”?
In which case you should create a toString method to return an appropriate string.
As an example (not to be used as it is) here's a TaskData class with an overridden toString method :-
public class TaskData {
private long id;
private String type, name, owner, expiration;
public TaskData(long id, String type, String name, String owner, String expiration) {
this.id = id;
this.type = type;
this.name = name;
this.owner = owner;
this.expiration = expiration;
}
//<<<< Oreridden toString Method Starts here >>>>
public String toString() {
return " Typ: " + type + " Name: " + name + " Owner: " + owner + " Until: " + expiration;
}
//<<<< End >>>>
public long getId(){return id;}
public String getType() {return this.type;}
public String getName() {return this.name;}
public String getOwner() {return this.owner;}
public String getExpiration() {return this.expiration;}
}
The overridden toString method returns a string that combines the type name and owner and expiration. e.g.
Type: Test Name: Fred Owner: Bert Until: 31/12/2018
LoveData beanClass = arrayList.get(position);
Log.e("DisplayPhotolistAdapter","beanClass:"+beanClass);
tv_date.setText(beanClass.getLOVE_DATE());
tv_total_percent.setText(beanClass.getPrcentage()+"%");
tv_hername.setText(beanClass.getHername());
tv_hisname.setText(beanClass.getHisname());
tv_Actvity.setText(beanClass.getActvity()+":");
Related
I am working on Recyclerview in which checkboxes are there. I want to know how to use the below to achieve MVVM data binding in android.
#BindingAdapter({"app:setCheckBoxListener"})
public static void setCheckBoxListener(AppCompatCheckBox checkBox, final OnCheckListener onCheckListener) {
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
onCheckListener.onCheckChanged(isChecked, (String) buttonView.getText());
}
});
}
this is the ViewModel class which I am using for the logical part. I want when I check on the checkboxes the data will be saved in the ArrayList.
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;
import com.codestrela.product.adapters.SelectContactAdapter;
import com.codestrela.product.data.Contact;
import com.codestrela.product.fragments.ListDialogFragment;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class ListDialogViewModel {
private static final String TAG = "ListDialogViewModel";
public static final String CONTACT_LIST = "contact_list";
public RowSelectContactViewModel viewModel;
ListDialogFragment listDialogFragment;
ArrayList<RowSelectContactViewModel> selectViewmodel;
ArrayList<Contact> contacts;
public SelectContactAdapter adapter;
public ListDialogViewModel(ListDialogFragment listDialogFragment) {
this.listDialogFragment = listDialogFragment;
adapter = new SelectContactAdapter(new ArrayList<RowSelectContactViewModel>());
selectViewmodel = new ArrayList<>();
onContact();
}
public void onContact() {
contacts = new ArrayList<>();
SharedPreferences sharedPreferences = listDialogFragment.getActivity().getSharedPreferences("shared preference", Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString(CONTACT_LIST, null);
Toast.makeText(listDialogFragment.getActivity(), "" + json, Toast.LENGTH_SHORT).show();
Type type = new TypeToken<ArrayList<Contact>>() {
}.getType();
contacts = gson.fromJson(json, type);
Log.e(TAG, "array size: " + contacts.toString());
for (int i = 0; i < contacts.size(); i++) {
viewModel = new RowSelectContactViewModel();
String name = contacts.get(i).getName();
viewModel.contactName.set(name);
viewModel.contactNumber.set(contacts.get(i).getNumber());
Toast.makeText(listDialogFragment.getActivity(), " check "+viewModel.contactCheckbox.get(), Toast.LENGTH_SHORT).show();
selectViewmodel.add(viewModel);
}
adapter.addAll(selectViewmodel);
}
}
this is the row layout that I am using in the recycler view in the application. This checkbox is there which I am using in the application. Please help me I am very new at this.
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="vm"
type="com.codestrela.product.viewmodels.RowSelectContactViewModel" />
</data>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="8dp"
android:layout_margin="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:checked="#{vm.contactCheckbox.get()}"
android:layout_alignParentLeft="true"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="8dp"
android:layout_gravity="center">
<TextView
android:id="#+id/contact_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{vm.contactName}"
android:layout_gravity="center"
android:textSize="18dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{vm.contactNumber}"
android:textSize="14dp"
android:layout_marginTop="4dp"
android:layout_gravity="center"
/>
</LinearLayout></LinearLayout></androidx.cardview.widget.CardView>
</layout>
You don't need to make BindingAdapter ,, it's too easy
according to docs of two-way data binding ,, you will just add this to your xml
it provides setting initial state of checkbox and onCheckedChange
<CheckBox
android:id="#+id/rememberMeCheckBox"
android:checked="#={viewmodel.rememberMe}"
/>
you have to save it to boolean variable
boolean contactCheckbox;
so in your xml it will be
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:checked="#={vm.contactCheckbox}"
android:layout_alignParentLeft="true"/>
just add equal sign = .. it makes the two-way binding works
I am trying to access TextView and ImageView but id's are not in the list
I'm following this tutorial https://www.youtube.com/watch?v=yK8RtB6aXC4 on you tube
here is my Xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:padding="10dp"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="#+id/home_icon"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="#drawable/home" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:gravity="center_vertical"
android:orientation="vertical"
>
<TextView
android:id="#+id/title1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Sub Title"
android:textColor="#000"
android:textSize="16sp" />
<TextView
android:id="#+id/title2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="subtitle"
android:textColor="#000"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout>
Class code
package com.demo.adapter;
import java.util.List;
import com.demo.modles.Navigation;
import com.example.madrobo.R;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class NavigationListAdapter extends ArrayAdapter<Navigation>{
Context context;
int resLayout;
List<Navigation> navigationlist;
public NavigationListAdapter(Context context, int resLayout,
List<Navigation> navigationlist) {
super(context, resLayout, navigationlist);
this.context=context;
this.resLayout=resLayout;
this.navigationlist=navigationlist;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v=View.inflate(context, resLayout, null);
TextView textview1=(TextView)v.findViewById(R.id);
return v;
}
}
NAvigation Class
package com.demo.modles;
public class Navigation {
private String title;
private String subTitle;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public int getResIcon() {
return resIcon;
}
public void setResIcon(int resIcon) {
this.resIcon = resIcon;
}
public Navigation(String title, String subTitle, int resIcon) {
super();
this.title = title;
this.subTitle = subTitle;
this.resIcon = resIcon;
}
private int resIcon;
}
here is my packages picture Please see
The R class could cause an error, but when it causes an error it shows the error as all of the "R." statements are red in colour.
You can check 2 more things.
1) Android Power Save Mode
Have a look at the screenshot below. There it specifies Android Studio Power Save Mode. If it is checked you face the same problem as the ids are not accessible as it turns off the intellisense for Android Studio for enhancing user performance.
To access the Android Power Save Mode you need to Left Click on the bottom right corner small android icon as shown in the image below.
Please uncheck (Power Save Mode) and keep the Import popup checked as in image below.
2) Shortcut to Access ids
If you are not able to access the ids instantly you could press "Ctrl + Space" at once so that the list appears if it is not appearing due to any other reason.
You are importing a R class from an other package than your java is in. You don't have to import a R class, because it is automaticly generated.
I am working on Android project, which will allow users to find nearest petrol pump's name, address, and most importantly their prices. I have a ListView, which I want to populate through Firebase list adapter because I am using Firebase for my project. Now after writing code I am getting nothing from Firebase -- it's just blank screen on Android phone (no error showing in Android Studio).
After writing setContentView(lview); in the end of the onCreate() method , it is giving me error now and the activity crashes. Finally I got the error from firebase : com.firebase.client.FirebaseException: Failed to bounce to type
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import com.firebase.client.Firebase;
import com.firebase.ui.FirebaseListAdapter;
public class testbezinpriser extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_testbezinpriser);
ListView lview = new ListView(this);
Firebase.setAndroidContext(this);
Firebase ref = new Firebase("https://xxxxx.firebaseio.com");
FirebaseListAdapter<Benzin> Adapter = new FirebaseListAdapter<Benzin>(this, Benzin.class, R.layout.listepriser, ref) {
#Override
protected void populateView(View v, Benzin s, int i) {
((TextView)v.findViewById(R.id.navnView)).setText(s.getName());
((TextView)v.findViewById(R.id.addressView)).setText(s.getAddress());
((TextView)v.findViewById(R.id.prisView)).setText(s.getPrice()));
}
};
lview.setAdapter(Adapter);
setContentView(lview);
}
}
And Benzin class
public class Benzin {
String Address;
String Name ;
String Price;
public Benzin(){
}
public Benzin (String Name , String Address , String Price){
this.Name = Name;
this.Address = Address;
this.Price = Price;
}
public String getAddress(){
return Address;
}
public String getName(){
return Name;
}
public String getPrice(){
return Price;
}
}
XML Layout for listepriser
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="80dp"
android:layout_height="50dp"
android:id="#+id/logoView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="20dp"
android:src="#drawable/shell"
android:contentDescription="tankstation_billed" />
<TextView
android:layout_width="70dp"
android:layout_height="25dp"
android:id="#+id/navnView"
android:layout_alignTop="#+id/logoView"
android:layout_toEndOf="#+id/logoView"
android:layout_marginStart="10dp"
android:textStyle="bold|italic"
android:textSize="15sp"
android:textColor="#000000"
android:text="SHELL"
android:layout_marginTop="5dp"
android:textIsSelectable="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Måløvhovedgade 38 , Måløv"
android:id="#+id/addressView"
android:layout_alignBottom="#+id/logoView"
android:layout_alignStart="#+id/navnView"
android:layout_marginBottom="3dp"
android:textSize="12sp"
android:textColor="#000000" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10.99"
android:id="#+id/prisView"
android:layout_alignTop="#+id/navnView"
android:layout_alignParentEnd="true"
android:layout_marginRight="10dp"
android:textColor="#000000"
android:typeface="serif" />
Database view
If you look at the full stack trace of the Failed to bounce to type exception, it will tell you what is wrong.
But in this case it seems likely that your problem is caused by the fact that the property names in your JSON start with an uppercase letter. This is likely to work:
public class Benzin {
public String Address;
public String Name ;
public String Price;
}
Try changing your Firebase reference. It doesn't look like it pointing to the right location. Based on the link you posted to your data structure it looks like you are trying to list objects stored in your /detail location. If that true try using a ref like this:
Firebase ref = new Firebase("https://xxxxx.firebaseio.com/detail");
Just a guess here.
Your getPrice() method returns a string. I think you need a getter that has the same return type as the property you are getting. You can keep the String one, but it must be in addition to a method with the signature...
public Double getPrice();
The reason I think this is because firebase is complaining that it is unable to figure what property of your object a certain field matches to. This could be because you are supposed to provide getters for each property, and Firebase may not like that price is a Double but your getter turns it into a string. Here is a link to a detailed post about how this all works by Frank. Why do I get "Failed to bounce to type" when I turn JSON from Firebase into Java objects?
I haven't used Firebase before, but shouldn't the ListView be added to the layout (or be retrieved from it)?
Something like
setContentView(R.layout.activity_testbezinpriser);
ListView lview = (ListView)findViewById(R.id.station_list);
In the activity_testbezinpriser.xml, there should be a ListView, like
<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:id="#+id/station_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Actually, I was trying to implement a shopping cart using Android Studio. There is a custom list view in the main page included an "Add to Cart" button. So, whenever I click on the button the item must be added in the cart. But, I have no idea. Please guys, help me out. I'm a newbie.
Here is the Product Adapter
package com.example.raswap.octomatic;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by aurora on 22/03/16.
*/
public class Pro_Adapter extends ArrayAdapter {
List list = new ArrayList();
public Pro_Adapter(Context context, int resource) {
super(context, resource);
}
static class DataHandler{
ImageView img;
TextView p_name;
TextView b_name;
TextView price;
Button b_atc;
}
#Override
public void add(Object object) {
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
DataHandler handler;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.e_layout, parent, false);
handler = new DataHandler();
handler.img = (ImageView)row.findViewById(R.id.pro_image);
handler.p_name = (TextView)row.findViewById(R.id.pro_name);
handler.b_name = (TextView)row.findViewById(R.id.brand);
handler.price = (TextView)row.findViewById(R.id.pricing);
handler.b_atc = (Button)row.findViewById(R.id.atc);
row.setTag(handler);
}else{
handler = (DataHandler)row.getTag();
}
Product_data_provider dataProvider;
dataProvider = (Product_data_provider)this.getItem(position);
handler.img.setImageResource(dataProvider.getPro_img_resource());
handler.p_name.setText(dataProvider.getPro_name());
handler.b_name.setText(dataProvider.getBr_name());
handler.price.setText(dataProvider.getPricing());
return row;
}
}
Here is the Main Activity class:
package com.example.raswap.octomatic;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class E_shop extends Activity {
ListView listView;
int[] emage = {R.drawable.gb32, R.drawable.tb1, R.drawable.dvd};
String[] pro_name;
String[] br_name;
String[] price;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_e_shop);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_titlebar);
View z = findViewById(R.id.oct_logo);
z.setClickable(true);
z.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(E_shop.this, MainActivity.class));
}
});
View x = findViewById(R.id.for_user_info);
x.setClickable(true);
x.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(E_shop.this, UserInformation.class));
}
});
Pro_Adapter adapter = new Pro_Adapter(getApplicationContext(),R.layout.e_layout);
ListView listView = (ListView)findViewById(R.id.e_list);
listView.setAdapter(adapter);
pro_name = getResources().getStringArray(R.array.nameOfProduct);
br_name = getResources().getStringArray(R.array.branding);
price = getResources().getStringArray(R.array.pricing);
int i = 0;
for(String pro: pro_name){
Product_data_provider dataProvider = new Product_data_provider(emage[i],pro, br_name[i], price[i]);
adapter.add(dataProvider);
i++;
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:
Intent newActivity = new Intent(E_shop.this, Product_Desc.class);
newActivity.putExtra("pro_emage",R.drawable.gb32);
newActivity.putExtra("title","Kingston 32Gigs Pen Drive");
newActivity.putExtra("desc", "Store a huge collection of data in a generous 32GB space of this Kingston pen drive and carry it along. It has a sleek design with a smooth finish, and a pretty-looking charm bearing the Kingston logo dangles from this pen drive. Featured in a size of 3 x 1.2 x 0.5 cm, this Kingston 32GB pen drive weighs only 5g. You can easily tuck it away in the pocket of your laptop bag, purse or your shirt pocket with its compact and light weight.");
startActivity(newActivity);
break;
case 1:
Intent Activity1 = new Intent(E_shop.this, Product_Desc.class);
Activity1.putExtra("pro_emage",R.drawable.tb1);
Activity1.putExtra("title","Samsung 1TB Portable Hard Disk");
Activity1.putExtra("desc", "From college to school students, all deal with transferring files, software and applications from various systems that are large in size. With the advancements in media technology on the rise, we require a large amount of space to store our data. Even most of the growing companies require a secure means of storing data for analyses. All of this embarks on the need for a reliable hard disk. The top quality brand of Samsung brings you this sleek and portable hard drive ideally designed for continuous usage. Now you can store 2TB of diverse data easily. This, sleek hard disk comes with 36 months warranty. The body of this drive has a smart construction. The Samsung external hard disk comes in a sturdy design.");
startActivity(Activity1);
break;
case 2:
Intent Activity2 = new Intent(E_shop.this, Product_Desc.class);
Activity2.putExtra("pro_emage", R.drawable.dvd);
Activity2.putExtra("title", "A pack of 50 DVD's");
Activity2.putExtra("desc", "Create and store digital video, audio and multimedia files, Stores up to 4.7GB or more than 2 hours of MPEG2 video, Has 7 times the storage capacity of a CDR, Sony branded 16X DVD-R in a 100 pack Spindle, AccuCORE Technology");
startActivity(Activity2);
break;
}
}
#SuppressWarnings("unused")
public void onClick(View v){
}
});
}
}
Here is the Product Data Provider Class:
package com.example.raswap.octomatic;
/**
* Created by aurora on 22/03/16.
*/
public class Product_data_provider {
private int pro_img_resource;
private String pro_name;
private String br_name;
private String pricing;
public int getPro_img_resource() {
return pro_img_resource;
}
public Product_data_provider(int pro_img_resource, String pro_name, String br_name, String pricing){
this.setPro_img_resource(pro_img_resource);
this.setPro_name(pro_name);
this.setBr_name(br_name);
this.setPricing(pricing);
}
public void setPro_img_resource(int pro_img_resource) {
this.pro_img_resource = pro_img_resource;
}
public String getPro_name() {
return pro_name;
}
public void setPro_name(String pro_name) {
this.pro_name = pro_name;
}
public String getBr_name() {
return br_name;
}
public void setBr_name(String br_name) {
this.br_name = br_name;
}
public String getPricing() {
return pricing;
}
public void setPricing(String pricing) {
this.pricing = pricing;
}
}
Now, Custom ListView XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/oneL"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/pro_image"
android:src="#drawable/gb32"
android:layout_width="160dp"
android:layout_height="match_parent" />
<LinearLayout
android:background="#afeeee"
android:orientation="vertical"
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/textAppearanceLarge"
android:text="Product Name"
android:id="#+id/pro_name"
android:textColor="#000"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Branding"
android:id="#+id/brand"
android:textColor="#000"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Price"
android:textColor="#000"
android:id="#+id/pricing"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to Cart"
android:id="#+id/atc" />
</LinearLayout>
</LinearLayout>
<View
android:layout_below="#+id/oneL"
android:layout_width="match_parent"
android:layout_height="5dp"
android:background="#000"/>
</RelativeLayout>
</RelativeLayout>
and finally the main layout XML file:
<?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.raswap.octomatic.E_shop">
<ListView
android:id="#+id/e_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
Add your button's OnClick event in the Pro_Adapter's getView() methond as you do normally in your activities' onCreate() method.
Implement OnClickListener in your adapter class and get the Button click first and do the other task when you get the event. If you need the call back to your main activity class implement your own listener.follow the link enter link description here
Add the onClickListener to your Button in getView() of your ListAdapter.
If you want handle event click button in row, i'm think you should answer set button onclick event for every row of listview
you can try this.
Change in custom Listview xml file.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to Cart"
android:onClick="AddCart"
android:id="#+id/atc" />
In MainActivity
public void AddCart(View v)
{
LinearLayout vwParentRow = (LinearLayout)v.getParent();
TextView child = (TextView)vwParentRow.getChildAt(0);
child.setText("I've been clicked!");
vwParentRow.refreshDrawableState();
}
I am trying to create a simple program which displays a "shopping
cart" list of items, along with a few buttons below it to manage the
cart.
The biggest problem is that items are getting duplicate entries in the
list view. That is, for every item I want to enter I see it appear
two times in the list view. What's the problem? Also, the scrollable
area of my cart is not big enough. How do I set it so that it is
bigger but I can still see my buttons? Perhaps I should put the
buttons above the cart?
Here is my shopping cart's layout XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shopping Cart" />
<ScrollView android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="110px">
<ListView
android:id="#+id/BookList"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
</ScrollView>
<Button android:text="Add Another Book"
android:id="#+id/AddAnother"
android:layout_width="250px"
android:textSize="18px"
android:layout_height="55px">
</Button>
<Button android:text="Checkout"
android:id="#+id/Checkout"
android:layout_width="250px"
android:textSize="18px"
android:layout_height="55px">
</Button>
</LinearLayout>
Here is the layout for individual row items:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="8dip">
<LinearLayout
android:orientation="vertical"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="fill_parent">
<TextView
android:id="#+id/BookTitle"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:singleLine="true"
android:gravity="center_vertical"
/>
<TextView
android:id="#+id/BookPrice"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:singleLine="true"
android:ellipsize="marquee"
/>
</LinearLayout>
<Button
android:id="#+id/buttonLine"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:text="Delete"
/>
</LinearLayout>
here is the java code for the shopping cart activity:
package com.sellbackyourbook.sellback;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.Activity;
//import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class cart extends Activity
{
private ListView m_bookListView;
private BookAdapter m_adapter;
//private static String[] data = new String[] = { ""
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState)
{
ShoppingCartSingleton shoppingCart = ShoppingCartSingleton.getInstance();
super.onCreate(savedInstanceState);
setContentView(R.layout.shoppingcart);
this.m_adapter = new BookAdapter(this, R.layout.cartitem,
shoppingCart.m_books);
m_bookListView = (ListView) findViewById(R.id.BookList);
m_bookListView.setAdapter(this.m_adapter);
//setListAdapter(this.m_adapter);
if (shoppingCart.m_books != null && shoppingCart.m_books.size() > 0)
{
//m_adapter.notifyDataSetChanged();
try
{
//m_adapter.clear();
//for(int i=0;i<1;i++)
Log.i("ARRAY", "m_books.size() before loop" + shoppingCart.m_books.size());
int size = shoppingCart.m_books.size();
for(int i=0;i<size;i++)
{
Log.i("ARRAY", "size in loop" + size);
Log.i("ARRAY", "adding item to adapter" + i);
m_adapter.add(shoppingCart.m_books.get(i));
}
} catch (RuntimeException e) {
e.printStackTrace();
}
//m_adapter.notifyDataSetChanged();
}
Button buttonAddAnother = (Button) findViewById(R.id.AddAnother);
buttonAddAnother.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
// TODO: only show this button if the shopping cart is not empty
Button buttonCheckout = (Button) findViewById(R.id.Checkout);
buttonCheckout.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
// TODO: open sellbackyourbook website using book ISBNs
ShoppingCartSingleton shoppingCart = ShoppingCartSingleton.getInstance();
String isbnList = "";
String checkoutURL = "http://www.sellbackyourbook.com/androidcart.php?isbn=";
for (Iterator<Book> i = shoppingCart.m_books.iterator(); i.hasNext(); )
{
Book currentBook = (Book) i.next();
isbnList = isbnList + currentBook.getBookISBN() + ",";
}
checkoutURL = checkoutURL + isbnList;
Log.i("CHECKOUT URL", "checkout URL to submit: " + checkoutURL);
Intent myIntent = new Intent(Intent.ACTION_VIEW);
myIntent.setData(Uri.parse(checkoutURL));
startActivity(myIntent);
}
});
}
private class BookAdapter extends ArrayAdapter<Book> {
private ArrayList<Book> books;
public BookAdapter(Context _context, int _textViewResourceId, ArrayList<Book> _books)
{
super(_context, _textViewResourceId, _books);
this.books = _books;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
System.out.println("getView " + position + " " + convertView);
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.cartitem, null);
}
Book b = books.get(position);
if (b != null)
{
TextView bTitle = (TextView) v.findViewById(R.id.BookTitle);
TextView bPrice = (TextView) v.findViewById(R.id.BookPrice);
if (bTitle != null)
{
bTitle.setText(b.getBookTitle());
}
if (bPrice != null)
{
bPrice.setText(b.getBookPrice());
}
}
return v;
}
}
}
Here is the Java code for my shopping cart. Am I using the singleton correctly? I really just wanted a quick and dirty way to allow multiple activities access to the shopping cart, as a different activity actually grabs the books from the user and this activity displays them in the cart.
I had an issue iterating through the books in onCreate() as well. the size() function kept increasing in the loop for some reason, so I changed the code and added a "size" variable to avoid making the size() call in the loop itself. I'm not really sure what that was all about.
I'm doing exactly the same thing and my getView is not called at all.
here is the script I was inspired by maybe it would help :
http://mfarhan133.wordpress.com/2010/10/14/list-view-tutorial-for-android/
Yes you are right at the point of BookAdapter's constructor. But the getView() method of BookAdapter is wrong. Please have a look at http://www.youtube.com/watch?v=wDBM6wVEO70 (from Google) to get the right way on how to work with ListView.
Removing the loop where I had this fixed the problem:
m_adapter.add(shoppingCart.m_books.get(i));
It seems like the BookAdapter constructor already took care of populating it, so I was duplicating the items by using the add() method.