how to set event for grid view by imageview - java

I'm newbie and just study Java around 1 month.
i'm trying to create group picture by grid view and if i click any picture then show for user alert dialog ask user want to delete picture or not. But somehow when i try to set event for grid view by image. i can't start up app. can help me find where is crash cause app can't start up.
package com.example.hi.gridviewhinhanh;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<Danhsachhinhanh> manghinhanh;
HinhanhAdapter arrayAdapter;
GridView gridView;
ImageView imgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = findViewById(R.id.gridview);
manghinhanh = new ArrayList<>();
manghinhanh.add(new Danhsachhinhanh(R.drawable.chupanh));
manghinhanh.add(new Danhsachhinhanh(R.drawable.goidien));
manghinhanh.add(new Danhsachhinhanh(R.drawable.photoshop));
manghinhanh.add(new Danhsachhinhanh(R.drawable.quality));
manghinhanh.add(new Danhsachhinhanh(R.drawable.secutiry));
manghinhanh.add(new Danhsachhinhanh(R.drawable.signuptoday));
arrayAdapter = new HinhanhAdapter(MainActivity.this, manghinhanh);
gridView.setAdapter(arrayAdapter);
imgView = findViewById(R.id.imageviewHinhanh);
imgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder hopthoai = new AlertDialog.Builder(MainActivity.this);
hopthoai.setTitle("Do you want to delete");
hopthoai.setMessage("Please confirm");
hopthoai.setIcon(R.mipmap.ic_launcher);
hopthoai.setCancelable(false);
hopthoai.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
hopthoai.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "You choose No", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
package com.example.hi.gridviewhinhanh;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
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.BaseAdapter;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
public class HinhanhAdapter extends BaseAdapter {
Context context;
ArrayList<Danhsachhinhanh> danhsachhinhanhArrayList;
public HinhanhAdapter (Context context, ArrayList<Danhsachhinhanh> danhsachhinhanhArrayList){
this.context = context;
this.danhsachhinhanhArrayList = danhsachhinhanhArrayList;
}
#Override
public int getCount() {
return danhsachhinhanhArrayList.size();
}
#Override
public Object getItem(int position) {
return danhsachhinhanhArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.dong_item_gridviewhinhanh,null);
ImageView imageView = convertView.findViewById(R.id.imageviewHinhanh);
Danhsachhinhanh danhsachhinhanh = (Danhsachhinhanh) getItem(position);
imageView.setImageResource(danhsachhinhanh.getHinhanh());
return convertView;
}
}

place you imageView clickListener in Adapter's getView() and check it again.
Becuase your imageView does not exist there. For more information read about adapter and recycleview.

Related

Recycler view does not show up

