How to pass value from listview to the next activity - java

I'm new to android studios and am currently about to finish up on my first project. However, I'm stuck at the part where I have to pass the value selected from the listview to the next activity. I have tried researching on the codes but none seem to be able to work. Any help would be greatly appreciated.
DisplayProduct.java
public class DisplayProduct extends AppCompatActivity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
DatabaseHelper databaseHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_product);
listView = (ListView)findViewById(R.id.listView);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.display_product_row);
listView.setAdapter(listDataAdapter);
databaseHelper = new DatabaseHelper(getApplicationContext());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//Object data = parent.getItemAtPosition(position);
//String value = data.toString();
}
});
sqLiteDatabase = databaseHelper.getReadableDatabase();
cursor = databaseHelper.getInformations(sqLiteDatabase);
if(cursor.moveToFirst())
{
do {
String contact,location,issue;
contact = cursor.getString(0);
location = cursor.getString(1);
issue = cursor.getString(2);
Information information = new Information(contact,location,issue);
listDataAdapter.add(information);
} while (cursor.moveToNext());
}
}
}
ListDataAdapter.java
public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler
{
TextView Contact,Location,Issue;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.display_product_row, parent, false);
layoutHandler = new LayoutHandler();
layoutHandler.Contact = (TextView) row.findViewById(R.id.textView8);
layoutHandler.Location = (TextView) row.findViewById(R.id.textView18);
layoutHandler.Issue = (TextView) row.findViewById(R.id.textView90);
row.setTag(layoutHandler);
} else {
layoutHandler = (LayoutHandler) row.getTag();
}
Information information = (Information) this.getItem(position);
layoutHandler.Contact.setText(information.getContact());
layoutHandler.Location.setText(information.getLocation());
layoutHandler.Issue.setText(information.getIssue());
return row;
}
}
LocationDetail.java
public class LocationDetail extends AppCompatActivity {
private TextView Textv;
DatabaseHelper databaseHelper;
SQLiteDatabase sqlitedatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_detail);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_location_detail, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

From DisplayProduct.java :
Intent intent = new Intent(this, LocationDetail.class);
Object data = parent.getItemAtPosition(position);
String message = data.toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
From LocationDetail.java:
Intent intent = getIntent();
String value = intent.getStringExtra(EXTRA_MESSAGE);

Related

How do I fix the constructor so it works with the parameters I want?

