I trying to change the way i open the contextmenu in my application,
Now, to open the contextmenu i need to long click on the item (in the listview), and its work perfectly.
I want to change that and add a button next to each row on the listview and by click on the button, the Context menu will open.
I added a ImageButton to rawlayout.xml (I see the button next to each row now) but i cannot get the button from the activity.
When i trying access the button, The app crashed with the message: java.lang.NullPointerException: Attempt to read from field 'android.widget.ImageButton com.grade.ido.grades.ListDataAdaptar$LayoutHandler.BUTTON' on a null object reference.
The current contextmenu happening in DataListActivity.java
Update 26/02/2016: I update the relevent codes:
I want that i could get the ImageButton for each row in the listview in the DataListActivity.java. but I get the NullPointerException error.
As you can see, in sortList function at DataListActivity, i declare the imageButton (I also tried to declare at the top of the activity, but i got the same null error).
When i set the onclicklistner in ListDataAdapter, I can access to every row imageButton in the listview, and popup a differnt toast for each, But i cannot create a new contextmenu.
Thre is an option to call the contextmenu found in DataListActivity from the onclick at listDataAdapter?
This is my DataListActivity.java:
package com.grade.ido.grades;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import java.text.DecimalFormat;
import java.util.Vector;
public class DataListActivity extends ActionBarActivity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
com.grade.ido.grades.CourseDbHelper courseDbHelper;
Cursor cursor;
com.grade.ido.grades.ListDataAdaptar listDataAdaptar;
Spinner sortSpinner;
Spinner yearSpinner;
Spinner semSpinner;
ArrayAdapter<String> sortAdapter;
ArrayAdapter<String> filterYearAdapter;
ArrayAdapter<String> filterSemAdapter;
private InterstitialAd mInterstitialAd;
private String tempGradeOld,tempGradeNew;
private String byYear,bySem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.grade.ido.grades.R.layout.update_course);
hideActionBar();
sortSpinner = (Spinner)findViewById(com.grade.ido.grades.R.id.sortSpinner);
yearSpinner = (Spinner)findViewById(R.id.yearSpinner);
semSpinner = (Spinner)findViewById(R.id.semSpinner);
String[] sortItems = new String[]{"Sort by","Course name","Year","Semester", "Grade", "Points"};
Vector<String> semItems = new Vector<>();
semItems.add("all");
sortAdapter = new ArrayAdapter<String>(this, R.layout.my_spinner_textview, sortItems);
filterYearAdapter = new ArrayAdapter<String>(this, R.layout.my_spinner_textview, new getData(getApplicationContext()).getYearItems());
filterSemAdapter = new ArrayAdapter<String>(this, R.layout.my_spinner_textview, semItems);
sortSpinner.setAdapter(sortAdapter);
semSpinner.setAdapter(filterSemAdapter);
yearSpinner.setAdapter(filterYearAdapter);
Bundle extras = getIntent().getExtras();
bySem="all";
byYear="all";
courseDbHelper = new com.grade.ido.grades.CourseDbHelper(getApplicationContext());
sqLiteDatabase = courseDbHelper.getReadableDatabase();
// System.out.println(extras.getString("SPINNER"));
int spinnerPosition = sortAdapter.getPosition(extras.getString("SORT_SPINNER"));
sortSpinner.setSelection(spinnerPosition);
System.out.println("extrras data " + extras);
if (extras==null){
Log.e("DATALISTACTIVITY", "extras null");
}
else {
Log.e("DATALISTACTIVITY", extras.toString());
}
TextView tAVR = (TextView) findViewById(R.id.avrAllCourse);
double tempAvr = new getData(getApplicationContext()).getTaverage();
int tempSum = new getData(getApplicationContext()).getSum();
if (tempSum==0){
tAVR.setText(Double.toString(0));
}
else {
tAVR.setText(new DecimalFormat("##.##").format(tempAvr));
}
cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo._ID);
sortSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo._ID);
sortList(byYear,bySem);
} else if (position == 1) {
cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo.COURSE);
sortList(byYear,bySem);
}
else if (position == 2) {
cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo.YEAR);
sortList(byYear,bySem);
}
else if (position == 3) {
cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo.SEMESTER);
sortList(byYear,bySem);
}
else if (position == 4) {
cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo.GRADE);
sortList(byYear,bySem);
}
else if (position == 5) {
cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo.POINTS);
sortList(byYear,bySem);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
listView = (ListView) findViewById(R.id.list_view);
View header = getLayoutInflater().inflate(R.layout.header, null);
listView.addHeaderView(header);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("XXXXXXXXXXXXXXX");
AdRequest adRequest = new AdRequest.Builder()
.build();
mInterstitialAd.loadAd(adRequest);
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
AdView mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(adRequest);
}
public static int getLocationSpinner(String arr[], String a){
int loc=-1;
for (int i=0;i<arr.length;i++){
if (arr[i].equals(a)){
loc=i;
}
}
return loc;
}
public void sortList(String byYear,String bySem){
registerForContextMenu(listView);
listDataAdaptar = new ListDataAdaptar(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(listDataAdaptar);
ImageButton button= (ImageButton) findViewById(R.id.settingsButton);
if (!cursor.moveToFirst()){
}
else {
do {
String year,semester,course,points,grade;
year = cursor.getString(0);
semester = cursor.getString(1);
course = cursor.getString(2);
points = cursor.getString(3);
grade = cursor.getString(4);
butt
addTheCourse(year, semester, course, points, grade,button);
}
while (cursor.moveToNext());
}
}
public void addTheCourse(String year,String semester,String course,String points,String grade,ImageButton but){
DataProvider dataProvider = new DataProvider(year, semester, course, points, grade,but);
listDataAdaptar.add(dataProvider);
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuInflater inflater = getMenuInflater();
if (((AdapterView.AdapterContextMenuInfo)menuInfo).position == 0) {
return;
}
inflater.inflate(R.menu.menu_data_list, menu);
menu.setHeaderTitle("Options");
}
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
final int mySelectedRowIndex = info.position-1;
com.grade.ido.grades.DataProvider raw2 = (com.grade.ido.grades.DataProvider) listDataAdaptar.getItem(mySelectedRowIndex);
switch (item.getItemId()) {
case R.id.update_item:
//case 1 code .....
return true;
case R.id.delete_item:
//case 2 code .....
return true;
case R.id.change_grade:
//case 3 code .....
return super.onOptionsItemSelected(item);
}
}
public void onBackPressed() {
startActivity(new Intent(this, MainActivity.class));
}
private void hideActionBar() {
//Hide the action bar only if it exists
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
}
}
this is my ListDataAdapter.java
package com.grade.ido.grades;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.grade.ido.grades.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ido on 08/08/2015.
*/
public class ListDataAdaptar extends ArrayAdapter{
List list = new ArrayList();
SQLiteDatabase sqLiteDatabase;
com.grade.ido.grades.CourseDbHelper courseDbHelper;
public ListDataAdaptar(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler{
TextView YEAR,SEMESTER,COURSE,POINTS,GRADE;
ImageButton BUTTON;
}
#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(com.grade.ido.grades.R.layout.row_layout,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.YEAR = (TextView)row.findViewById(com.grade.ido.grades.R.id.textYear);
layoutHandler.SEMESTER = (TextView)row.findViewById(com.grade.ido.grades.R.id.textSemester);
layoutHandler.COURSE = (TextView)row.findViewById(com.grade.ido.grades.R.id.textCourse);
layoutHandler.POINTS = (TextView)row.findViewById(com.grade.ido.grades.R.id.textPoints);
layoutHandler.GRADE = (TextView)row.findViewById(com.grade.ido.grades.R.id.textGrade);
layoutHandler.BUTTON= (ImageButton) row.findViewById(R.id.settingsButton);
row.setTag(layoutHandler);
}
else{
layoutHandler = (LayoutHandler) row.getTag();
}
final com.grade.ido.grades.DataProvider dataProvider = (com.grade.ido.grades.DataProvider) this.getItem(position);
layoutHandler.YEAR.setText(dataProvider.getYear());
layoutHandler.SEMESTER.setText(dataProvider.getSemester());
layoutHandler.COURSE.setText(dataProvider.getCourse());
layoutHandler.POINTS.setText(dataProvider.getPoints());
layoutHandler.GRADE.setText(dataProvider.getGrade());
// layoutHandler.BUTTON.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// ContextMenu cm;
//
// Toast.makeText(getContext(), dataProvider.getCourse(),
// Toast.LENGTH_LONG).show();
}
});
return row;
}
}
row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<TextView
android:layout_width="40dp"
android:layout_height="wrap_content"
android:id="#+id/textGrade"
android:text="Grade"
android:gravity="center"
android:textColor="#000000"/>
<TextView
android:layout_width="30dp"
android:layout_height="wrap_content"
android:id="#+id/textPoints"
android:text="Points"
android:gravity="center"
android:textColor="#000000"/>
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:id="#+id/textCourse"
android:text="Course"
android:gravity="center"
android:textColor="#000000"/>
<TextView
android:layout_width="60dp"
android:layout_height="wrap_content"
android:id="#+id/textSemester"
android:text="Semester"
android:gravity="center"
android:textColor="#000000"/>
<TextView
android:layout_width="30dp"
android:layout_height="wrap_content"
android:id="#+id/textYear"
android:text="Year"
android:gravity="center"
android:textColor="#000000"/>
<ImageButton
android:layout_width="32dp"
android:layout_height="32dp"
android:id="#+id/settingsButton"
android:src="#drawable/settings"
android:nestedScrollingEnabled="false" />
</LinearLayout>
Related
I have a problem when i use setOnItemClickListener to get the id of clicked item in GridView return null. I try to do that because I want when a user click an item I retrieve data from db then represent it in another fragment so there is a solution to get id or there are another way to deal with that. thanks a lot.
I use an Adapter:
The fragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import com.example.mohamed.osarelkheir.Adapters.Section_Adapter;
import com.example.mohamed.osarelkheir.First_Launch;
import com.example.mohamed.osarelkheir.Models.Section_Model;
import com.example.mohamed.osarelkheir.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentChange;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Sections_Fragment extends Fragment {
private GridView Dep_grid_View; //object from GridView (list) -Session Fragment
private List<Section_Model> Dep_list; //Data Model Object
private Section_Adapter section_adapter; //Adapter Object
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;
private String Dep_id;
private String item;
private DocumentSnapshot lastVisible; //to print the last ....
//Empty Contractor
public Sections_Fragment() {
}
private FragmentManager fragmentManager;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.section_fragment, container, false);
Dep_grid_View = view.findViewById(R.id.gridSection);
Dep_list = new ArrayList<>();
firebaseAuth = FirebaseAuth.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
// myList = Arrays.asList(section_models); //he create its own array list to view it as a templet data cooooool
section_adapter = new Section_Adapter(getContext(), Dep_list);
Dep_grid_View.setAdapter(section_adapter);
//First Query
Query firstQuery = firebaseFirestore.collection("Department");
firstQuery.addSnapshotListener(getActivity(), new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#javax.annotation.Nullable QuerySnapshot snapshots, #javax.annotation.Nullable FirebaseFirestoreException e) {
// Toast.makeText(getActivity(), "No", Toast.LENGTH_SHORT).show();
for (DocumentChange doc : snapshots.getDocumentChanges()) {
// Toast.makeText(getActivity(), "NoO", Toast.LENGTH_SHORT).show();
if (doc.getType() == DocumentChange.Type.ADDED) {
// Toast.makeText(getActivity(), "No00", Toast.LENGTH_SHORT).show();
Dep_id = doc.getDocument().getId();
Toast.makeText(getActivity(), "Id" + Dep_id, Toast.LENGTH_SHORT).show();
// <<<<<<<<<<<<<GET DATA from DB >>>>>>>>>>>>>>>>>>
Section_Model section_model = doc.getDocument().toObject(Section_Model.class).withId(Dep_id);
//<<<<<<<<<<<<<<<then Put it in object of BlogList >>>>>>>>>>>>>>
Dep_list.add(section_model);
section_adapter.notifyDataSetChanged();
}
}
}
});
Dep_grid_View.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//it's return null
item = Dep_grid_View.getItemAtPosition(i).toString();
printadminview();
}
});
return view;
}
void printadminview() {
Intent intent = new Intent(getContext(), First_Launch.class);
intent.putExtra("value", 3);
intent.putExtra("Dep_ID", item );
// Toast.makeText(getActivity(), "pos " + pos, Toast.LENGTH_SHORT).show();
getContext().startActivity(intent);
}
}
The .xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<SearchView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#drawable/item_background_manage"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginStart="5dp"
android:layout_weight="1"
android:queryHint="search"/>
</LinearLayout>
<GridView
android:id="#+id/gridSection"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:verticalSpacing="5dp"
android:horizontalSpacing="3dp"
android:layout_margin="8dp" />
</LinearLayout>
Adapter class
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
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.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.mohamed.osarelkheir.First_Launch;
import com.example.mohamed.osarelkheir.Models.Section_Model;
import com.example.mohamed.osarelkheir.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.List;
public class Section_Adapter extends ArrayAdapter<Section_Model> { //1
private Context mContext;
private List<Section_Model> data;
public Section_Adapter(Context mContext,List<Section_Model> data) {//2
super(mContext,R.layout.item_section,data);
this.mContext = mContext;
this.data = data;
}
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
View row = convertView;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(R.layout.item_section, parent, false);
holder = new ViewHolder();
holder.txtSectionName = row.findViewById(R.id.sectionName);
holder.imageView = row.findViewById(R.id.imageSection);
holder.imageIc = row.findViewById(R.id.ic_sec);
row.setTag(holder);
row.setTag(new Integer(position));
} else {
holder = (ViewHolder) row.getTag();
}
setView(holder, position);
Section_Model model = getItem(position);
String id = model.getId();
Intent intent=new Intent(mContext, First_Launch.class);
intent.putExtra("value",1);
intent.putExtra("DepartmentId", id);
mContext.startActivity(intent);
return row;
}
private void setView(ViewHolder holder, int position) {
Section_Model section_model = data.get(position);
holder.txtSectionName.setText(section_model.getSection_name());
String downlaodUriImage = section_model.getSection_image();
String DownloadUriLogo = section_model.getSection_icon();
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.logo);
Glide.with(mContext).applyDefaultRequestOptions(requestOptions).load(downlaodUriImage).into(holder.imageView);
Glide.with(mContext).load(DownloadUriLogo).apply(requestOptions.override(40,40)).into(holder.imageIc);
}
static class ViewHolder {
TextView txtSectionName;
ImageView imageView;
ImageView imageIc;
}
}
To only get the id, you just need to use the following code lines.
firstQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
String documentId = document.getId();
Log.d(TAG, documentId);
}
}
}
});
There is no need to use addSnapshotListener unless you need to get data in real-time. The output will be:
CIcg...
E30F...
rXY9...
If you need to get the corresponding id of item that was clicked, simply use getItem(position);
According to your comment, the simplest way would be to add a new property in your Section_Model class named id in which to can store the id of each particular document. So everytime you add a new document, that document will contain the id. Using getItem(position) will return an object of Section_Model class. See the code below:
Section_Model model = getItem(position);
String id = model.getId();
So model.getId() will return the id of the object that was set when you have added that document to the database.
I want to get new updated list in Favourite activity,but instead i'm getting no items in favourite list.List getting values from sharedpreference but not updating to recycler view.
DiseaseAdapter
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by admin on 12/4/2017.
*/
public class DiseaseAdapter extends RecyclerView.Adapter<DiseaseAdapter.DiseaseAdapterViewHolder> {
List <String> data;
Context ctx;
SharedPreference sharedPreference;
DiseaseAdapter(List <String> data, Context ctx){
this.data=data;
notifyDataSetChanged();
this.ctx=ctx;
sharedPreference = new SharedPreference();
}
#Override
public DiseaseAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view= inflater.inflate(R.layout.activity_listview,parent,false);
return new DiseaseAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(DiseaseAdapterViewHolder holder, int position) {
final String title=data.get(position);
holder.textView1.setText(title);
if (checkFavoriteItem(title)) {
holder.imageButton.setImageResource(R.drawable.star_colour);
holder.imageButton.setTag("red");
} else {
holder.imageButton.setImageResource(R.drawable.ic_action_name);
holder.imageButton.setTag("grey");
}
}
#Override
public int getItemCount() {
return data.size();
}
class DiseaseAdapterViewHolder extends RecyclerView.ViewHolder {
TextView textView1;
ImageView imageButton;
public DiseaseAdapterViewHolder(View itemView) {
super(itemView);
textView1=(TextView) itemView.findViewById(R.id.textView);
imageButton=(ImageView)itemView.findViewById(R.id.imgbtn_favorite);
}
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(String checkProduct) {
boolean check = false;
List<String> favorites = sharedPreference.getFavorites(ctx);
if (favorites != null) {
for (String product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
}
MainActivity
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity{
RecyclerView simpleListView;
static Context ctx;
String diseaseList[];
SharedPreference sharedPreference;
DiseaseAdapter da;
List<String> newDiseaseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx=this;
sharedPreference = new SharedPreference();
diseaseList= new String[]{"Abscess",
"Allergies",
"Amnesia",
"Anemia",
"Andropause",
"Angina",
"Weight Loss"};
Arrays.sort(diseaseList);
newDiseaseList = Arrays.asList(diseaseList);
simpleListView= (RecyclerView)findViewById(R.id.simpleListView);
LinearLayoutManager lm=new LinearLayoutManager(MainActivity.this);
simpleListView.setLayoutManager(lm);
/* DividerItemDecoration di=new DividerItemDecoration(MainActivity.this,lm.getOrientation());
simpleListView.addItemDecoration(di);*/
da=new DiseaseAdapter(newDiseaseList,ctx);
simpleListView.setAdapter(da);
simpleListView.setHasFixedSize(true);
simpleListView.addOnItemTouchListener(
new RecyclerItemClickListener(ctx, simpleListView ,new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx, newDiseaseList.get(position));
Toast.makeText(ctx,
"add to favourites",
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx, newDiseaseList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
Toast.makeText(ctx,
"removed from favourites",
Toast.LENGTH_SHORT).show();
}
}
#Override public void onLongItemClick(View view, int position) {
}
})
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
Intent i=new Intent(this,Favourite.class);
this.startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
}
SharedPreference.java
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<String> favorites) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<String>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<String> getFavorites(Context context) {
SharedPreferences settings;
List<String> favorites ;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
String [] favoriteItems = (gson.fromJson(jsonFavorites,String [].class));
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<String>(favorites);
} else
return null;
return (ArrayList<String>) favorites;
}
}
Favourite.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
public class Favourite extends AppCompatActivity {
RecyclerView favoriteList;
SharedPreference sharedPreference;
List<String> favorites;
DiseaseAdapter diseaseAdapter;
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
ctx=this;
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(ctx);
favoriteList = (RecyclerView)findViewById(R.id.favListView);
if (favorites == null) {
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (favorites.size() == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
if (favorites != null) {
diseaseAdapter = new DiseaseAdapter(favorites,ctx);
diseaseAdapter.notifyDataSetChanged();
favoriteList.setAdapter(diseaseAdapter);
favoriteList.invalidate();
favoriteList.addOnItemTouchListener(
new RecyclerItemClickListener(ctx, favoriteList ,new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
ImageView button = (ImageView) view
.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx,
favorites.get(position));
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
/* diseaseAdapter.remove(favorites
.get(position));*/
diseaseAdapter.notifyItemRemoved(position);
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
}
#Override public void onLongItemClick(View view, int position) {
}
})
);
}
}
}
public void showAlert(String title, String message) {
if (ctx != null) {
AlertDialog alertDialog = new AlertDialog.Builder(ctx)
.create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// activity.finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.admin.fav.MainActivity">
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/simpleListView"
>
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
activity_listview.xml
<?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="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="20dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:textColor="#434b3e"
android:text=""/>
<ImageView
android:id="#+id/imgbtn_favorite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="3dp"
android:background="#null"
/>
</RelativeLayout>
activity_favourite.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.admin.fav.Favourite">
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/favListView"
>
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
You are missing setLayoutManager() in Favourite.java.
Try calling NotifyDataSetChanged() instead of NotifyItemRemoved() or NotifyItemAdded(). These methods did not work for me either. You just won't get the animations of items being added and removed but you can add your own animations to do the trick!
You should use Room Database to store lists and handle them as it is much easier and makes a lot of sense. SharedPreferences is recommended for storing values such as integers and booleans, not whole lists.
Why is this app is not working properly when I click on the each item of the recycle view Toast of the position of the item appears but when I click each item(cardview) to open a new activity app crash. I don't know what is wrong.
GalleryFragment.java
package com.example.kiran.cr7;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import java.util.ArrayList;
/** * A simple {#link Fragment} subclass. */ public class GalleryFragment extends Fragment implements Adapter.OnCardClickListner {
public GalleryFragment() {
// Required empty public constructor
}
private RecyclerView mrecycleview;
private CardView mcardview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
mrecycleview = (RecyclerView)view.findViewById(R.id.recycle_view);
mcardview = (CardView)view.findViewById(R.id.card_view);
//improve performance
mrecycleview.setHasFixedSize(true);
LinearLayoutManager manager = new LinearLayoutManager(view.getContext());
mrecycleview.setLayoutManager(manager);
ArrayList<Item> itemlist = dummies();
//set adapter // Adapter adapter = new Adapter(view.getContext(),itemlist); // mrecycleview.setAdapter(adapter); // adapter.setOnCardClickListner(this);
Adapter adapter = new Adapter(view.getContext(),itemlist);
mrecycleview.setAdapter(adapter);
adapter.setOnCardClickListner(this);
return view;
}
private ArrayList<Item> dummies() {
ArrayList<Item> list = new ArrayList<>();
for (int i = 0; i < 6; i++) {
if (i == 0) {
Item item = new Item();
item.id = i;
item.text = "RonaldoPhoto" + (i);
item.img = "http://wallpapercave.com/wp/sIggTrG.jpg";
list.add(item);
} else if (i == 1) {
Item item = new Item();
item.id = i;
item.text = "RonaldoPhoto" + (i);
item.img = "http://i2.wp.com/www.footballwood.com/wp-content/uploads/2015/01/Ronaldo-Best-Wallpapers.jpg";
list.add(item);
} else if (i == 2) {
Item item = new Item();
item.id = i;
item.text = "RonaldoPhoto" + (i);
item.img = "http://www.magazinefuse.com/wp-content/uploads/2015/09/7-i476725-1024x640.jpg";
list.add(item);
} else if (i == 3) {
Item item = new Item();
item.id = i;
item.text = "RonaldoPhoto" + (i);
item.img = "https://i.ytimg.com/vi/SwHv6xGGBBQ/maxresdefault.jpg";
list.add(item);
}else if (i == 4) {
Item item = new Item();
item.id = i;
item.text = "RonaldoPhoto" + (i);
item.img = "https://i.ytimg.com/vi/WrCfkR4Qcns/maxresdefault.jpg";
list.add(item);
}
else if (i == 5) {
Item item = new Item();
item.id = i;
item.text = "RonaldoPhoto" + (i);
item.img = "http://images.latinpost.com/data/images/full/101477/cristiano-ronaldo-real-madrid.jpg";
list.add(item);
}
}
return list;
}
#Override
public void OnCardClicked(View view, int position) {
Log.d("OnClick", "Card Position" + position);
Toast.makeText(getContext(),"click"+position,Toast.LENGTH_SHORT).show();
Intent in= new Intent(view.getContext(),Detail.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(in);
} }
Adapter.java
package com.example.kiran.cr7;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder>{
private RecyclerView mRecyclerView;
private Context context;
private ArrayList<Item> itemlist;
OnCardClickListner onCardClickListner;
public Adapter(Context context, ArrayList<Item> itemlist){
this.context = context;
this.itemlist = itemlist;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.from(parent.getContext()).inflate(R.layout.cardview,parent,false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycle_view);
ViewHolder viewholder = new ViewHolder(view);
return viewholder;
}
//bind views with data
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final Item item = itemlist.get(position);
//get element form your dataset at this position
//replace the contents of the view with that element
Picasso.with(context)
.load(item.img)
.placeholder(R.drawable.fern)
.error(android.R.drawable.stat_notify_error)
.into(holder.cardimage);
holder.cardtext.setText(item.text);
holder.card_view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onCardClickListner.OnCardClicked(v,position);
Intent in = new Intent(v.getContext(), Detail.class);
in.putExtra("item",item);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//context.startActivity(in);
}
});
}
#Override
public int getItemCount() {
if(itemlist != null){
return itemlist.size();
}
return 0;
}
//provide the reference to the views for each data item
//ViewHolder class
//since it is static it uses only single memory so protect memory leak : a design pattern for android
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public CardView card_view;
public TextView cardtext;
public ImageView cardimage;
//connects which view belongs to which layout
public ViewHolder(View itemView) {
super(itemView);
card_view = (CardView)itemView.findViewById(R.id.card_view);
cardtext = (TextView)itemView.findViewById(R.id.cardtext);
cardimage = (ImageView)itemView.findViewById(R.id.cardimage);
}
#Override
public void onClick(View view) {
}
}
public interface OnCardClickListner {
void OnCardClicked(View view, int position);
}
public void setOnCardClickListner(OnCardClickListner onCardClickListner) {
this.onCardClickListner = onCardClickListner;
}
}
Detail
package com.example.kiran.cr7;
import android.app.DownloadManager; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class Detail extends AppCompatActivity implements Adapter.OnCardClickListner {
private ImageView detailimage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
detailimage = (ImageView)findViewById(R.id.detailimage);
}
#Override
public void OnCardClicked(View view, int position) {
Log.d("OnClick", "Card Position" + position);
if(getIntent().getSerializableExtra("item") != null){
Item i = (Item)getIntent().getSerializableExtra("item");
Picasso.with(this)
.load(i.img)
.placeholder(R.drawable.fern)
.error(android.R.drawable.stat_notify_error)
.into(detailimage);
}
} }
You don't need to use OnCardClicked in detail.java activity. Use serializable to send data from one activity from another. Use OnCardClicked.onBindViewHolder to send data from one activity to another.
package com.example.kiran.cr7;
import android.app.DownloadManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
public class Test extends Activity {
private ImageView detailimage;
private Button download;
DownloadManager downloadManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
download = (Button) findViewById(R.id.Download);
detailimage = (ImageView) findViewById(R.id.detailimage);
final Animation animAlpha = AnimationUtils.loadAnimation(this,R.anim.anim_alpha);
if (getIntent().getSerializableExtra("item") != null) {
final Item i = (Item) getIntent().getSerializableExtra("item");
Picasso.with(this)
.load(i.img)
.resize(500,600)
.placeholder(R.drawable.fern)
.error(android.R.drawable.stat_notify_error)
.into(detailimage);
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
//Toast.makeText(Test.this, "Network Connection available", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Test.this, "No Network Connection", Toast.LENGTH_LONG).show();
}
download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
view.startAnimation(animAlpha);
downloadManager =(DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(i.img);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);
}
});
}
}
}
I am Trying to Display the Contact From Phone to the ListView(Which is used in a Fragment)..... I have Tried Putting a SearchView to Filter Data from ListView.....
Search View Does Not Filter Data ....
Pls Help ...I Am badly Stuck...
ScreenShot of App having SearchView over List View Showing Contact Details....
https://drive.google.com/file/d/0B8sFN35Zdhnfa0RtVEJKc2V2WG8/view?usp=sharing
https://drive.google.com/file/d/0B8sFN35ZdhnfWTljaTRWaGY3c1E/view?usp=sharing
contactfragment.xml , GetContactAdapter.java , Contact_Fragment3.java
are three different files..
**contractfragment.xml**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<SearchView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/searchContactLIST"
android:queryHint="Search...."
android:clickable="true"
>
</SearchView>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lists"
android:scrollbarStyle="outsideOverlay"
/>
</LinearLayout>
**GetContactAdapter.java**
package com.example.cosmic.zumi_test;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class GetContactAdapter extends ArrayAdapter<String> implements Filterable {
String[] phone = {};
String[] names = {};
int[] img = {};
Context c;
LayoutInflater inflater;
public class Viewholder {
TextView names;
TextView address;
ImageView img;
}
public GetContactAdapter(Context context, String[] names, String[] add) {
super(context, R.layout.customcontactlist, names);
this.c = context;
this.names = names;
this.phone = add;
this.img = img;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.customcontactlist, null);
}
Viewholder viewholder = new Viewholder();
viewholder.names = (TextView) convertView.findViewById(R.id.contact_name);
viewholder.address = (TextView) convertView.findViewById(R.id.contact_no);
viewholder.img = (ImageView) convertView.findViewById(R.id.image_contactlist);
//ASSIGN DATA
viewholder.img.setImageResource(R.drawable.com_facebook_button_icon_blue);
viewholder.names.setText(names[position]);
viewholder.address.setText(phone[position]);
return convertView;
}
}
**Contact_Fragment3.java**
package com.example.cosmic.zumi_test;
import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filterable;
import android.widget.ListView;
import android.widget.Toast;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
/**
* Created by cosmic on 31/12/16.
*/
public class Contact_FRAGMENT3 extends Fragment {
private Uri uriContact;
private String contactID;
private ListView lstNames;
private GetContactAdapter adapter;
// Request code for READ_CONTACTS. It can be any number > 0.
private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
private android.widget.SearchView search;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.contactfragment, container, false);
this.lstNames = (ListView) v.findViewById(R.id.lists);
this.search = (android.widget.SearchView) v.findViewById(R.id.searchContactLIST);
// Read and show the contacts
showContacts();
return v;
}
private void showContacts() {
// Check the SDK version and whether the permission is already granted or not.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
//After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
} else {
// Android version is lesser than 6.0 or the permission is already granted.
List<String> contacts = getContactNames();
// String[] arr_contact=contacts.to
List<String> contacts_no = getContactNo();
String[] strarray = new String[contacts.size()];
contacts.toArray(strarray);
String[] strarray2 = new String[contacts_no.size()];
contacts_no.toArray(strarray2);
adapter = new GetContactAdapter(getContext(), strarray, strarray2);
lstNames.setAdapter(adapter);
search.setOnQueryTextListener(new android.widget.SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return true;
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted
showContacts();
} else {
Toast.makeText(getContext(), "Until you grant the permission, we cannot display the names", Toast.LENGTH_SHORT).show();
}
}
}
private List<String> getContactNames() {
List<String> contacts = new ArrayList<>();
List<String> number = new ArrayList<>();
// Get the ContentResolver
ContentResolver cr = getActivity().getContentResolver();
// Get the Cursor of all the contacts
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
// Move the cursor to first. Also check whether the cursor is empty or not.
if (cursor.moveToFirst()) {
// Iterate through the cursor
do {
// Get the contacts name
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String numbers = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
number.add(numbers);
contacts.add(name);
} while (cursor.moveToNext());
}
// Close the curosor
cursor.close();
return contacts;
}
private List<String> getContactNo() {
List<String> number = new ArrayList<>();
// Get the ContentResolver
ContentResolver cr = getActivity().getContentResolver();
// Get the Cursor of all the contacts
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
// Move the cursor to first. Also check whether the cursor is empty or not.
if (cursor.moveToFirst()) {
// Iterate through the cursor
do {
// Get the contacts name
// String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String numbers = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
number.add(numbers);
// contacts.add(name);
} while (cursor.moveToNext());
}
// Close the curosor
cursor.close();
return number;
}
}
try this code if it might help you
public class SearchViewFilterMode extends Activity implements SearchView.OnQueryTextListener {
private SearchView mSearchView;
private ListView mListView;
private final String[] mStrings = Cheeses.sCheeseStrings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.searchview_filter);
mSearchView = (SearchView) findViewById(R.id.search_view);
mListView = (ListView) findViewById(R.id.list_view);
mListView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
mStrings));
mListView.setTextFilterEnabled(true);
setupSearchView();
}
private void setupSearchView() {
mSearchView.setIconifiedByDefault(false);
mSearchView.setOnQueryTextListener(this);
mSearchView.setSubmitButtonEnabled(true);
mSearchView.setQueryHint("Search Here");
}
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
mListView.clearTextFilter();
} else {
mListView.setFilterText(newText.toString());
}
return true;
}
public boolean onQueryTextSubmit(String query) {
return false;
}
}
I am creating this layout where a list of text is displayed with a "delete" button besides each item. I am not able to get the layout right i guess. Can i get some help on this?
Here is the layout file for the 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"
android:orientation="vertical" >
<ListView
android:id="#+id/locationList"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/delete"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFFFFFFF"
android:text="Delete"
android:onClick="onClickDelete"/>
</ListView>
</RelativeLayout>
Here is the java code:
package com.android.ict.seneca.androidpocketguide;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class Websites extends Activity
implements AdapterView.OnItemClickListener{
private final String CLASS_NAME = "Websites";
DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm");
String date;
String location;
String name;
int counter;
List listName;
private SharedPreferences savedState;
private ListView listView;
private List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_websites);
listName= new ArrayList();
String app_name = "//sdcard//LocoLog.txt";
//int counter = 0, flag = 0;
String temp = "";
savedState = getSharedPreferences( "quantitySaved", MODE_PRIVATE );
rowItems = new ArrayList<RowItem>();
counter = savedState.getInt("counter", -1 );
if(counter!=-1)
{
for (int i = 1; i <= counter; i++)
{
String na;
String da;
String lo;
na = "name" + i;
da = "date" + i;
lo = "location" + i;
name = savedState.getString(na, "na" );
date = savedState.getString(da, "da" );
location = savedState.getString(lo, "lo" );
//Toast.makeText(this, "The data: "+name + " " + location + " " + date,Toast.LENGTH_LONG).show();
listName.add(new RowItem(name, location, date, counter));
}
}
else
{
Toast.makeText(this, "No locations saved yet",Toast.LENGTH_LONG).show();
}
listView = (ListView) findViewById(R.id.locationList);
listView.setAdapter( new CustomListAdapter(this, R.layout.list_item, listName ) );
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String cities = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(this, cities, Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(view.getContext(), SingleListItem.class);
myIntent.putExtra("product", cities);
startActivityForResult(myIntent, 0);
}
public void onClickDelete(View view)
{
//String cities = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(this, "delete ", Toast.LENGTH_LONG).show();
//rowItems.remove(position);
}
public void onClickAdd(View view)
{
Toast.makeText(this, "add ", Toast.LENGTH_LONG).show();
}
public void onStart() {
super.onStart();
Log.d(CLASS_NAME, "onStart invoked!");
}
public void onPause() {
super.onPause();
Log.d(CLASS_NAME, "onPause invoked!!");
}
public void onResume() {
super.onResume();
Log.d(CLASS_NAME, "onResume invoked!!");
}
public void onStop() {
super.onStop();
Log.d(CLASS_NAME, "onStop invoked!!!");
}
public void onDestroy() {
super.onDestroy();
Log.d(CLASS_NAME, "onDestroy INVOKED!!!");
}
public void onRestart() {
super.onRestart();
Log.d(CLASS_NAME, "onRestart invoked!!");
}
}
You cannot add Button like this in listview.Your button should be in separate layout.
mainLayout.xml
<ListView
android:id="#+id/locationList"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
and your listview items layout i.e button in your case
buttons.xml
<Button
android:id="#+id/delete"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFFFFFFF"
android:text="Delete"
android:onClick="onClickDelete"/>
and then in your Activity
listview.setAdapter(YourAdapter());
and then in your adapter's getView method()
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderItem viewHolder;
if(convertView==null){
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(R.layout.buttons, parent, false);
viewHolder = new ViewHolderItem();
viewHolder.button = convertView.findViewById(R.id.button);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolderItem) convertView.getTag();
}
viewHolder.button.setOnClickListener(new View.onClickListener(){
public void onClick(){
//handle your on click.
}
});
return convertView;
}
Viewholder class
static class ViewHolderItem{
private Button button;
}
Read this for further information http://www.androidhive.info/2011/10/android-listview-tutorial