I am having problem with my recyclerview I builed an app in android studio which suppose to create contacts and watch their cards using cardview and recyclerview the issue is that the list of contacts is not shown instead I am seeing a white screen
so here is my code:
import android.net.sip.SipSession;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
/*Connect contact list to
*
* */
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {
private List<Contact> contacts;
public ContactAdapter(List<Contact> contacts) {
this.contacts = contacts;
}
interface ContactsListener{
void onContactClicked(int position,View view);
}
ContactsListener listener;
public void setListener(ContactsListener listener){
this.listener=listener;
}
public class ContactViewHolder extends RecyclerView.ViewHolder {
ImageView contactpicture;
TextView contactname;
TextView contactphone;
TextView contactemail;
public ContactViewHolder(View itemview) {
super(itemview);
contactpicture = itemview.findViewById(R.id.card_image);
contactphone = itemview.findViewById(R.id.contact_email);
contactphone = itemview.findViewById(R.id.contact_phone);
contactname = itemview.findViewById(R.id.contact_name);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null)
listener.onContactClicked(getAdapterPosition(), view);
}
});
}
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent,int viewType){
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.contact_layout,parent,false);
ContactViewHolder holder=new ContactViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ContactViewHolder holder,int position){
Contact contact=contacts.get(position);
holder.contactpicture.setImageBitmap(contact.getPhoto());
holder.contactname.setText(contact.getName());
holder.contactphone.setText(contact.getPhone());
holder.contactemail.setText(contact.getEmail());
}
#Override
public int getItemCount(){
return contacts.size();
}
}
package com.example.b_safe;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
/*Define the list of contacts*/
public class ContactsList extends Activity {
#Override
protected void onCreate(#Nullable Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.show_contacts_activity);//לבדוק שזה מתקיים
RecyclerView recyclerview=findViewById(R.id.contacts_list);
recyclerview.setHasFixedSize(true);
recyclerview.setLayoutManager(new LinearLayoutManager( this));//צריך להוסיף this
ContactManager manager=ContactManager.getInstance(this);
ContactAdapter adapter=new ContactAdapter(manager.getContacts());
recyclerview.setAdapter(adapter);
adapter.setListener(new ContactAdapter.ContactsListener() {
#Override
public void onContactClicked(int position, View view) {
}
});
}
}
package com.example.b_safe;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
/*Adds new member to the contacts list
*
*
* */
public class AddContactActivity extends AppCompatActivity{
Bitmap bitmap;
EditText nameEt,phone_numberEt,emailEt;
ImageView img;
final int CAMERA_REQUEST=1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_contact_activity);
nameEt=findViewById(R.id.name_input);
phone_numberEt=findViewById(R.id.phone_input);
emailEt=findViewById(R.id.email_input);
img=findViewById(R.id.photo_result);
Button takepicture=findViewById(R.id.take_pic);
takepicture.setOnClickListener(new View.OnClickListener() {//Activation
#Override
public void onClick(View v) {
Intent camera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera,CAMERA_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==CAMERA_REQUEST&&resultCode==RESULT_OK){ //checks if results where properly
bitmap=(Bitmap)data.getExtras().get("data");
img.setImageBitmap(bitmap);//saving as contact's photo
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {//Load menu type
getMenuInflater().inflate(R.menu.contact_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {//fulfill actions
switch(item.getItemId()){
case R.id.action_save:
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Please confirm")
.setMessage("Would you like to save the following contact?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Contact contact=new Contact(nameEt.getText().toString(),phone_numberEt.getText().toString(),emailEt.getText().toString(),bitmap);
ContactManager manager=ContactManager.getInstance(AddContactActivity.this);
manager.addContact(contact);//Manager saved data
//Data zeroing
nameEt.setText("");
phone_numberEt.setText("");
emailEt.setText("");
img.setImageBitmap(null);
}})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(AddContactActivity.this,"The conatct saved",Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(AddContactActivity.this,"The conatct saved",Toast.LENGTH_SHORT).show();
}
}).show();
break;
case R.id.action_back:
finish();
}
return super.onOptionsItemSelected(item);//Loads activity
}
}
AdapterActivity is the subclass adapter AddContactActivity creates new contacts and the problem is with the ContactsList activity which holds the list and does not show up

Deleting item from listview behaving strange