I'm making an app where there's data sent from one activity to another. I'm using among other ArrayAdapters. I've created a container that contains the parameters I need, but when I write it in the Activity, it doesn't work as it expects something else than I write. The data I'm sending from one activity to another is the input from the user. I'm using the input to filter a ListView I've made. So my question is, how do I fix the constructor, so it can work with the parameters I need? I know I've uploaded a lot of code, but I think it's relevant.
This is my Container:
public class Container{
public final String søgeord;
public final String itemname;
public final Integer imgid;
Container(String søgeord, String itemname, Integer imgid){
this.søgeord=søgeord;
this.itemname = itemname;
this.imgid = imgid;
}
}
This is the CustomListAdapter:
public class CustomListAdapter extends ArrayAdapter<Container>{
private final Activity context;
LayoutInflater inflater;
public CustomListAdapter(Activity context, Container[] containers) {
super(context, R.layout.mylist, containers);
this.context=context;
}
public View getView(int position,View view,ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.mylist, null);
TextView txtTitle = (TextView) view.findViewById(R.id.item);
ImageView imageView = (ImageView) view.findViewById(R.id.icon);
TextView extratxt = (TextView) view.findViewById(R.id.textView1);
Container currentItem = getItem(position);
txtTitle.setText(currentItem.itemname);
imageView.setImageResource(currentItem.imgid);
extratxt.setText(currentItem.itemname);
return view;
};
}
This is the Activity I send data from, and have commented beside the constructor:
public class Forside extends AppCompatActivity implements View.OnClickListener, Liste{
CustomListAdapter listAdapter;
EditText filterText;
ImageButton sog;
EditText sogefelt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forside);
filterText = (EditText)findViewById(R.id.sogefelt);
ListView itemList = (ListView)findViewById(R.id.listView);
listAdapter = new CustomListAdapter (this, annoncer, imageId, null); //this is the constructor
sog = (ImageButton) findViewById(R.id.sog);
sog.setOnClickListener(this);
sogefelt = (EditText) findViewById(R.id.sogefelt);
itemList.setAdapter(listAdapter);
itemList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position==0){
Intent intent = new Intent(Forside.this, Sogeresultater.class);
startActivity(intent);
}
}
});
}
public void onClick (View v){
if (v == sog){
String søgeord = sogefelt.getText().toString();
ArrayList<String> resultater = new ArrayList<String>();
for(String i: annoncer) {
if (i.toUpperCase().contains(søgeord.toUpperCase()))
resultater.add(i);
}
Intent intent = new Intent(this, Sogeresultater.class);
intent.putExtra("søg", resultater.toArray(new String[resultater.size()]));
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.Forside) {
Intent intent = new Intent(this, Forside.class);
startActivity(intent);
}
else if (id == R.id.Logind){
Intent intent = new Intent(this, Log_Ind.class);
startActivity(intent);
}
else if (id==R.id.Opretbruger) {
Intent intent = new Intent(this, Opret_bruger.class);
startActivity(intent);
}
return true;
}
}
Last but not least, this is the Activity I send data to:
public class Sogeresultater extends AppCompatActivity implements Liste{
CustomListAdapter listAdapter;
EditText filterText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
final String[] søgestreng = getIntent().getExtras().getStringArray("søg");
filterText = (EditText)findViewById(R.id.sogefelt);
ListView itemList = (ListView)findViewById(R.id.listView);
listAdapter = new CustomListAdapter (this, annoncer, imageId, søgestreng); //this also the constructor, here I want "søgestreng", as it's the input from the user
itemList.setAdapter(listAdapter);
itemList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Position " + position, Toast.LENGTH_LONG).show();
}
});
filterText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Sogeresultater.this.listAdapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.Forside) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
CustomListAdapter is only capable of dealing with an array of Containers. Each container seems to have the properties you try to supply to the adapter's constructor.
To make it work you'll either need to turn the data you have into the format it expects: (i.e. transform the String[] array into a Container[] array)
List<Container> containers = new ArrayList<Container>();
for (String sogething : søgestreng) {
String itemname = "I don't know"; // ?
Integer imgid = 1234; // ?
Container container = new Container(sogething, itemname, imgid);
containers.add(container);
}
Container[] array = containers.toArray(new Container[containers.size()]);
listAdapter = new CustomListAdapter(this, array);
Or you need to change the existing / add another constructor that is happy with just a String[] array instead of a full Container array. But since your Adapter needs the things defined in Container you'll have to come up with a way to substitute / load the data that belongs to the string.

How to add data from a database to a recycler view using a cursor adapter?

