error when startActivity - java

happy new year to all of you.
I am having a problem with the method onItemClickListener, because when I tried to toast the position and id ,in my second activity, I get zeros.
here is the code, I rely on the position of the image in the array that is why I need to get the position/id accurately.
+
I am duplicating my array in both activities because I don't know how to access it from the second activity?
MainActivity.java
package swe.trial;
import android.content.Context;
import android.widget.ImageView;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.AdapterView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView items = (GridView) findViewById(R.id.itemsList);
items.setAdapter(new item_adapter(this));
items.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//if an item is clicked or selceted,then go to the activity itemDetails:
Intent i= new Intent (MainActivity.this, itemDetails.class);
i.putExtra("position", position);
i.putExtra("id", id);
startActivity(i);
}
});
}
}
class item_adapter extends BaseAdapter {
Integer[] picsId = {
R.drawable.pic1,
R.drawable.pic2,
R.drawable.pic3,
R.drawable.pic4,
R.drawable.pic5,
R.drawable.pic6,
R.drawable.pic7};
private Context context;
public item_adapter(Context context) {
this.context = context;
}
public Object getItem(int position) {
return null;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imgview= new ImageView(context);
imgview.setLayoutParams(new GridView.LayoutParams(250,250));
imgview.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgview.setPadding(20,20,20,20);
imgview.setImageResource(picsId[position]);
return imgview;
}
public long getItemId(int position) {
return position;
}
public int getCount (){
return picsId.length;
}
}
itemDetails.java
package swe.trial;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
import android.net.Uri;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by good on 1/01/17.
*/
public class itemDetails extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item);
ArrayList<item> items = new ArrayList<item>();
// items item1=
// Bundle d = getIntent().getExtras();
int id=0;getIntent().getIntExtra("id",id);
int position=0;
getIntent().getIntExtra("position", position);
Toast.makeText( this, "id= " +id + " . and posistion= "+ position, Toast.LENGTH_LONG).show();
Integer[] picsId = {
R.drawable.pic1,
R.drawable.pic2,
R.drawable.pic3,
R.drawable.pic4,
R.drawable.pic5,
R.drawable.pic6,
R.drawable.pic7
};
ImageView imgview = (ImageView) findViewById(R.id.item_image);
imgview.setImageResource(picsId[id+ 1]);
TextView txt= (TextView) findViewById(R.id.pricetxtview);
txt.setText("This is the description provided." + id);
//(id);
// item item1 = {"Red rose", "#/drawable/", 1, 1.25};
// items.add(item1);
// now i will search for the array that holds the given id. and i will retrieve its info and display it again
// in the new layout.
}
}

You misunderstand the way you should use intents.
The right form is like this :
int id =getIntent().getIntExtra("id",0);
int position = getIntent().getIntExtra("position", 0);
when you use getIntExtra , the second parameter is the default value. In case there is not such value with that tag in your intent, it will return that default value.
See Google docs for more info

You have to fetch value according the following way,
int id=0;
int position=0;
i=getIntent().getIntExtra("id",id);
position= getIntent().getIntExtra("position", position);
Toast.makeText( this, "id= " +id + " . and posistion= "+ position, Toast.LENGTH_LONG).show();

Related

Dynamically add checkboxes to a listview