I have a listview that extends base adapter. There is a delete button on every list item. When the delete button is clicked then the list item should be deleted. But when I try to do so listview behaves strangely. The delete button is causing the main problem. Sometimes the list is becoming double and sometimes app is crashing. I am trying to add a delete button to the item of the listview. When someone clicks on the button then the list item will be deleted and it will delete the item also from firebase.
I am trying to achieve this.
Sorry for my bad English. Advance thanks for your help.
package com.owoshopkeeperpanel.adapters;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.cepheuen.elegantnumberbutton.view.ElegantNumberButton;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.owoshopkeeperpanel.Interface.ItemClickListener;
import com.owoshopkeeperpanel.Model.Cart;
import com.owoshopkeeperpanel.Prevalent.Prevalent;
import com.owoshopkeeperpanel.R;
import java.util.ArrayList;
public class CartListAdapter extends BaseAdapter {
private Context mCtx;
private ArrayList<Cart> cartList;
final DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("Cart List");
public CartListAdapter(Context mCtx, ArrayList<Cart> cartList) {
this.mCtx = mCtx;
this.cartList = cartList;
}
#Override
public int getCount() {
return cartList.size();
}
#Override
public Object getItem(int position) {
return cartList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Cart cart = cartList.get(position);
if(convertView==null) {
LayoutInflater layoutInflater = (LayoutInflater) mCtx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.cart_items_sample, null);
}
ImageView delete = convertView.findViewById(R.id.cart_item_delete);
ImageView cart_product_image = convertView.findViewById(R.id.cart_product_image);
TextView cart_product_name = convertView.findViewById(R.id.cart_product_name);
TextView cart_product_quantity = convertView.findViewById(R.id.cart_product_quantity);
TextView cart_product_price = convertView.findViewById(R.id.cart_product_price);
ElegantNumberButton cart_item_change_button = convertView.findViewById(R.id.cart_item_change_btn);
Glide.with(mCtx).load(cart.getProduct_image()).into(cart_product_image);
cart_product_name.setText(cart.getProduct_name());
cart_product_quantity.setText(cart.getProduct_price()+" × "+cart.getNeeded_quantity());
double product_total_price = Double.parseDouble(cart.getProduct_price()) * Double.parseDouble(cart.getNeeded_quantity());
cart_product_price.setText("৳ "+String.valueOf(product_total_price));
cart_item_change_button.setNumber(cart.getNeeded_quantity());
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mCtx);
alertDialogBuilder.setMessage("Are you sure you want to remove this item from cart ?");
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
cartListRef.child(Prevalent.currentOnlineUser.getPhone())
.child(String.valueOf(cart.getProduct_id()))
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(mCtx, String.valueOf(cartList.size()), Toast.LENGTH_LONG).show();
cartList.remove(cart);
notifyDataSetChanged();
}
}
});
}
});
alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
return convertView;
}
}

Android with Firebase : Trying to implement RecycleView with CardView but can't retrieve RecycleView item position?

I'm a beginner, try to make a RecycleView layout with some information retrieve from Firebase database (in MemberFragment.java). In my code RecycleView layout with retrieve information from fire base database is worked but I can't retrieve item list position and can't be used for different massage display with different item list selected / clicked by user can any one help me how can I do it.
my code is:-
package np.com.rotaractnepalapp;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
import np.com.rotaractnepalapp.Interface.ItemClickListener;
import np.com.rotaractnepalapp.Model.Member;
import np.com.rotaractnepalapp.ViewHolder.MemberViewHolder;
public class MemberFragment extends Fragment {
View memFragment;
RecyclerView listofMembers;
RecyclerView.LayoutManager memLayoutManger;
FirebaseRecyclerAdapter<Member, MemberViewHolder> memAdapter;
FirebaseDatabase database;
DatabaseReference members;
public static MemberFragment newInstance(){
MemberFragment memberFragment = new MemberFragment();
return memberFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = FirebaseDatabase.getInstance();
members = database.getReference("ClubKNE");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
memFragment = inflater.inflate(R.layout.fragment_member,container,false);
TextView title = (TextView) memFragment.findViewById(R.id.txtClubNameTitle);
title.setText("RAC Kathmandu North-East");
listofMembers = (RecyclerView) memFragment.findViewById(R.id.memLists);
listofMembers.setHasFixedSize(true);
memLayoutManger = new LinearLayoutManager(container.getContext());
listofMembers.setLayoutManager(memLayoutManger);
loadMember();
return memFragment;
}
private void loadMember() {
memAdapter = new FirebaseRecyclerAdapter<Member, MemberViewHolder>(
Member.class,
R.layout.mem_layout,
MemberViewHolder.class,
members
) {
#Override
protected void populateViewHolder(MemberViewHolder viewHolder, Member model, int position) {
viewHolder.memDesignation.setText(model.getMemDesignation());
viewHolder.memName.setText(model.getMemName());
viewHolder.memProfession.setText(model.getMemProfession());
viewHolder.memEmail.setText(model.getMemEmail());
Picasso.with(getActivity())
.load(model.getMemImage())
.into(viewHolder.memImage);
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(view.getContext());
LayoutInflater factory = LayoutInflater.from(view.getContext());
view = factory.inflate(R.layout.member_info_layout, null);
alertDialog.setView(view);
alertDialog.setNegativeButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
});
}
};
memAdapter.notifyDataSetChanged();
listofMembers.setAdapter(memAdapter);
}
}
To get the position of an item, there are two solutions. One would be:
Member member = listMemenbers.get(position);
If you are using a list of Member objects. And second:
Member member = memAdapter.getItem(position);
In which case you are getting the position of the item directly from the adapter.
You can simply use position variable i.e int position it will show the position of card or any other other value