So I have tried implementing my database with a recycler view and cursoradapter, but I am getting errors. I can not understand them well so I dont know if I did not implement the adapter right or if it is something else. Here are the java files:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.nick.mowen.receiptmanager.LOCATION";
public String Places[];
public RecyclerView RV;
private RVAdapter adapter;
Cursor mCursor;
ManagerDatabaseAdapter managerDatabaseAdapter;
List<MainInfo> mainInfo = new ArrayList<MainInfo>();
RecyclerView.LayoutManager layoutManager;
private Context activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
managerDatabaseAdapter = new ManagerDatabaseAdapter(this);
setContentView(R.layout.activity_main);
adapter = new RVAdapter(getActivity(), managerDatabaseAdapter.getTheCursor());
RV = (RecyclerView) findViewById(R.id.mainV);
layoutManager = new LinearLayoutManager(getActivity());
RV.setLayoutManager(layoutManager);
RV.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
// getMenuInflater().inflate(R.menu.menu_main, li)
return true;
}
public static void getData () {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this,SettingsActivity.class);
intent.putExtra(EXTRA_MESSAGE,true);
startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
return true;
}
return super.onOptionsItemSelected(item);
}
/*#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView userText= (TextView) view;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}*/
public void addInstance(View view) {
Intent intent = new Intent(this,LocationAdder.class);
intent.putExtra(EXTRA_MESSAGE,true);
startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
}
public Context getActivity() {
return activity;
}
}
Here is the recycler view adapter:
public class RVAdapter extends Adapter<RVAdapter.MyViewHolder> {
private LayoutInflater inflater;
CursorAdapter mCursorAdapter;
Context mContext;
//Cursor cursor;
//public Cursor mCursor;
MainInfo mainInfo;
ManagerDatabaseAdapter.ManagerHelper managerHelper;
public ManagerDatabaseAdapter managerDatabaseAdapter;
// public List<MainInfo> mainInfoList = Collections.emptyList();
public RVAdapter (Context context, Cursor cursor) {
mContext = context;
mCursorAdapter = new CursorAdapter(mContext, cursor, 0) {
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
//Cursor mCursor = getCursor();
final LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.custom_row, parent, false);
int nameCol = cursor.getColumnIndex("Codes");
String name = cursor.getString(nameCol);
TextView nameText = (TextView) view.findViewById(R.id.mainV);
if (nameText != null) {
nameText.setText(name);
}
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
int nameCol = cursor.getColumnIndex("Code");
String name = cursor.getString(nameCol);
TextView nameText = (TextView) view.findViewById(R.id.mainV);
if (nameText != null) {
nameText.setText(name);
}
}
};
//this.mainInfoList = mainInfoList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mCursorAdapter.newView(mContext, mCursorAdapter.getCursor(), parent);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int i) {
/*MainInfo mainInfo = mainInfoList.get(i);
holder.Title.setText(mainInfo.get_Title());
holder.Body.setText(mainInfo.get_SubT());*/
mCursorAdapter.bindView(holder.itemView, mContext, mCursorAdapter.getCursor());
}
#Override
public int getItemCount() {
//return mainInfoList.size();
return mCursorAdapter.getCount();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView Title;
MyViewHolder(View itemView) {
super(itemView);
Title = (TextView) itemView.findViewById(R.id.Row_Header);
//Body = (TextView) itemView.findViewById(R.id.Row_Footer);
}
}
}
Here is the method to get the cursor:
public Cursor getTheCursor() {
String[] columns = {ManagerHelper.UID,ManagerHelper.NAME,ManagerHelper.CODE};
SQLiteDatabase db = helper.getWritableDatabase();
Cursor mCursor = db.query(ManagerHelper.TABLE_NAME, columns, null, null, null, null, null);
return mCursor;
}
And finally here is the error I am getting:
The problem is that in onCreate you're using the method getActivity() but you're never initializing the activity object.
Please try to change your onCreate to something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
managerDatabaseAdapter = new ManagerDatabaseAdapter(this);
setContentView(R.layout.activity_main);
adapter = new RVAdapter(this, managerDatabaseAdapter.getTheCursor());
RV = (RecyclerView) findViewById(R.id.mainV);
layoutManager = new LinearLayoutManager(this);
RV.setLayoutManager(layoutManager);
RV.setAdapter(adapter);
}
That should fix your NPE and you can see what other parts are missing. And remove the getActivity() method, you don't need that in an Activity it is used on a Fragment, so I supposed you copied that code from a Fragment implementation.
If you are running a query with a CursorLoader and you want RecyclerView instead of ListView.
You can try my CursorRecyclerViewAdapter CursorAdapter in RecyclerView
And also visit this reference link link

null pointer exception in OnOptionItemSelected

