I'm trying to bookmark my app but I have some charges in my code, below I'll explain my problems.
Let's start with my adapter memes.class
public class memes{
private String nome;
private int resID;
private Boolean mIsFavourite;
public memes(String nome, int resID){
this.nome = nome;
this.resID = resID;
}
public Boolean getmIsFavourite() {
return mIsFavourite;
}
public void setmIsFavourite(Boolean mIsFavouriteResource) {
this.mIsFavourite = mIsFavouriteResource;
}
public String getNome(){
return nome;
}
public int getResId(){
return resID;
}
#Override
public String toString(){
return nome;
}
}
Main activity
public class MainActivity extends AppCompatActivity {
ListView lv;
MediaPlayer mp;
ArrayList<memes> item;
ArrayAdapter<memes> arrayAdapter;
String[] Nomes = new String[]{"Compartilhar", "Add Favoritos"};
List<memes> favoriteMemes = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
lv = findViewById(R.id.lv);
mp = new MediaPlayer();
item = new ArrayList<>();
//itens
item.add(new memes("item 1", R.raw.audio1));
item.add(new memes("item 2", R.raw.audio2));
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, item);
lv.setAdapter(arrayAdapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int position, long l) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Menu");
builder.setItems(MainActivity.this.Nomes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
sendWhatsAppAudio(position);
return;
case 1:
//set item true
item.get(position).setmIsFavourite(true);
return;
default:
}
}
});
builder.show();
return true;
}
});
}
This is where I send the items to the other activity
//Here is the mess.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.abreFavoritos:
for(int i=0;i<lv.getAdapter().getCount();i++){
memes fMeme = (memes)lv.getAdapter().getItem(i);
//mIsFavourite in my code it turns red
//what should I put after the item. to work?
if (item.mIsFavourite()) {
favoriteMemes.add(fMeme);
}
}
intent = new Intent(this, Favoritos.class);
intent.putExtra("favoritos", new Gson().toJson(favoriteMemes));
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Now finally activity in which we place the Favoritos.class
public class Favoritos extends AppCompatActivity {
ListView lv;
ArrayAdapter<memes> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
lv = findViewById(R.id.lv);
String memesString = getIntent().getStringExtra("favoritos");
memes[] fMemes = new Gson().fromJson(memesString,memes[].class);
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, fMemes);
lv.setAdapter(arrayAdapter);
}
}
Items are not displayed with this code.
I think my problem is in if (item.mIsFavorite ()) but I have no idea what to put here.
one more thing, on the second activity how would I remove the items?
and tbm could I recommend a good tutorial from SharedPreferences so I can use that case.
Thank you
Related
I have converted the contents of Textview texx; to a string where I can display it as an array however it displays the contents of textView before the doit() task has excecuted, the current output that appears on the screen is 'TextView', I want it to display the output of TextView texx; after it has finished its task. Any help would be greatly apreciated.
Im very new to android studio and java.
public class AppHome extends AppCompatActivity implements PopupMenu.OnMenuItemClickListener {
TextView texx;
private ArrayList<String> al;
private ArrayAdapter<String> arrayAdapter;
private int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_home);
new doit().execute();
texx= findViewById(R.id.text1);
String text = texx.getText().toString();
//String num = text;
String[] str = text.split(",");
final ArrayList al = new ArrayList<String>(Arrays.asList(str));
(Full code below)
```
public class AppHome extends AppCompatActivity implements PopupMenu.OnMenuItemClickListener {
TextView texx;
private ArrayList<String> al;
private ArrayAdapter<String> arrayAdapter;
private int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_home);
new doit().execute();
texx= findViewById(R.id.text1);
String text = texx.getText().toString();
//String num = text;
String[] str = text.split(",");
final ArrayList al = new ArrayList<String>(Arrays.asList(str));
arrayAdapter = new ArrayAdapter<>(this, R.layout.item, R.id.helloText, al );
SwipeFlingAdapterView flingContainer = findViewById(R.id.frame);
registerForContextMenu(flingContainer);
flingContainer.setAdapter(arrayAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
al.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(AppHome.this, "left", Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(AppHome.this, "right", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
al.add("XML ".concat(String.valueOf(i)));
arrayAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
}
});
// Optionally add an OnItemClickListener
/*
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
}
});
*/
}
public class doit extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
String words = "";
try {
Document doc = Jsoup.connect("https://screenscrape4top40.000webhostapp.com/").get();
words = doc.text();
} catch(Exception e) {
e.printStackTrace();
}
return words;
}
#Override
public void onPostExecute(String words) {
super.onPostExecute(words);
texx.setText(words);
}
}
public void showPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
popup.setOnMenuItemClickListener(this);
popup.inflate(R.menu.dropdown_menu1);
popup.show();
}
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
Toast.makeText(this, "Item 1 clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.item2:
Toast.makeText(this, "Item 2 clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.item3:
Toast.makeText(this, "Item 3 clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.item4:
Toast.makeText(this, "Item 4 clicked", Toast.LENGTH_SHORT).show();
return true;
default:
return false;
}
}
}
I have some records in list view, I want to update and delete these records when I long press on particular item of list. Like this structure
DBHelper1 DBHelper2 DBHelper3 DBHelper4 DBHelper5
DBHelper6
package com.example.loginproject.model;
public class Record {
String lead;
String name;
String mobile;
public Record(String lead, String name, String mobile) {
this.lead = lead;
this.name = name;
this.mobile = mobile;
}
public String getLead() {
return lead;
}
public Record(){}
public void setLead(String lead) {
this.lead = lead;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}}
public class MyAdapter extends BaseAdapter {
Context context;
ArrayList<Record> arrayList;
public MyAdapter(Context context,ArrayList<Record>arrayList){
this.context=context;
this.arrayList=arrayList;
}
#Override
public int getCount() {
return this.arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView= layoutInflater.inflate(R.layout.custom_list_view,null);
TextView textView1 =(TextView)convertView.findViewById(R.id.textview_leads);
TextView textView2 =(TextView)convertView.findViewById(R.id.textview_names);
TextView textView3 =(TextView)convertView.findViewById(R.id.textview_company);
Record record=arrayList.get(position);
textView1.setText(record.getLead());
textView2.setText(record.getName());
textView3.setText(record.getMobile());
return convertView;
}
}
public class Home extends AppCompatActivity {
TextView Name;
Button refresh,addlead;
DatabaseHelper databaseHelper;
SQLiteOpenHelper sqLiteOpenHelper;
SQLiteDatabase db;
ListView listView;
MyAdapter myAdapter;
ArrayList<Record>arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Name=(TextView)findViewById(R.id.Name);
addlead=(Button)findViewById(R.id.addlead);
refresh=(Button)findViewById(R.id.viewlead);
listView=(ListView)findViewById(R.id.list_view);
sqLiteOpenHelper=new DatabaseHelper(this);
db=sqLiteOpenHelper.getReadableDatabase();
databaseHelper=new DatabaseHelper(this);
arrayList=new ArrayList<>();
loaddatainlist();
registerForContextMenu(listView);
Name.setText(getIntent().getStringExtra(MainActivity.user));
refresh();
add_lead();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.mybutton) {
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setMessage("Are you really want to Logout ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"Logout Successfully",Toast.LENGTH_SHORT).show();
finish();
//startActivity(new Intent(Home.this,MainActivity.class));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();
}
return super.onOptionsItemSelected(item);
}
public void add_lead()
{
addlead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Home.this,Registration.class));
}
});
}
private void loaddatainlist()
{
arrayList=databaseHelper.getalldata();
myAdapter=new MyAdapter(this,arrayList);
listView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.listoption,menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.editoption:
{
startActivity(new Intent(Home.this, Update.class));
}
case R.id.deleteoption:
{
Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();
}
return true;
default:
return super.onContextItemSelected(item);
}
}
public void refresh()
{
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
startActivity(getIntent());
}
});
}
}
public class Update extends AppCompatActivity {
EditText lead,name,company,mobile,address;
Button update;
DatabaseHelper databaseHelper;
SQLiteDatabase dataBase;
ImageButton getrecord;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
databaseHelper=new DatabaseHelper(this);
lead=(EditText)findViewById(R.id.lead);
name=(EditText)findViewById(R.id.updatename);
company=(EditText)findViewById(R.id.updatecompany_name);
address=(EditText)findViewById(R.id.updateaddress);
mobile=(EditText)findViewById(R.id.updatemobile);
update=(Button)findViewById(R.id.update_button);
}
}
I displayed all the records which i stored in database but I can not update it.
I am going class by class to make the things easy to understand.
DatabaseHelper class:
I am not sure why you have used below section in onCreate() method:
If there is no specific purpose then you can remove it (you can comment for it's use).
Now in Complete your Record model with all the fields which you have used in Client table. Also make the class serialized if it is not. So the Record class will look like-
public class Record implements Serializable {
..
public Record(String sno, lead, String name, String mobile, String companyName, ...) {
this.sno = sno;
this.lead = lead;
this.name = name;
this.mobile = mobile;
this.companyName = companyName;
.
.
.
}
..
}
Back to db class. Change the update() method to -
public boolean updateClientInfo(Record record) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
//Updated code will be like
ContentValues contentValues = new ContentValues();
contentValues.put(Column21, record.getLead());
.
.
.
int count = sqLiteDatabase.update(Table2, contentValues, "SNO = ?", new String[] {record.getSno()});
return count > 0 ? true : false;
}
In getAllData() method to populate Record model list, pupulate all fields such as SNO etc in the updated Record model (as mentioned above with added fields).
Change the code for delete() method to-
public boolean deleteClientInfo(Record record) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
//Updated code will be
int count = sqLiteDatabase.update(Table2, "SNO = ?", new String[] {record.getSno()});
return count > 0 ? true : false;
}
Update getalldata() method in DB class to -
I have updated your Home activity class so that it will work perfectly for db refresh. You try to notice the differences basically in the following area-
refresh() -> updated, loaddatainlist() -> removed, createAdapter() -> added, refreshListFromDb() -> added, onCreate() updated, onReume() -> added.
public class Home extends AppCompatActivity {
TextView Name;
Button refresh, addlead;
DatabaseHelper databaseHelper;
SQLiteOpenHelper sqLiteOpenHelper;
SQLiteDatabase db;
ListView listView;
MyAdapter myAdapter;
ArrayList<Record> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Name = (TextView) findViewById(R.id.Name);
addlead = (Button) findViewById(R.id.addlead);
refresh = (Button) findViewById(R.id.viewlead);
listView = (ListView) findViewById(R.id.list_view);
sqLiteOpenHelper = new DatabaseHelper(this);
db = sqLiteOpenHelper.getReadableDatabase();
databaseHelper = new DatabaseHelper(this);
arrayList = new ArrayList<>();
createAdapter();
registerForContextMenu(listView);
Name.setText(getIntent().getStringExtra(MainActivity.user));
refresh();
add_lead();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.mybutton) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you really want to Logout ?").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Logout Successfully", Toast.LENGTH_SHORT).show();
finish();
// startActivity(new Intent(Home.this,MainActivity.class));
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
return super.onOptionsItemSelected(item);
}
public void add_lead() {
addlead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Home.this, Registration.class));
}
});
}
private void createAdapter() {
myAdapter = new MyAdapter(this, arrayList);
listView.setAdapter(myAdapter);
}
private void refreshListFromDb() {
arrayList = databaseHelper.getAllClientData(arrayList);
myAdapter.notifyDataSetChanged();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.listoption, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.editoption: {
startActivity(new Intent(Home.this, Update.class));
}
case R.id.deleteoption: {
Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();
}
return true;
default:
return super.onContextItemSelected(item);
}
}
public void refresh() {
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
refreshListFromDb();
}
});
}
#Override
public void onResume() {
super.onResume();
refreshListFromDb()
}
}
When you are calling Update class after longpress call the Intent as-
Intent intent = new Intent(this, Update.class);
intent.putExtra("parcel_record", recordModel); // record model of the index from array list where longpress is made.
startActivity(intent);
Fetch the record object in Update activity like this-
#Override
protected void onCreate(Bundle savedInstanceState) {
// Using getParcelableExtra(String key) method
Record record = (Record) getIntent().getParcelableExtra("parcel_record");
....
}
Now populate the fields such as name, mobile in update activity by taking from record model such as
editTextMobile.setText(record.getMobile());
Once user click on Update button, update the record model with the edited value from field such as -
record.setMobile(editTextMobile.getText().toString());
....
and call updateClientInfo(record) of DB helper class.
Hope the detail will help you to get your requirement.
Note: It's my suggestion, use a proper name for the variables and methods such as getingData() to getUserRecord() in DB class, insertData() to insertClientInfo() and so on.
try this:-
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// TODO Auto-generated method stub
Log.v("long clicked","pos: " + pos);
return true;
}
});
if you want to set onLongClick on an adapter item.then just do this**(in onBindViewHolder method of adapter)**:-
holder.lv.setOnItemLongClickListener(new OnItemLongClickListener() {
//your code here.i.e updating the database
}
When I click list item from search result, return to 0 position. How do I get original position from string?
My code is:
String.xml
<resources>
<string name="app_name">SearchViewList</string>
<string-array name="array_country">
<item>Alemania</item>
<item>Mexico</item>
<item>EUA</item>
<item>Argentina</item>
<item>Rusia</item>
<item>España</item>
</string-array>
</resources>
My code is:
MenuSearch.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/menuSearch"
android:title="Buscar"
android:icon="#android:drawable/ic_menu_search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="always"></item>
</menu>
My code is:
MainActivity.java
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView)findViewById(R.id.lista);
ArrayList<String> arrayCountry = new ArrayList<>(); arrayCountry.addAll(Arrays.asList(getResources().getStringArray(R.array.array_country)));
adapter = new ArrayAdapter<>(
MainActivityRespaldo2.this, android.R.layout.simple_list_item_1, arrayCountry);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView adapterView, View view, int posicion, long l) {
switch (posicion) {
case 0 :
Intent i0 = new Intent(getApplicationContext(), Alemania.class);
startActivity(i0);
break;
case 1 :
Intent i1 = new Intent(getApplicationContext(), Mexico.class);
startActivity(i1);
break;
case 2 :
Intent i2 = new Intent(getApplicationContext(), EUA.class);
startActivity(i2);
break;
case 3 :
Intent i3 = new Intent(getApplicationContext(), Argentina.class);
startActivity(i3);
break;
default:
Toast.makeText(getApplicationContext(), "Developing", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_buscar, menu);
MenuItem item = menu.findItem(R.id.menuBuscar);
SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
Please help me
Couple of day's ago I was doing the some project and digging on internet but I found the solution yesterday. In my way it may not be professional but it works very fine and help you.The concept is I will identify my products by their corresponding code and whenever any one searches it, the it will get its code and it will open the activity.
My adaptor class.
public class MainActivityAdapter extends RecyclerView.Adapter<MainActivityAdapter.Holderview>{
private List<Item> productlist;
private Context context;
public MainActivityAdapter(List<Item> productlist, Context context) {
this.productlist = productlist;
this.context = context;
}
#Override public Holderview onCreateViewHolder(ViewGroup parent, int viewType) {
View layout= LayoutInflater.from(parent.getContext()).
inflate(R.layout.customitem,parent,false);
return new Holderview(layout);
}
#Override public void onBindViewHolder(Holderview holder, final int position) {
holder.v_name.setText(productlist.get(position).getName());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
if (productlist.get(position).getCode()=="A")
{
context.startActivity(new Intent(context, one.class));
Toast.makeText(context, "Position is"+productlist.get(position).getName(), Toast.LENGTH_SHORT).show();
}
else if(productlist.get(position).getCode()=="B")
{
context.startActivity(new Intent(context, two.class));
Toast.makeText(context, "Position is"+productlist.get(position).getName(), Toast.LENGTH_SHORT).show();
}
else if(productlist.get(position).getCode()=="C")
{
context.startActivity(new Intent(context, three.class));
Toast.makeText(context, "Position is"+productlist.get(position).getName(), Toast.LENGTH_SHORT).show();
}
else if(productlist.get(position).getCode()=="D")
{
context.startActivity(new Intent(context, four.class));
Toast.makeText(context, "Position is"+productlist.get(position).getName(), Toast.LENGTH_SHORT).show();
}
else if(productlist.get(position).getCode()=="E")
{
context.startActivity(new Intent(context, five.class));
Toast.makeText(context, "Position is"+productlist.get(position).getName(), Toast.LENGTH_SHORT).show();
}
}
});
}
#Override public int getItemCount() {
return productlist.size();
}
public void setfilter(List<Item> listitem)
{
productlist=new ArrayList<>();
productlist.addAll(listitem);
notifyDataSetChanged();
}
class Holderview extends RecyclerView.ViewHolder
{
TextView v_name;
Holderview(View itemview)
{
super(itemview);
v_name = (TextView) itemView.findViewById(R.id.product_title);
}
}
public void SetFilter(ArrayList<Item> newList)
{
productlist= new ArrayList<>();
productlist.addAll(newList);
notifyDataSetChanged();
}
}
My MainActivity class note I have included my string array in main activity and I have added another array which named as Code it will help me to identify after search.
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
RecyclerView showrcy;
List<Item> productlists = new ArrayList<>();
MainActivityAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
productlists.add(new Item("MyproductOne", "A"));
productlists.add(new Item("MyproductTwo", "B"));
productlists.add(new Item("MyproductThree", "C"));
productlists.add(new Item("MyproductFour", "D"));
showrcy = (RecyclerView) findViewById(R.id.listshow);
showrcy.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
showrcy.setLayoutManager(linearLayoutManager);
adapter = new MainActivityAdapter(productlists, MainActivity.this);
showrcy.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.searchfile, menu);
MenuItem myActionMenuItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView) myActionMenuItem.getActionView();
searchView.setOnQueryTextListener(this);
return true;
}
private List<Item> filter(List<Item> pl, String query) {
query = query.toLowerCase();
final List<Item> filteredModeList = new ArrayList<>();
for (Item model : pl) {
final String text = model.getName().toLowerCase();
if (text.startsWith(query)) {
filteredModeList.add(model);
}
}
return filteredModeList;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
newText= newText.toLowerCase();
ArrayList<Item> newList= new ArrayList<>();
for (Item mylists: productlists)
{
String name= mylists.getName().toLowerCase();
if (name.contains(newText))
newList.add(mylists);
}
adapter.SetFilter(newList);
return true;
}
}
Finally My getter and setter class is as Item class it helps me to get and set Code and my product list.
public class Item {
private String name,code;
public Item(String name,String code) {
this.name = name;
this.code = code;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I have here an arraylist that is shown in a listview, when I give long click a dialog is displayed it contains the option of favorite that when selected the object is marked as true, how do I only display the items marked in my ActivityFavoritos?
MainActivity.class
public class MainActivity extends AppCompatActivity {
ListView lv;
MediaPlayer mp;
ArrayList<memes> item;
ArrayAdapter<memes> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
lv = findViewById(R.id.lv);
mp = new MediaPlayer();
item = new ArrayList<>();
//itens
item.add(new memes("Fique apertado sobre o meme para compartilhar", R.raw.sharebagui));
item.add(new memes("2 mil anos", R.raw.milanos));
item.add(new memes("Acelera jesus", R.raw.acelera_jesus));
item.add(new memes("Azideia", R.raw.asideia));
item.add(new memes("Acertou mizeravi", R.raw.mizeravi));
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, item);
lv.setAdapter(arrayAdapter);
//play audio
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
playSong(position);
}
});
//PROGRESS
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int position, long l) {
//PROGRESS
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Olá, Marilene!");
builder.setItems(Nomes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: // Delete
sendWhatsAppAudio(position);
break;
case 1: // Copy
item.get(position).setmIsFavourite(true);
break;
default:
break;
}
}
});
AlertDialog alertDialog = builder.create();
builder.show();
return true;
}
});
}
public void playSong(int songIndex) {
mp.reset();
mp = MediaPlayer.create(this, arrayAdapter.getItem(songIndex).getResId());
mp.start();
}
#Override
public void onDestroy() {
super.onDestroy();
mp.release();
}
}
memes.class
public class memes{
private String nome;
private int resID;
private Boolean mIsFavourite;
memes(String nome, int resID){
this.nome = nome;
this.resID = resID;
}
public String getNome(){
return nome;
}
int getResId(){
return resID;
}
#Override
public String toString(){
return nome;
}
public Boolean getmIsFavourite() {
return mIsFavourite;
}
public void setmIsFavourite(Boolean mIsFavouriteResource) {
this.mIsFavourite = mIsFavouriteResource;
}
}
this is my progress so far I am confused of what I should do in the favorite activity.
ActivityFavoritos.class
public class ActivityFavoritos {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_favoritos);
lv = findViewById(R.id.lvf);
if (list.get(position).getmIsFavourite()) {
//do want you want when its true
} else {
//do want your code when its false.
}
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, item);
lv.setAdapter(arrayAdapter);
}
}
In your memes class declare variable
private Boolean mIsFavourite;
And declare getter and setter method for same.
public Boolean getmIsFavourite() {
return mIsFavourite;
}
public void setmIsFavourite(Boolean mIsFavouriteResource) {
this.mIsFavourite = mIsFavouriteResource;
}
Now on Double click set value of that item to True
item.get(position).setmIsFavourite(true);
In your second Activity just check value of this by using getmIsFavourite()
EDIT :
To use this getmIsFavourite()
if(list.get(position).getmIsFavourite())
{
//do want you want when its true
}else{
//do want your code when its false.
}
Onclick and OnlongClick doesn't work, I am using AppCompatActivity to support KitKat. I am not sure why it's not working. Is it the adapter OR the view? I know I am using deprecated adapter, but I am using it for a purpose.
The code below:
public class MainActivity extends AppCompatActivity {
ActionMode mActionMode;
private CartDbAdapter dba;
private Cursor cursor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
databaseview();
}
else {
setContentView(R.layout.cart);
dba = new CartDbAdapter(this);
dba.open();
}
private void databaseview(){
cursor = dba.fetchAllBooks();
ListView listView = (ListView) findViewById(list);
startManagingCursor(cursor);
String [] from = new String[] {BookContract.TITLE , BookContract.AUTHORS };
int [] to = new int [] {android.R.id.text1 , android.R.id.text2 };
SimpleCursorAdapter databaseAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2, cursor, from, to);
listView.setAdapter(databaseAdapter);
listView.setOnLongClickListener(longListener);
listView.setOnClickListener(clickListener);
}
View.OnLongClickListener longListener = new View.OnLongClickListener() {
public boolean onLongClick(View view) {
if (mActionMode != null) {
return false;
}
mActionMode = MainActivity.this.startSupportActionMode(callback);
view.setSelected(true);
return true;
}
};
View.OnClickListener clickListener = new View.OnClickListener(){
public void onClick(View view) {
Intent viewIntent = new Intent(MainActivity.this, BookActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable(BookActivity.KEY, dba.fetchBook(view.getId()));
viewIntent.putExtras(bundle);
startActivity(viewIntent);
}
};
private ActionMode.Callback callback = new ActionMode.Callback() {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextbar_menu, menu);
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
mode.finish();
return true;
default:
return false;
}
}
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};
Thank you!
I just solved this issue by using setOnItemClickListener and setOnItemLongClickListener with ListView Adapter..
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Toast.makeText(arg0.getContext(), ((TextView)arg1).getText(), Toast.LENGTH_SHORT).show();
return false;
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View itemView, int index,
long id) {
}
});