How to use StringArrays in a Custom ListView Adapter [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying use a StringArray to display items in a ListView with a custom Adapter.
But it does not work.
package ir.safarbazha.safarbazha.Acts;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.view.AbsSavedState;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.text.Format;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import javax.xml.datatype.DatatypeConstants;
import ir.safarbazha.safarbazha.Core.adapter.DrawerCustomListAdapter;
import ir.safarbazha.safarbazha.Core.app.AppController;
import ir.safarbazha.safarbazha.R;
import static ir.safarbazha.safarbazha.R.id.content_frame;
import static ir.safarbazha.safarbazha.R.id.toolbar;
public class HomeAct extends AppCompatActivity {
ActionBar homeActionbar;
String[] draweritems;
List<String> drawerItems;
int homeDrawerMenuItemsNumber=1;
DrawerCustomListAdapter drawerCustomListAdapter;
DrawerLayout homeDLayout;
ListView homeDrawerListView;
ImageView mainToolbarMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Localize...
if (!Locale.getDefault().getLanguage().equals("fa")){
String languageToLoad = "fa";
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.act_about);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
setContentView(R.layout.act_home);
homeDLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
homeDrawerListView=(ListView)findViewById(R.id.drawer_lv);
//Set Custom ToolBar...
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
homeActionbar=getSupportActionBar();
final LayoutInflater inflator = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.toolbar, null);
homeActionbar.setCustomView(v);
homeActionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
//Set Custom ToolBar Objects...
//MainToolBar Menu Image Object...
mainToolbarMenu=(ImageView)findViewById(R.id.nav_drawer_menu);
mainToolbarMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (homeDLayout.isDrawerOpen(GravityCompat.START))
homeDLayout.closeDrawer(GravityCompat.START);
else homeDLayout.openDrawer(GravityCompat.START);
}
});
//Set Custom Home Navigation Drawer...
draweritems= getResources().getStringArray(R.array.main_titles);
drawerItems=new ArrayList<String>(Arrays.asList(draweritems));
drawerCustomListAdapter=new DrawerCustomListAdapter(this,draweritems);
homeDrawerListView.setAdapter(drawerCustomListAdapter);
// homeDrawerListView.setAdapter(new ArrayAdapter<String>(
// this,R.layout.drawer_list_row,homeDrawerMenuItems));
// homeDrawerListView.setAdapter(new ArrayAdapter<String>(
// this,android.R.layout.simple_list_item_1,homeDrawerMenuItems));
homeDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedItem=getResources().getStringArray(R.array.main_titles)[position];
Toast.makeText(getBaseContext(),"برروی "+selectedItem+"کلیک شد!",Toast.LENGTH_SHORT).show();
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
package ir.safarbazha.safarbazha.Core.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import ir.safarbazha.safarbazha.R;
public class DrawerCustomListAdapter extends BaseAdapter{
public Context context;
public List<String> drawerItems;
private static LayoutInflater inflater=null;
public void drawerCustomListViewItemRow(
Context context,List<String> drawerItems
){
this.context=context;
this.drawerItems=drawerItems;
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return drawerItems.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return drawerItems.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (vi == null)
vi = inflater.inflate(R.layout.drawer_list_row, null);
TextView title = (TextView) vi.findViewById(R.id.drawer_lv_title);
title.setText(drawerItems.get(position));
ImageView icon=(ImageView)vi.findViewById(R.id.drawer_lv_icon);
icon.setImageResource(R.drawable.ic_menu_left);
return vi;
}
/*
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.drawer_list_row, null);
TextView title = (TextView)vi.findViewById(R.id.drawer_lv_title); // title
ImageView icon=(ImageView)vi.findViewById(R.id.drawer_lv_icon); // thumb image
// Setting all values in listview
title.setText(R.string.app_name);
icon.setImageResource(R.drawable.ic_account_circle);
return vi;
}
*/
}
My Android Studio says that the problem is in HomeAct, where I typed: (this,draweritems);
You added void here, therefore creating a method, not a constructor. Constructors have no return type.
Remove it
public **void** drawerCustomListViewItemRow(
Context context,List<String> drawerItems
){
this.context=context;
this.drawerItems=drawerItems;
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
Also capitalize the D for your class name from drawerCustomListViewItemRow to instead DrawerCustomListAdapter
And use the List of drawerItems, not the array draweritems when you create the adapter. Probably best to only store one or the other, not both anyway.
you have to add a constructor to your adapter class
change you'r drawerCustomListViewItemRow method name to this:
public DrawerCustomListAdapter(Context context, List<string> drawerItems)
and one more thing is that you have to either change String[] draweritems; in HomeAct to List<string> draweritems; or change the adapter List to string arary
I have modified your code. Please check the difference. Your DrawerCustomListAdapter constructor was not ok.
package ir.safarbazha.safarbazha.Acts;
import android.content.Context; import android.content.Intent; import
android.content.pm.ActivityInfo; import
android.content.res.Configuration; import android.os.Bundle; import
android.support.design.widget.FloatingActionButton; import
android.support.design.widget.Snackbar; import
android.support.v4.view.AbsSavedState; import
android.support.v4.view.GravityCompat; import
android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.widget.DrawerLayout; import
android.support.v7.app.ActionBar; import
android.support.v7.app.AlertDialog; import
android.support.v7.app.AppCompatActivity; import
android.support.v7.widget.Toolbar; import android.view.Gravity; import
android.view.LayoutInflater; import android.view.View; import
android.widget.AdapterView; import android.widget.ArrayAdapter; import
android.widget.ImageView; import android.widget.ListView; import
android.widget.Toast;
import java.lang.reflect.Field; import
java.lang.reflect.InvocationHandler; import java.text.Format; import
java.util.ArrayList; import java.util.Arrays; import
java.util.Comparator; import java.util.List; import java.util.Locale;
import javax.xml.datatype.DatatypeConstants;
import ir.safarbazha.safarbazha.Core.adapter.DrawerCustomListAdapter;
import ir.safarbazha.safarbazha.Core.app.AppController; import
ir.safarbazha.safarbazha.R;
import static ir.safarbazha.safarbazha.R.id.content_frame; import
static ir.safarbazha.safarbazha.R.id.toolbar;
public class HomeAct extends AppCompatActivity {
ActionBar homeActionbar;
String[] draweritems;
List<String> drawerItems;
int homeDrawerMenuItemsNumber = 1;
DrawerCustomListAdapter drawerCustomListAdapter;
DrawerLayout homeDLayout;
ListView homeDrawerListView;
ImageView mainToolbarMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Localize...
if (!Locale.getDefault().getLanguage().equals("fa")) {
String languageToLoad = "fa";
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.act_about);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
setContentView(R.layout.act_home);
homeDLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
homeDrawerListView = (ListView) findViewById(R.id.drawer_lv);
//Set Custom ToolBar...
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
homeActionbar = getSupportActionBar();
final LayoutInflater inflator = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.toolbar, null);
homeActionbar.setCustomView(v);
homeActionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
//Set Custom ToolBar Objects...
//MainToolBar Menu Image Object...
mainToolbarMenu = (ImageView) findViewById(R.id.nav_drawer_menu);
mainToolbarMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (homeDLayout.isDrawerOpen(GravityCompat.START))
homeDLayout.closeDrawer(GravityCompat.START);
else homeDLayout.openDrawer(GravityCompat.START);
}
});
//Set Custom Home Navigation Drawer...
draweritems = getResources().getStringArray(R.array.main_titles);
drawerItems = new ArrayList<String>(Arrays.asList(draweritems));
drawerCustomListAdapter = new DrawerCustomListAdapter(this, draweritems);
homeDrawerListView.setAdapter(drawerCustomListAdapter);
// homeDrawerListView.setAdapter(new ArrayAdapter<String>(
// this,R.layout.drawer_list_row,homeDrawerMenuItems));
// homeDrawerListView.setAdapter(new ArrayAdapter<String>(
// this,android.R.layout.simple_list_item_1,homeDrawerMenuItems));
homeDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = getResources().getStringArray(R.array.main_titles)[position];
Toast.makeText(getBaseContext(), "برروی " + selectedItem + "کلیک شد!", Toast.LENGTH_SHORT).show();
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
} }
package ir.safarbazha.safarbazha.Core.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import ir.safarbazha.safarbazha.R;
public class DrawerCustomListAdapter extends BaseAdapter {
public Context context;
public List<String> drawerItems;
private static LayoutInflater inflater = null;
public void DrawerCustomListAdapter(
Context context, List<String> drawerItems
) {
this.context = context;
this.drawerItems = drawerItems;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return drawerItems.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return drawerItems.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (vi == null)
vi = inflater.inflate(R.layout.drawer_list_row, null);
TextView title = (TextView) vi.findViewById(R.id.drawer_lv_title);
title.setText(drawerItems.get(position));
ImageView icon = (ImageView) vi.findViewById(R.id.drawer_lv_icon);
icon.setImageResource(R.drawable.ic_menu_left);
return vi;
}
/*
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.drawer_list_row, null);
TextView title = (TextView)vi.findViewById(R.id.drawer_lv_title); // title
ImageView icon=(ImageView)vi.findViewById(R.id.drawer_lv_icon); // thumb image
// Setting all values in listview
title.setText(R.string.app_name);
icon.setImageResource(R.drawable.ic_account_circle);
return vi;
}
*/ }

