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;
}
}
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 am having trouble loading images from internet into gridView. I am using Fresco for image loading. When I run the app, it doesn't crash but does not show the images in gridView. Also, there is no error shown in logcat. I am new to Android development. Thanks in advance!
GalleryFragment.java
package com.example.android.tabswithswipes;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import com.example.android.tabswithswipes.Utils.GridImageAdapter;
import com.example.android.tabswithswipes.Utils.UniversalImageLoader;
import com.facebook.drawee.view.SimpleDraweeView;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
/**
* Created by Chaitanya Shiva on 08-05-2018.
*/
public class GalleryFragment extends Activity {
private GridView gridView;
private ImageView galleryImage;
private ProgressBar mProgressBar;
private Spinner directorySpinner;
private Context mContext = GalleryFragment.this;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_gallery);
galleryImage = (SimpleDraweeView)findViewById(R.id.galleryImageView);
gridView = (GridView)findViewById(R.id.gridView);
directorySpinner = (Spinner)findViewById(R.id.spinnerDirectory);
mProgressBar = (ProgressBar)findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
ImageView closeGallery = (ImageView)findViewById(R.id.closeGallery);
closeGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
TextView nextScreen = (TextView) findViewById(R.id.tvNext);
nextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Uri uri = Uri.parse("https://www.gstatic.com/webp/gallery/4.sm.jpg");
galleryImage.setImageURI(uri);
tempGridSetup();
}
private void setUpImageGrid(ArrayList<String> imgURLs){
GridView gridView = (GridView)findViewById(R.id.gridView);
GridImageAdapter adapter = new GridImageAdapter(mContext, R.layout.layout_grid_imageview,"", imgURLs);
gridView.setAdapter(adapter);
}
private void tempGridSetup(){
ArrayList<String> imgURLs = new ArrayList<>();
imgURLs.add("https://www.gstatic.com/webp/gallery/4.sm.jpg");
imgURLs.add("https://www.gstatic.com/webp/gallery3/1.sm.png");
imgURLs.add("https://cdn.pixabay.com/photo/2018/05/10/09/07/bleeding-heart-3387085_1280.jpg");
imgURLs.add("https://images.idgesg.net/images/article/2017/08/android_robot_logo_by_ornecolorada_cc0_via_pixabay1904852_wide-100732483-large.jpg");
imgURLs.add("https://www.androidcentral.com/sites/androidcentral.com/files/styles/xlarge_wm_brw/public/article_images/2018/03/android-p-logo-pixel-2-xl-5.jpg?itok=DB93lUGS");
imgURLs.add("https://www.androidcentral.com/sites/androidcentral.com/files/styles/xlarge_wm_brw/public/article_images/2018/03/android-p-virtual-notch.jpg?itok=EnKJzDgF");
imgURLs.add("https://www.androidcentral.com/sites/androidcentral.com/files/styles/xlarge_wm_brw/public/article_images/2018/03/samsung-galaxy-s9-plus-black-4.jpg?itok=bTitZlS_");
imgURLs.add("https://www.extremetech.com/wp-content/uploads/2017/03/smiling-android.jpg");
imgURLs.add("https://rimblogs.files.wordpress.com/2016/04/marshmallowman.png?w=800");
imgURLs.add("https://www.androidcentral.com/sites/androidcentral.com/files/topic_images/2015/android-apps-topic.png");
imgURLs.add("https://images.idgesg.net/images/article/2017/11/android-security-100741557-large.jpg");
setUpImageGrid(imgURLs);
}
}
GridImageAdapter.java
package com.example.android.tabswithswipes.Utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.example.android.tabswithswipes.R;
import com.facebook.drawee.view.SimpleDraweeView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import java.util.ArrayList;
/**
* Created by Chaitanya Shiva on 12-05-2018.
*/
public class GridImageAdapter extends ArrayAdapter<String>{
private Context mContext;
private LayoutInflater mInflater;
private int layoutResource;
private String mAppend;
private ArrayList<String> imgURLs;
public GridImageAdapter(Context context, int layoutResource, String append, ArrayList<String> imgURLs) {
super(context, layoutResource, imgURLs);
this.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mContext = context;
this.layoutResource = layoutResource;
this.mAppend = append;
this.imgURLs = imgURLs;
}
private static class ViewHolder{
SimpleDraweeView image;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
/*
Viewholder build pattern (Similar to recyclerview)
*/
final ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(layoutResource, parent, false);
holder = new ViewHolder();
holder.image = (SimpleDraweeView) convertView.findViewById(R.id.gridImageView);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
String imgURL = getItem(position);
holder.image.setImageURI(imgURL);
return convertView;
}
}
layout_grid_imageview.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="match_parent">
<com.facebook.drawee.view.SimpleDraweeView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/gridImageView"
android:scaleType="centerCrop"/>
</RelativeLayout>
Here you forgot to hide the progressbar. You need to hide it when the image is loaded. You can do the following :
val controllerBuilder = Fresco.newDraweeControllerBuilder()
controllerBuilder.setUri(url)
controllerBuilder.oldController = drawee.controller
controllerBuilder.controllerListener = object : BaseControllerListener<ImageInfo>() {
override fun onFinalImageSet(id: String?, imageInfo: ImageInfo?, animatable: Animatable?) {
super.onFinalImageSet(id, imageInfo, animatable)
holder.mProgressBar.setVisibility(VISIBLE.GONE);
}
}
holder.image.controller = controllerBuilder.build()
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);
}
});
}
}
}
My program is designed to search the database for the specific name entered, then the program will only display the row of the specific name. However, my code is unable to display the specific data. I have tried many kind of ways but it is unable to solve my problem. My php code is as below:
<?php
$con = mysql_connect('mysql17.000webhost.com', 'a2634311_minzhe', 'MZRules0118');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("a2634311_gdp", $con);
$result = mysql_query("SELECT * FROM groupdesign");
while($row = mysql_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);
?>
My activity code is as below:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
public class PatientLocation extends ActionBarActivity {
private ListView PatientLocationListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
this.PatientLocationListView = (ListView) this.findViewById(R.id.listView4);
new Location().execute(new API_Connector());
}
public void setListAdapter(JSONArray jsonArray) {
SharedPreferences settings = getSharedPreferences("myprefrences", Context.MODE_PRIVATE);
String name = settings.getString("name", "");
this.PatientLocationListView.setAdapter(new PatientAdapter(jsonArray,name, this));
}
private class Location extends AsyncTask<API_Connector, Long, JSONArray> {
#Override
protected JSONArray doInBackground(API_Connector... params) {
//it is executed on Background thread
return params[0].GetPatientLocation();
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
// check for null
if (jsonArray != null) {
// only pass the array to adapter if it is not null
setListAdapter(jsonArray);
} else {
Toast.makeText(PatientLocation.this, "Null Array returned", Toast.LENGTH_SHORT).show();
}
}
}
}
class PatientAdapter extends BaseAdapter {
private JSONArray dataArray;
private Activity activity;
String pname;
private static LayoutInflater inflater = null;
public PatientAdapter(JSONArray jsonArray, String name, Activity a) {
this.dataArray = jsonArray;
this.activity = a;
this.pname = name;
inflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.dataArray.length();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String patientname,patientlocation;
//set up convert view if it is null
ListCell cell = new ListCell();
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_position, null);
cell.patient_name = (TextView) convertView.findViewById(R.id.textView30);
cell.patient_location = (TextView) convertView.findViewById(R.id.textView31);
convertView.setTag(cell);
}
else {
cell = (ListCell) convertView.getTag();
}
//change the data of the cell
try {
for(int i=0;i<dataArray.length();i++) {
JSONObject jsonObject = this.dataArray.getJSONObject(i);
if(pname == jsonObject.getString("Name")) {
patientname = jsonObject.getString("Name");
patientlocation = jsonObject.getString("Location");
cell.patient_name.setText(patientname);
cell.patient_location.setText(patientlocation);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
return convertView;
}
private class ListCell {
private TextView patient_name;
private TextView patient_location;
}
}
Where is WHERE clause in your query in php code? You need to set some conditions to match specific name in query like if you want to search 'abcd' then your query should be SELECT * FROM groupdesign WHERE column_name = "abcd". This will return records which contanis value "abcd" from your database
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>