I am trying to make an app that takes the number of sets, and number of reps for each set from the user, and adds rows ( for each set) and checkboxes (for each rep)
for the reps: i made a method that takes the number of reps from the SQLite server, and loops through the number of reps to make the checkboxes.
for the sets: i made list adapter to make each row.
how can i make the reps be contained inside the rows? thanks.
recyclerview adaptor:
'''
package com.example.workouttracker;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class WorkoutInterfacesAdapter extends RecyclerView.Adapter<WorkoutInterfacesAdapter.WorkoutInterfaceViewHolder> {
Context mContext;
private ArrayList<WorkoutInterfaceClass> sets;
private LinearLayout linearLayout;
public WorkoutInterfacesAdapter(Context mContext , ArrayList<WorkoutInterfaceClass> sets) {
this.sets = sets;
this.mContext = mContext;
}
#NonNull
#Override
public WorkoutInterfaceViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.workout_interface_item,parent,false);
return new WorkoutInterfacesAdapter.WorkoutInterfaceViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull WorkoutInterfacesAdapter.WorkoutInterfaceViewHolder holder, int position) {
holder.bind(sets.get(position));
//new code:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,"Set number: " + sets.get(position).numberOfSets + " ,Rep Number: "+sets.get(position).numberOfReps,Toast.LENGTH_LONG).show();
Intent intent = new Intent(mContext,WorkoutInterface.class);
intent.putExtra("workout_sets",sets.get(position).numberOfSets);
intent.putExtra("workout_reps",sets.get(position).numberOfReps);
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return sets.size();
}
static class WorkoutInterfaceViewHolder extends RecyclerView.ViewHolder{
TextView numberOfSets;
int numberOfReps;
CheckBox checkBox;
LinearLayout linearLayout;
public WorkoutInterfaceViewHolder(#NonNull View itemView) {
super(itemView);
numberOfSets =itemView.findViewById(R.id.edit_text_number_of_sets_item);
checkBox=itemView.findViewById(R.id.checkbox_number_of_reps_item);
linearLayout=itemView.findViewById(R.id.ll_checkbox_mother);
}
public void bind(WorkoutInterfaceClass sets) {
//
numberOfSets.setText("Set number:" + sets.numberOfSets); ;
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
numberOfReps=sets.numberOfReps;
for (int i = 1; i <= numberOfReps; i++) {
CheckBox checkBox = new CheckBox(linearLayout.getContext());
checkBox.setId(View.generateViewId());
checkBox.setText("Rep: "+checkBox.getId());
checkBox.setOnClickListener((View.OnClickListener) linearLayout.getContext());
System.out.println("Total Number Of Sets:"+numberOfReps + "And the index is : "+ i );
}
}
}}
'''
Try creating a custom layout that will contain all the necessary views and pass the layout in the onCreateView of you adapter class with a layout inflater.

Error:java.lang.NullPointerException (no error message) in CustomBaseAdapter

I am creating simple contacts app in android. MainActivity consist of listview displaying image and name. I am using a model for setting and getting data and ArrayList to pass the data to next activity. When I click on single listview item. It should display next activity displaying contact details.
MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
String[] name={
"Adam",
"John",
"Jasmine"
};
int[] image={
R.drawable.img1,
R.drawable.img2,
R.drawable.img3
};
String[] mobile_no={
"03349875429",
"03458294792",
"03318245801",
};
String[] email={
"adam123#yahoo.com",
"john123#gmail.com",
"jasmine456#hotmail.com"
};
String[] url={
"https://www.google.com.pk/",
"https://www.google.com.pk/",
"https://www.google.com.pk/"
};
ContactModel contact;
ArrayList<ContactModel> contact_list=new ArrayList<ContactModel>();
ListView ls;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ls=(ListView)findViewById(R.id.listView);
for(int i=0;i<name.length;i++){
contact=new ContactModel();
contact.setImage(image[i]);
contact.setName(name[i]);
contact.setMobile_no(mobile_no[i]);
contact.setEmail(email[i]);
contact.setUrl(url[i]);
contact_list.add(contact);
}
CustomBaseAdapter adapter=new CustomBaseAdapter(this,contact_list);
ls.setAdapter(adapter);
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ContactModel contacts=contact_list.get(i);
Intent intent=new Intent(getApplicationContext(),ContactDetails.class);
intent.putExtra("contacts",contacts);
startActivity(intent);
}
});
}
}
CustomeBaseAdapter.java
import android.app.Activity;
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 java.util.ArrayList;
public class CustomBaseAdapter extends BaseAdapter {
Activity activity;
ArrayList<ContactModel> contact;
LayoutInflater inflator;
TextView name;
ImageView image;
public CustomBaseAdapter(Activity activity, ArrayList<ContactModel> contact) {
this.activity=activity;
this.contact=contact;
inflator=activity.getLayoutInflater();
}
#Override
public int getCount() {
return contact.size();
}
#Override
public Object getItem(int i) {
return contact.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v=view;
if(view==null){
v=inflator.inflate(R.layout.contact_list_,null);
}
name=(TextView)v.findViewById(R.id.name_textView);
image=(ImageView)v.findViewById(R.id.imageView);
ContactModel c=(ContactModel) getItem(i);
name.setText(c.getName());
image.setImageResource(c.getImage());
return v;
}
}
ContactDetails.java
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class ContactDetails extends AppCompatActivity {
ImageView imageView;
TextView nameView;
TextView mobileView;
TextView emailtextview;
TextView urlView;
ImageView callButton;
ImageView messageButton;
ImageView emailButton;
ImageView websiteButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_details);
Intent intent=getIntent();
final ContactModel contacts=(ContactModel)intent.getSerializableExtra("contacts");
imageView=(ImageView)findViewById(R.id.imageView);
nameView=(TextView)findViewById(R.id.name_view);
mobileView=(TextView)findViewById(R.id.number_view);
emailtextview=(TextView)findViewById(R.id.email_textview);
urlView=(TextView)findViewById(R.id.url_textview);
//Buttons
callButton=(ImageView)findViewById(R.id.callButton);
messageButton=(ImageView)findViewById(R.id.message_view);
emailButton=(ImageView)findViewById(R.id.email_imageview);
websiteButton=(ImageView)findViewById(R.id.url_imageview);
imageView.setImageResource(contacts.getImage());
nameView.setText(contacts.getName());
mobileView.setText(contacts.getMobile_no());
emailtextview.setText(contacts.getEmail());
urlView.setText(contacts.getUrl());
}
}
ContactModel simply consist of setter and getter methods. Call Button etc functionality is not implemented yet. No error is displayed but when I run the project it displays 1 error: Error:java.lang.NullPointerException (no error message)
logcat:
09-25 05:09:54.006 1745-1775/system_process E/BluetoothAdapter: Bluetooth binder is null
09-25 05:11:00.001 1745-1773/system_process I/ProcessStatsService: Prepared write state in 0ms
09-25 05:16:38.974 98-98/? D/Genyd: Received Set Clipboard
09-25 05:16:38.974 98-98/? D/Genymotion: Received Set Clipboard
you can do this to resolve your problem:
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//ContactModel contacts=new ContactModel();//here you did mistake
Intent intent=new Intent(getApplicationContext(),ContactDetails.class);
intent.putExtra("contacts",(Serializable) adapterView.getSelectedItem());
startActivity(intent);
}
});
In ls.setOnItemClickListener, you're passing ContactModel contacts=new ContactModel(); which is technically a blank object of ContactModel.
Now, when you're trying to set data in ContactDetails.java from that blank object that you got from Intent like this,
imageView.setImageResource(contacts.getImage());
nameView.setText(contacts.getName());
the contact object has no image or name (or other attributes for that matter) that has been previously set on it. Hence, you're getting a null pointer exception.
So, change it like below and your problem should get away.
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ContactModel contacts= contact_list.get(i);
Intent intent=new Intent(getApplicationContext(),ContactDetails.class);
Bundle bundle = new Bundle();
bundle.putSerializable("contacts",contacts);
intent.putExtras(bundle);
startActivity(intent);
}
});
And in ContactDetails.java, get the object like this.
Intent intent=getIntent();
Bundle bundle = intent.getExtras();
final ContactModel contacts=(ContactModel)bundle.getSerializable("contacts");

