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);
Related
i have tried several methods to make my items clickable i have read about focus and added the lines in my XML file Relative layout. nothing seems to help. the click listener still doesn't seem to do anything for me.. please help!!!
this is my activity list view class:
package com.example.trezah12.adminmodule;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class AdminList extends AppCompatActivity {
CustomAdapterAdmin adapterAdmin;
ArrayList<Admin> list;
ListView list1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_list);
DBhandler dBhandler = new DBhandler(this);
list = new ArrayList<>();
list1 = (ListView) findViewById(R.id.listview4);
viewData();
list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long Id) {
Intent intent = new Intent(AdminList.this, LaunchActivity.class);
}
});
}
private void viewData() {
final DBhandler dbHandler3 = new DBhandler(AdminList.this);
Cursor cursor = dbHandler3.viewData();
if (cursor.getCount() == 0){
Toast toast = Toast.makeText(getApplicationContext(), "Sorry no Data Found!!", Toast.LENGTH_SHORT);
}
else {
while (cursor.moveToNext()) {
Admin admin = new Admin();
admin.setUsername(cursor.getString(0));
list.add(admin);
list1 = (ListView) findViewById(R.id.listview4);
adapterAdmin = new CustomAdapterAdmin(list, AdminList.this);
list1.setAdapter(adapterAdmin);
}
}
}
}
below is my custom adapter class for admin:
package com.example.trezah12.adminmodule;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by trezah12 on 23/10/2018.
*/
public class CustomAdapterAdmin extends BaseAdapter {
private List<Admin> adminList = new ArrayList<Admin>();
private Context activity;
private static LayoutInflater inflater = null;
public CustomAdapterAdmin(List<Admin> adminList, Context activity) {
this.adminList = adminList;
this.activity = activity;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return adminList.size();
}
#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) {
View v = convertView;
if (convertView == null) {
v = inflater.inflate(R.layout.customeadmin, null);
}
Admin admin = adminList.get(position);
TextView txt1 = (TextView) v.findViewById(R.id.textView1);
txt1.setText(admin.getUsername());
TextView txt2 = (TextView) v.findViewById(R.id.textView2);
txt2.setText(admin.getPassword());
return v;
}
}
Below is my XML file for list view
<?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"
>
<ListView
android:id="#+id/listview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</ListView>
</RelativeLayout>
that is because yout did not start the activity
list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long Id) {
Intent intent = new Intent(AdminList.this, LaunchActivity.class);
startActivity(intent);
}
});
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();
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.
Getting error on My array Adapter class .The error is on Startavtivity line i dont know why it is its working on other pahes but it shows error on this page .So could you please help me out
ERROR" The Constructor Intent(MyArrayAdapter,Class<Add_new_employee >undefined)
package com.example.employeemanager;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class MyArrayAdapter extends ArrayAdapter<Student> {
Context context;
int layoutResourceId;
ArrayList<Student> students = new ArrayList<Student>();
public MyArrayAdapter(Context context, int layoutResourceId,ArrayList<Student> studs)
{
super(context, layoutResourceId, studs);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.students = studs;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View item = convertView;
StudentWrapper StudentWrapper = null;
if (item == null)
{
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
item = inflater.inflate(layoutResourceId, parent, false);
StudentWrapper = new StudentWrapper();
StudentWrapper.name = (TextView) item.findViewById(R.id.textName);
StudentWrapper.age = (TextView) item.findViewById(R.id.textAge);
StudentWrapper.address = (TextView) item.findViewById(R.id.textAddr);
StudentWrapper.edit = (Button) item.findViewById(R.id.btnEdit);
StudentWrapper.delete = (Button) item.findViewById(R.id.btnDelete);
StudentWrapper.checkBox = (CheckBox) item.findViewById(R.id.checkBox1);
item.setTag(StudentWrapper);
}
else
{
StudentWrapper = (StudentWrapper) item.getTag();
}
Student student = students.get(position);
StudentWrapper.name.setText(student.getName());
StudentWrapper.age.setText(student.getAge());
StudentWrapper.address.setText(student.getAddress());
StudentWrapper.edit.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
startActivity(new Intent
(MyArrayAdapter.this,Add_new_employee.class) );
}
});
StudentWrapper.delete.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
StudentWrapper.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
Toast.makeText(context, "Checkox", Toast.LENGTH_LONG).show();
}
});
return item;
}
protected void startActivity(Intent intent) {
// TODO Auto-generated method stub
}
static class StudentWrapper
{
TextView name;
TextView age;
TextView address;
Button edit;
Button delete;
CheckBox checkBox;
}
}
Inseted of this
startActivity(new Intent
(MyArrayAdapter.this,Add_new_employee.class) );
use this
context.startActivity(new Intent
(context,Add_new_employee.class) );
Note: Make sure you had declared Add_new_employee in android manifest.xml
Try
startActivity(new Intent
(getBaseContext(),Add_new_employee.class) );
I want to show a context menu (OnClickLong)with delete and edit option, in a custom list i created with a custom list adapter. i will post the code
SpotListFragment
package com.pap.myspots.fragments;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.pap.myspots.R;
import com.pap.myspots.R.layout;
import com.pap.myspots.database.DBAdapter;
import com.pap.myspots.listView.SpotList;
import com.pap.myspots.listView.SpotListAdapter;
import android.annotation.SuppressLint;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class SpotListFragment extends Fragment implements OnClickListener{
String nome;
String local;
Button createToast;
List<String> nomes ;
List<String> locais ;
ListView listView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_spotlist, container, false);
DBAdapter db = new DBAdapter(getActivity());
db.open();
Cursor cursor = db.getAllTitles();
nomes = new ArrayList<String>();
while(cursor.moveToNext()){
String uname = cursor.getString(cursor.getColumnIndex("nome"));
nomes.add(uname);
}
Cursor cursor2 = db.getAllTitles();
locais = new ArrayList<String>();
while(cursor2.moveToNext()){
String ulocal = cursor2.getString(cursor.getColumnIndex("local"));
locais.add(ulocal);
}
SpotListAdapter adapter = new SpotListAdapter(getActivity(), generateData());
// 2. Get ListView from activity_main.xml
listView = (ListView) rootView.findViewById(R.id.spotList);
// 3. setListAdapter
listView.setAdapter(adapter);
return rootView;
}
private ArrayList<SpotList> generateData(){
ArrayList<SpotList> items = new ArrayList<SpotList>();
int i = 0;
while(nomes.size()>i){
items.add(new SpotList(new String(nomes.get(i)),new String(locais.get(i))));
i++;
}
return items;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
//Deleted individual cart items
}
SpotListAdapter
package com.pap.myspots.listView;
import java.util.ArrayList;
import com.pap.myspots.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class SpotListAdapter extends ArrayAdapter<SpotList> {
private final Context context;
private final ArrayList<SpotList> itemsArrayList;
public SpotListAdapter(Context context, ArrayList<SpotList> itemsArrayList) {
super(context, R.layout.list_row, itemsArrayList);
this.context = context;
this.itemsArrayList = itemsArrayList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1. Create inflater
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 2. Get rowView from inflater
View rowView = inflater.inflate(R.layout.list_row, parent, false);
// 3. Get the two text view from the rowView
TextView labelView = (TextView) rowView.findViewById(R.id.title);
TextView valueView = (TextView) rowView.findViewById(R.id.place);
// 4. Set the text for textView
labelView.setText(itemsArrayList.get(position).getNome());
valueView.setText(itemsArrayList.get(position).getLocal());
// 5. retrn rowView
return rowView;
}
}
SpotList(Beans)
package com.pap.myspots.listView;
public class SpotList {
public SpotList(String nome, String local) {
super();
this.nome = nome;
this.local = local;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getLocal() {
return local;
}
public void setLocal(String local) {
this.local = local;
}
private String nome;
private String local;
}
So first of all register your listView for a context menu in the onCreate method:
registerForContextMenu(yourListView);
Create the contextmenu by overridig the onCreateContextMenu:
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
_listPosition = info.position; // Get Index of long-clicked item
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Choose Action"); // Context-menu title
menu.add(0, v.getId(), 0, "Edit"); // Add element "Edit"
menu.add(0, v.getId(), 1, "Delete"); // Add element "Delete"
}
React on clicks in context-menu:
#Override
public boolean onContextItemSelected(MenuItem item)
{
if(item.getTitle() == "Edit") // "Edit" chosen
{
// Do stuff
}
else if(item.getTitle() == "Delete") // "Delete" chosen
{
// Do stuff
}
else
{
return false;
}
return true;
}
Next time just spend few minutes and google it yourself:
http://developer.android.com/guide/topics/ui/menus.html#context-menu
http://www.stealthcopter.com/blog/2010/04/android-context-menu-example-on-long-press-gridview/
Override onCreateContextMenu() to create the menu and onContextItemSelected() to handle the click event
You also need to register listView for the contextual menu. You can do it in fragment's onActivityCreated() method:
registerForContextMenu(listView);
You have to register your custom ListView with Context Menu. Use Method registerForContextMenu(listView); . Call this method in onCreate
I would define the onLongClickListener in the getView() method of your overriden ArrayList extension. Just register the view inside the long click listener, using registerForContextView(convertView).
Now in your Activity code, simply define the context menu as you would in any other case:
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
...
menu.setHeaderTitle(...);
menu.add(...);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
final int mId = item.getItemId();
switch (mId) {
case 0:
...
break;
default:
break;
}
More precision:
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
TreeViewList v1=(TreeViewList) v; //my custom listview
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
final LinearLayout viewLayout = (LinearLayout) v1.getChildAt(info.position-v1.getFirstVisiblePosition());//if in list many items
final TextView descriptionView = (TextView) viewLayout
.findViewById(R.id.list_item_description);
menu.add(0, v.getId(), 0, descriptionView.getText());
menu.add(0, v.getId(), 0, "Action 2");
}