using bitmap with custom spinner

I used this tutorial to make a custom spinner but now I'm having a java.lang.OutOfMemoryError: Failed to allocate a 95976012 byte allocation with 16777120 free bytes and 31MB until OOMerror. I am aware that I should use bitmaps I just don't know how to include the bitmapFactory in my CustomAdapter. I have already compressed my images to sizes less than 16kb and put them in the mipmap folder because they are icons. I have also already tried
<application
android:largeHeap="true"
</application>
Here's my code :
MainActivity.java
package com.kathure.flags;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import static android.R.attr.id;
import static android.graphics.BitmapFactory.*;
import static java.security.AccessController.getContext;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String[] countryNames= {
"Kenya" , "Malawi", "Nigeria", "Rwanda", "Tanzania", "Uganda"
};
int [] flags = {
R.mipmap.kenyamin,R.mipmap.malawimin, R.mipmap.nigeriamin, R.mipmap.rwandamin, R.mipmap.tanzaniamin, R.mipmap.ugandamin
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
spin.setOnItemSelectedListener(this);
CustomAdapter customAdapter=new CustomAdapter(getApplicationContext(),flags,countryNames);
spin.setAdapter(customAdapter);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), countryNames[i], Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
CustomAdapter.java
package com.kathure.flags;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by kathure on 28/09/16.
*/
public class CustomAdapter extends BaseAdapter {
Context context;
int flags[];
String[] countryNames;
LayoutInflater inflter;
public CustomAdapter(Context applicationContext, int[] flags, String[] countryNames) {
this.context = applicationContext;
this.flags = flags;
this.countryNames = countryNames;
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return flags.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.custom_spinner_items, null);
ImageView icon = (ImageView) view.findViewById(R.id.imageView);
TextView names = (TextView) view.findViewById(R.id.textView);
icon.setImageResource(flags[i]);
names.setText(countryNames[i]);
return view;
}
}

Categories

Resources