The method and The constructor is undefined for the type

I have error message like this
The method setContentView(int, FindPeopleFragment) is undefined for the type FindPeopleFragment
The constructor BoxOfficeMoviesAdapter(FindPeopleFragment, ArrayList<BoxOfficeMovie>) is undefined
The constructor Intent(FindPeopleFragment, Class<BoxOfficeDetailActivity>) is undefined
So, what I need to improve on in my code? This my code, I want to display a ListView Box Office in the FindPeopleFragment
BoxOfficeMoviesAdapter.java
import info.androidhive.slidingmenu.R;
import java.util.ArrayList;
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 com.squareup.picasso.Picasso;
public class BoxOfficeMoviesAdapter extends ArrayAdapter<BoxOfficeMovie> {
public BoxOfficeMoviesAdapter(Context context, ArrayList<BoxOfficeMovie> aMovies) {
super(context, 0, aMovies);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
BoxOfficeMovie movie = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_box_office_movie, null);
}
// Lookup view for data population
TextView tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
TextView tvCriticsScore = (TextView) convertView.findViewById(R.id.tvCriticsScore);
TextView tvCast = (TextView) convertView.findViewById(R.id.tvCast);
ImageView ivPosterImage = (ImageView) convertView.findViewById(R.id.ivPosterImage);
// Populate the data into the template view using the data object
tvTitle.setText(movie.getTitle());
tvCriticsScore.setText("Score: " + movie.getCriticsScore() + "%");
tvCast.setText(movie.getCastList());
Picasso.with(getContext()).load(movie.getPosterUrl()).into(ivPosterImage);
// Return the completed view to render on screen
return convertView;
}
}
BoxOfficeMovieDetail.java
import info.androidhive.slidingmenu.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class BoxOfficeDetailActivity extends Activity {
private ImageView ivPosterImage;
private TextView tvTitle;
private TextView tvSynopsis;
private TextView tvCast;
private TextView tvAudienceScore;
private TextView tvCriticsScore;
private TextView tvCriticsConsensus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_box_office_detail);
// Fetch views
ivPosterImage = (ImageView) findViewById(R.id.ivPosterImage);
tvTitle = (TextView) findViewById(R.id.tvTitle);
tvSynopsis = (TextView) findViewById(R.id.tvSynopsis);
tvCast = (TextView) findViewById(R.id.tvCast);
tvCriticsConsensus = (TextView) findViewById(R.id.tvCriticsConsensus);
tvAudienceScore = (TextView) findViewById(R.id.tvAudienceScore);
tvCriticsScore = (TextView) findViewById(R.id.tvCriticsScore);
// Load movie data
BoxOfficeMovie movie = (BoxOfficeMovie) getIntent().getSerializableExtra(BoxOfficeActivity.MOVIE_DETAIL_KEY);
loadMovie(movie);
}
// Populate the data for the movie
#SuppressLint("NewApi")
public void loadMovie(BoxOfficeMovie movie) {
if (android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setTitle(movie.getTitle());
}
// Populate data
tvTitle.setText(movie.getTitle());
tvCriticsScore.setText(Html.fromHtml("<b>Critics Score:</b> " + movie.getCriticsScore() + "%"));
tvAudienceScore.setText(Html.fromHtml("<b>Audience Score:</b> " + movie.getAudienceScore() + "%"));
tvCast.setText(movie.getCastList());
tvSynopsis.setText(Html.fromHtml("<b>Synopsis:</b> " + movie.getSynopsis()));
tvCriticsConsensus.setText(Html.fromHtml("<b>Consensus:</b> " + movie.getCriticsConsensus()));
// R.drawable.large_movie_poster from
// http://content8.flixster.com/movie/11/15/86/11158674_pro.jpg -->
Picasso.with(this).load(movie.getLargePosterUrl()).
placeholder(R.drawable.large_movie_poster).
into(ivPosterImage);
}
}
FindPeopleFragment.java
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.loopj.android.http.JsonHttpResponseHandler;
import info.androidhive.slidingmenu.boxoffice.BoxOfficeActivity;
import info.androidhive.slidingmenu.boxoffice.BoxOfficeDetailActivity;
import info.androidhive.slidingmenu.boxoffice.BoxOfficeMovie;
import info.androidhive.slidingmenu.boxoffice.BoxOfficeMoviesAdapter;
import info.androidhive.slidingmenu.boxoffice.RottenTomatoesClient;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
public class FindPeopleFragment extends Fragment {
private ListView lvMovies;
private BoxOfficeMoviesAdapter adapterMovies;
private RottenTomatoesClient client;
public static final String MOVIE_DETAIL_KEY = "movie";
public FindPeopleFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_box_office, this);
lvMovies = (ListView) getView().findViewById(R.id.lvMovies);
ArrayList<BoxOfficeMovie> aMovies = new ArrayList<BoxOfficeMovie>();
adapterMovies = new BoxOfficeMoviesAdapter(this, aMovies);
lvMovies.setAdapter(adapterMovies);
// Fetch the data remotely
fetchBoxOfficeMovies();
setupMovieSelectedListener();
}
private void fetchBoxOfficeMovies() {
client = new RottenTomatoesClient();
client.getBoxOfficeMovies(new JsonHttpResponseHandler() {
#Override
public void onSuccess(int code, JSONObject body) {
JSONArray items = null;
try {
items = body.getJSONArray("movies");
ArrayList<BoxOfficeMovie> movies = BoxOfficeMovie.fromJson(items);
adapterMovies.addAll(movies);
adapterMovies.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public void setupMovieSelectedListener() {
lvMovies.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View item, int position, long rowId) {
Intent i = new Intent(FindPeopleFragment.this, BoxOfficeDetailActivity.class);
i.putExtra(MOVIE_DETAIL_KEY, adapterMovies.getItem(position));
startActivity(i);
}
});
}}
Please help me to fix it, thanks
The constructor BoxOfficeMoviesAdapter(FindPeopleFragment,
ArrayList) is undefined
In your Fragment use getActivity() instead of this when you pass context to the constructor.
Change this
adapterMovies = new BoxOfficeMoviesAdapter(this, aMovies);
to
adapterMovies = new BoxOfficeMoviesAdapter(getActivity(), aMovies);
The method setContentView(int, FindPeopleFragment) is undefined for
the type FindPeopleFragment
setContentView(R.layout.activity_box_office, this);
must be removed
setContentview is a method of Activity class not Fragment
Change to
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_box_office,container,false);
// rest of the code
return view;
}
Further getView() returns null
Change this
lvMovies = (ListView) getView().findViewById(R.id.lvMovies);
to
lvMovies = (ListView) view.findViewById(R.id.lvMovies);
The constructor Intent(FindPeopleFragment,
Class) is undefined
Finally Change this
Intent i = new Intent(FindPeopleFragment.this, BoxOfficeDetailActivity.class);
to
Intent i = new Intent(getActivity(), BoxOfficeDetailActivity.class);
You better read the Fragment documentation before going any further.