I am trying to delete multiple checked rows from listview when click on the delete icon on action bar. However i get these nullpointerexception, i think the problem would be on adapter and dbHelper as i only declare them, but i do not know how i can solve this.
public class MainActivity extends ActionBarActivity {
public static TaskerDbHelper dbHelper;
public static ListView listviewTasks;
public static List<Task> arrayTasks;
public static TaskAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new TaskerDbHelper(this);
arrayTasks = dbHelper.getAllTasks();
listviewTasks = (ListView) findViewById(R.id.Tasks_onDate);
adapter = new TaskAdapter(this,arrayTasks);
listviewTasks.setAdapter(adapter);
listviewTasks.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Intent detailIntent = new Intent(MainActivity.this, DetailTaskActivity.class);
detailIntent.putExtra("rowID", (int)id);
startActivity(detailIntent);
}
});
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch(item.getItemId()){
case R.id.action_search:
return true;
case R.id.action_add:
Intent Addintent = new Intent(MainActivity.this, AddTaskActivity.class);
startActivity(Addintent);
return true;
case R.id.action_delete:
SparseBooleanArray checkedItems = listviewTasks.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++){
if(checkedItems.valueAt(i)){
dbHelper.deleteTask((int)adapter.getItemId(i));
}
}
listviewTasks.invalidateViews();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
and the log is
http://i.stack.imgur.com/OqLuN.png
My guess is to work with a extended ArrayAdapter. This worked like a charm for me for multiple click->delete listview.
I declared it all like this:
arrayAdapter = new ListAdapter(this,R.layout.list_item, **YOUR LIST**);
listview.setAdapter(arrayAdapter);
listview.setCacheColorHint(Color.TRANSPARENT);
selectedItems = new ArrayList<Integer>();
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
ArrayList<Integer> selectedIds = arrayAdapter.selectedid;
Integer pos = new Integer(position);
if(selectedIds.contains(pos)) {
selectedIds.remove(pos);
}
else {
selectedIds.add(pos);
}
arrayAdapter.notifyDataSetChanged();
}
});
The class I extended.
public class ListAdapter extends ArrayAdapter<ChartItem> {
Context context;
protected ArrayList<**YOUR LIST ITEM**> list;
LayoutInflater inflater;
ArrayList<Integer> selectedid;
public ListAdapter(Context context, int layoutResourceId ,ArrayList<ChartItem> ticket) {
super(context,layoutResourceId,ticket);
selectedid = new ArrayList<Integer>();
this.list = **ARRAY YOU WANT TO LIST**;
this.inflater = LayoutInflater.from(context);
this.context = context;
}
public int getCount() {
return list.size();
}
public ChartItem getItem(int position) {
return list.get(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = this.inflater.inflate(R.layout.list_item, parent, false);
holder.name = (TextView) convertView.findViewById(R.id.rowTextView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ChartItem item = list.get(position);
TextView tv = (TextView) convertView.findViewById(R.id.rowTextView);
tv.setText(item.getName());
TextView tv2 = (TextView) convertView.findViewById(R.id.rowTextView2);
tv2.setText(String.valueOf(item.getPrice()));
if(selectedid.contains(position)){
tv.setBackgroundColor(Color.DKGRAY);
tv.setTextColor(Color.WHITE);
}
else{
tv.setBackgroundColor(Color.TRANSPARENT);
tv.setTextColor(Color.BLACK);
}
return convertView;
}
private class ViewHolder {
TextView name;
}
}
I really had allot of trouble with this aswell and I think this is the best way to do it so far.
If you need any more help or when you have questions about this code snippet let me know!
It is actually the checkedItems is null.
I actually wanna reach something like this. So when user checked the rows, they may delete or mark it as completed
http://i.stack.imgur.com/k4jKT.png
I solve it from another approaches like below.
case R.id.action_delete:
for(int i = 0; i < arrayTasks.size();i++){
if((CheckBox)listviewTasks.getChildAt(i).findViewById(R.id.selected) != null){
CheckBox cBox=(CheckBox)listviewTasks.getChildAt(i).findViewById(R.id.selected);
if(cBox.isChecked()){
dbHelper.deleteTask((int)adapter.getItemId(i));
}
}
}
adapter.notifyDataSetChanged();
return true;
I juz change the action_delete for the onoptionitemselected function.
[1]:

How do i call a context menu on longclick in a ListView Item?

HomeFragment
imports;
public class HomeFragment extends Fragment {
// Declare Variables
ListView list;
TextView text;
ListViewAdapter adapter;
EditText editsearch;
String[] title;
String[] date;
String[] status;
ArrayList<ListCourse> arraylist = new ArrayList<ListCourse>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
date = new String[] { "11/01/2011", "10/05/2006", "12/07/2002", "05/04/2011", "01/08/2012",
"09/12/2017", "22/06/2024", "31/01/2000", "10/10/2156", "10/02/2006" };
title = new String[] { "Programação", "Matemática", "Logística",
"Mobile", "Sistemas Operativos", "iOS", "Android", "Windows",
"Hardware", "Formação" };
status = new String[] { " ongoing ", " ongoing ",
" ongoing ", " standby ", " ongoing ", " ongoing ",
" ongoing ", " ongoing ", " finished ", " ongoing " };
// Locate the ListView in listview_main.xml
list = (ListView) rootView.findViewById(R.id.listview);
for (int i = 0; i < title.length; i++)
{
ListCourse wp = new ListCourse(date[i], title[i],
status[i]);
// Binds all strings into an array
arraylist.add(wp);
}
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(getActivity(), arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
return rootView;
}
}
I just need 3 items on the context menu: Like, Comment and Favorite. I tried implementing various tutorials to no avail, my project consist of a MainActivity that has a slidermenu to open some fragments like this one where the list is and where I want to put the context menu.
Here´s my adapter:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<ListCourse> coursepopulatelist = null;
private ArrayList<ListCourse> arraylist;
public ListViewAdapter(Context context, List<ListCourse> coursepopulatelist) {
mContext = context;
this.coursepopulatelist = coursepopulatelist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<ListCourse>();
this.arraylist.addAll(coursepopulatelist);
}
public class ViewHolder {
TextView title;
TextView date;
TextView status;
}
#Override
public int getCount() {
return coursepopulatelist.size();
}
#Override
public ListCourse getItem(int position) {
return coursepopulatelist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.title = (TextView) view.findViewById(R.id.title);
holder.date = (TextView) view.findViewById(R.id.date);
holder.status = (TextView) view.findViewById(R.id.status);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.title.setText(coursepopulatelist.get(position).getTitle());
holder.date.setText(coursepopulatelist.get(position).getDate());
holder.status.setText(coursepopulatelist.get(position).getStatus());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, SingleItemView.class);
// Pass all data rank
intent.putExtra("title",(coursepopulatelist.get(position).getTitle()));
// Pass all data country
intent.putExtra("date",(coursepopulatelist.get(position).getDate()));
// Pass all data population
intent.putExtra("status",(coursepopulatelist.get(position).getStatus()));
// Pass all data flag
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
coursepopulatelist.clear();
if (charText.length() == 0) {
coursepopulatelist.addAll(arraylist);
}
else
{
for (ListCourse wp : arraylist)
{
if (wp.getDate().toLowerCase(Locale.getDefault()).contains(charText))
{
coursepopulatelist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Are the changes supposed to go in the adapter or the fragment? I tried several times with OnCreateContextMenu and ContextMenuSelectedItem cant get it to work on the fragment, also tried OnLongItemClick. Any help would be appreciated.
I managed to get one context menu working, right here:
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
adapter = new ListViewAdapter(getActivity(), arraylist);
Object item = adapter.getItem(info.position);
menu.setHeaderTitle("Opções");
menu.add(0, v.getId(), 0, "Like");
menu.add(1, v.getId(), 0, "Comment");
menu.add(2, v.getId(), 0, "Favorite");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Like") {
addLike(item.getItemId());
} else if (item.getTitle() == "Comment") {
} else if (item.getTitle() == "Favorite") {
// code
} else {
return false;
}
return true;
}
public void addLike(int id){
}
Right after the return rootView in the HomeFragment. Also had to add android:longClickable="true" on the listview.xml or it would never work (I put it into the listviewitem.xml too just in case).
first set your listvieW as follow myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myListView.setAdapter(adapter);
then register for MultiChoiceModeListener and override his methods in your liking :)
myListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// here you will inflate your CAB
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
});
}
Here is the link