unknown error causing the app to crash

I am trying to populate an arraylist with three variable. After that the arraylist should display its content in a listview. when i run this class logcat shows an error which is completely unknown to me. Following is the class I am using.
import java.util.ArrayList;
import android.app.Activity;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Secondscreen extends Activity {
String pName ;
int pPrice;
String pDisc;
int total;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
ListView lv= (ListView) findViewById(R.id.listView1);
//TextView showCartContent = (TextView) findViewById(R.id.showCart);
final Button thirdBtn = (Button) findViewById(R.id.third);
//final LinearLayout lb = (LinearLayout) findViewById(R.id.secondLinear);
final Controller aController = (Controller) getApplicationContext();
final int cartSize = aController.getCart().getCartSize();
final ArrayList<Listitem> arrayList=new ArrayList<Listitem>();
BaseAdapter 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(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);
tv.setText(pName);
tv2.setText(pPrice);
tv3.setText(pDisc);
return view;
}
};
lv.setAdapter(adapter);
if(cartSize >0)
{
for(int i=0;i<cartSize;i++)
{
pName = aController.getCart().getProducts(i).getProductName();
pPrice = aController.getCart().getProducts(i).getProductPrice();
pDisc = aController.getCart().getProducts(i).getProductDesc();
Listitem item=new Listitem(pName, pPrice,pDisc);
arrayList.add(item);
adapter.notifyDataSetChanged();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Please Help me to solve this.
tv2.setText(pPrice);
pPrice is a int. setText(int) looks for a String id inside the R classes throwing a ResourceNotFoundException if the look-up fails. A quick fix is
tv2.setText(""+pPrice);
This way you are providing a String object to setText
Edit:
Change your getView this way:
#Override
public View getView(int position, View view, ViewGroup viewgroup) {
if (view == null) {
view=inflater.inflate(R.layout.pattern, null);
}
Listitem item = (Listitem)getItem(position)
TextView tv=(TextView) view.findViewById(R.id.nameview);
TextView tv2=(TextView) view.findViewById(R.id.pdesc);
TextView tv3=(TextView) view.findViewById(R.id.priceView);
tv.setText(item. pName);
tv2.setText(""+item.pPrice);
tv3.setText(item.pDisc);
return view;
}
You never get your objects from the ArrayList. Add this code to your getView() method:
ListItem item = arrayList.get(position);
tv.setText(item.pName);
tv2.setText(item.pPrice);
tv3.setText(item.pDisc);

setOnItemClickListener in custom ListView not Work ActionBarSherlock

I'm using ActionBar Sherlock and works fine.
This code works fine in 2.x but not in 4.x
The click only works in versions 2.x not working in 4.x versions I've tried many ways and I can not make the click function
what is the problem?
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockListActivity;
public class Inicio extends SherlockListActivity {
private ListView mListView;
private ArrayList<Capitulos> listado;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mListView = getListView();
listado = new ArrayList<Capitulos>();
for(int i = 0; i < 20; i++){
listado.add(new Capitulos("Titulo " + i, "descripcion " + i));
}
AdaptadorTitulares adaptador = new AdaptadorTitulares(Inicio.this);
setListAdapter(adaptador);
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Toast.makeText(Inicio.this, "hazlo", 0).show();
}
});
}
class AdaptadorTitulares extends ArrayAdapter {
Activity context;
#SuppressWarnings("unchecked")
AdaptadorTitulares(Activity context) {
super(context, R.layout.lista, listado);
this.context = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View item = inflater.inflate(R.layout.lista, null);
TextView titulo = (TextView)item.findViewById(R.id.titulo_art);
titulo.setText(((Capitulos)getItem(position)).getTitulo());
TextView subtitulo = (TextView)item.findViewById(R.id.desc_art);
subtitulo.setText(((Capitulos)getItem(position)).getDescrip());
return(item);
}
}
}
Try to define it inside the arrayyAdapter class as onClickListener():
item.setOnClickListener(.....

Categories