Want to remove html tag in my android project

I am fetching data from website and i am displaying as listview in android,but with the data it shows some html tags also including the data in my listview.
Applicationadapter.java
public class ApplicationAdapter extends ArrayAdapter<Application>
{
private List<Application> items;
private LayoutInflater inflator;
public ApplicationAdapter(Context context, List<Application> items)
{
super(context, R.layout.activity_row, items);
this.items = items;
inflator = LayoutInflater.from(getContext());
}
#Override
public int getCount()
{
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
//View v = convertView;
if ( convertView == null )
{
convertView = inflator.inflate(R.layout.activity_row, null);
LayoutInflater li = LayoutInflater.from(getContext());
//convertView = inflator.inflate(R.layout.app_custom_list, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(R.id.text1);
holder.chk = (CheckBox) convertView.findViewById(R.id.checkbox);
/*holder.chk
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
/*#Override
public void onCheckedChanged(CompoundButton view,
boolean isChecked) {
int getPosition = (Integer) view.getTag();
items.get(getPosition).setSelected(view.isChecked());
}
});*/
convertView.setTag(holder);
convertView.setTag(R.id.text1, holder.text1);
convertView.setTag(R.id.checkbox, holder.chk);
}else {
holder = (ViewHolder) convertView.getTag();
}
Application app = items.get(position);
holder.chk.setTag(position);
holder.text1.setText(items.get(position).getContent());
//holder.chk.setChecked(items.get(position).isSelected());
if ( app != null )
{
TextView titleText = (TextView) convertView.findViewById(R.id.titleTxt);
if ( titleText != null )
titleText.setText(Html.fromHtml(app.getContent()).toString());
//titleText.setText(app.getContent());
//holder.chk.setChecked(((View) Html.fromHtml(app.getContent())).isSelected());
}
return convertView;
}
static class ViewHolder {
public TextView text1;
public CheckBox chk;
}
//return convertView;
}
eventhough i used one line for remove the html tag in listview,but i dont know eventhough its shows the html tags like with my listview. my output shows like that in listview hi<br> bye<br>' hello<br>.but i dont want to show that html tags in my listview,how i can solve the problem.
Mainactivity.java
public class MainActivity extends Activity implements FetchDataListener
{
private static final int ACTIVITY_CREATE=0;
private ProgressDialog dialog;
ListView lv;
//private ProjectsDbAdapter mDbHelper;
//private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
//mDbHelper = new ProjectsDbAdapter(this);
//mDbHelper.open();
//fillData();
//registerForContextMenu(getListView());
lv =(ListView)findViewById(R.id.list);
initView();
}
private void initView()
{
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://dry-brushlands-3645.herokuapp.com/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
//mDbHelper.open();
//Cursor projectsCursor = mDbHelper.fetchAllProjects();
//startManagingCursor(projectsCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
//String[] from = new String[]{ProjectsDbAdapter.KEY_TITLE};
// and an array of the fields we want to bind those fields to (in this case just text1)
//int[] to = new int[]{R.id.text1};
/* Now create a simple cursor adapter and set it to display
SimpleCursorAdapter projects =
new SimpleCursorAdapter(this, R.layout.activity_row, projectsCursor, from, to);
setListAdapter(projects);
*/
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
/*dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_row,
projectsCursor,
from,
to,
0);
setListAdapter(dataAdapter);
*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.activity_main, menu);
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
createProject();
return super.onMenuItemSelected(featureId, item);
}
private void createProject() {
Intent i = new Intent(this, ProjectEditActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
initView();
}
#Override
public void onFetchComplete(List<Application> data)
{
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
lv.setAdapter(adapter);
}
#Override
public void onFetchFailure(String msg)
{
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}
i want to show the listview only data,dont need of htmltags
I want to know which line is correct if ( titleText != null ) then
titleText.setText(Html.fromHtml(app.getContent()).toString()); or i want to write like this holder.text1.setText(Html.fromHtml(app.getContent()).toString());
You can do by change
holder.text1.setText(items.get(position).getContent());
to
holder.text1.setText(Html.fromHtml(items.get(position).getContent()));

Categories