I want a popup in my android - android

I want a pop like this when i click an item in the list. In the popupmenu i should not be able to increase my height above 7 ft and 0 inch and shouldnt decrease my height below 3 ft and 0 inch.
This is my activity
package com.example.shivnandan.fit;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity1 extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener
{
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");
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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
/////////////////////////////////////////////////////////
listView = (ListView) findViewById(R.id.listView2);
final ListViewItem[] items = new ListViewItem[5];
for (int i = 0; i < items.length; i++)
{
if (i == 0)
{
items[i] = new ListViewItem("White " + i, CustomAdapter.TYPE_WHITE); //mainactivity
}
else if (i == 1)
{
items[i] = new ListViewItem( "Black " + i, CustomAdapter.TYPE_BLACK ); //1
}
else if (i == 2)
{
items[i] = new ListViewItem("EVEN " + i, CustomAdapter.TYPE_ODD); //2
}
else if (i == 3)
{
items[i] = new ListViewItem("EVEN " + i, CustomAdapter.TYPE_EVEN); //3
}
else
{
items[i] = new ListViewItem("EVEN " + i, CustomAdapter.TYPE_FOUR); //4
}
/* else
{
items[i] = new ListViewItem( "odd"+i,CustomAdapter.TYPE_WHITE);
}*/
}
CustomAdapter customAdapter = new CustomAdapter(this, R.id.text, items);
listView.setAdapter(customAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView adapterView, View view, int i, long l)
{
if (i == 0)
{
openDialogManager();
}
}
});
}
public void openDialogManager()
{
final TextView tv3 = (TextView)findViewById(R.id.hometext);
final CharSequence[] items = {"Male", "Female"};
new AlertDialog.Builder(MainActivity1.this)
.setTitle("Gender")
.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which)
{
case 0:
// Toast.makeText( MainActivity1.this, "male ", Toast.LENGTH_SHORT).show();
tv3.setText("Male");
dialog.dismiss();
break;
case 1:
// Toast.makeText(MainActivity1.this, "female ", Toast.LENGTH_SHORT).show();
tv3.setText("Female");
dialog.dismiss();
break;
}
dialog.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
})
.show();
}
public void openDialogManagerr()
{
final TextView tv3 = (TextView)findViewById(R.id.hometext);
final CharSequence[] items = {"Male", "Female"};
new AlertDialog.Builder(MainActivity1.this)
.setTitle("Gender")
.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which)
{
case 0:
// Toast.makeText( MainActivity1.this, "male ", Toast.LENGTH_SHORT).show();
tv3.setText("Male");
dialog.dismiss();
break;
case 1:
// Toast.makeText(MainActivity1.this, "female ", Toast.LENGTH_SHORT).show();
tv3.setText("Female");
dialog.dismiss();
break;
}
dialog.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
})
.show();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public void onBackPressed()
{
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START))
{
drawer.closeDrawer(GravityCompat.START);
}
else
{
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
{
Toast.makeText(getApplicationContext(), " Setting ", Toast.LENGTH_SHORT).show();
return true;
}
if(id==R.id.Change_photo)
{
Toast.makeText(getApplicationContext(),"Change Your Photo",Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item)
{
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera)
{
}
else if (id == R.id.nav_gallery)
{
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
else if (id == R.id.nav_slideshow)
{
}
else if (id == R.id.nav_manage)
{
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
class ListViewItem
{
private String text;
private int type;
public ListViewItem(String text, int type)
{
this.text = text;
this.type = type;
}
public String getText()
{
return text;
}
public void setText(String text)
{
this.text = text;
}
public int getType()
{
return type;
}
public void setType(int type)
{
this.type = type;
}
}
class ViewHolder
{
TextView text;
public ViewHolder(TextView text) {
this.text = text;
}
public TextView getText() {
return text;
}
public void setText(TextView text) {
this.text = text;
}
}
class CustomAdapter extends ArrayAdapter
{
public static final int TYPE_ODD = 0;
public static final int TYPE_EVEN = 1;
public static final int TYPE_WHITE = 2;
public static final int TYPE_BLACK = 3;
public static final int TYPE_FOUR = 4;
private ListViewItem[] objects;
#Override
public int getViewTypeCount()
{
return 4;
}
#Override
public int getItemViewType(int position)
{
return objects[position].getType();
}
public CustomAdapter(MainActivity1 context, int resource, ListViewItem[] objects)
{
super(context, resource, objects);
this.objects = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder viewHolder = null;
ListViewItem listViewItem = objects[position];
int listViewItemType = getItemViewType(position);
if (convertView == null)
{
if (listViewItemType == TYPE_EVEN)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.even, null);
}
else if (listViewItemType == TYPE_ODD)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.odd, null);
}
else if (listViewItemType == TYPE_WHITE)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.white, null);
}
else if (listViewItemType == TYPE_FOUR)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.four, null);
}
else
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.black, null);
}
TextView textView = (TextView) convertView.findViewById(R.id.text);
viewHolder = new ViewHolder(textView);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
// viewHolder.getText().setText(listViewItem.getText());
return convertView;
}
}

1.Create a custom dialog and adjust to your needs, e. g. my_dialog.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/tv_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text"/>
<Button
android:id="#+id/btn_dialog"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_below="#+id/tv_dialog"
android:text="Button"/>
</RelativeLayout>
2.Declare and open dialog from activity:
my_dialog = new Dialog(context);
my_dialog .requestWindowFeature(Window.FEATURE_NO_TITLE);
my_dialog .setCancelable(true);
my_dialog .setContentView(R.layout.my_dialog);
my_dialog.show();

Related

How to add a footer view in recyclerview that is get data from DB and in a reverse layout

currently i have a recyclerview that is populated from a database. also recyclerview setreverselayout == true for start item from the bottom. now i want to add a footer view to my recyclerview. i have tried some tutorials but still didnt get a working solution. any help will be really appreciated.
this is my adapter class
package com.shan.vehicle_maintainance;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
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.view.animation.TranslateAnimation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class HistoryAdapter extends RecyclerView.Adapter<HistoryAdapter.HistoryViewHolder> {
private Context context;
boolean isInserted;
private List<History> listhistory;
private DatabaseHelper myDb;
public HistoryAdapter(Context context, List<History> listhistory) {
this.context = context;
this.listhistory = listhistory;
myDb = new DatabaseHelper(context);
}
#Override
public HistoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.history_list_layout, parent, false);
return new HistoryViewHolder(view);
}
private void changeStateOfItemsInLayout(History historyItem, int p) {
for (int x = 0; x < listhistory.size(); x++) {
if (x == p) {
historyItem.setShouldBeExpanded(true);
//Since this is the tapped item, we will skip
//the rest of loop for this item and set it expanded
continue;
}
listhistory.get(x).setShouldBeExpanded(false);
}
}
#Override
public void onBindViewHolder(final HistoryViewHolder holder, final int position) {
final History singleHistory = listhistory.get(position);
holder.txt1.setText(singleHistory.getTxt1());
holder.txt2.setText(String.valueOf(singleHistory.getTxt2())+" km");
holder.txt3.setText("Rs."+String.valueOf(singleHistory.getTxt4()));
String datettime = singleHistory.getTxt3();
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm");
Date date = null;
try {
date = dt.parse(datettime);
} catch (ParseException e) {
e.printStackTrace();
}
History historyItem = listhistory.get(position);
if(historyItem.getShouldBeExpanded()){
expand(holder.expand);
holder.mainview.setBackgroundResource(0);
}else{
collapse(holder.expand);
//holder.expand2.collapse();
final int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
holder.mainview.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.cardview_bg) );
} else {
holder.mainview.setBackground(ContextCompat.getDrawable(context, R.drawable.cardview_bg));
}
}
// *** same for the format String below
SimpleDateFormat dt1 = new SimpleDateFormat("yyyy MMM dd");
holder.txt4.setText(dt1.format(date));
//View v = holder.layoutManager.findViewByPosition(position)
int size = listhistory.size() - 1;
Integer tbltype = singleHistory.getTxt5();
if (tbltype == 1){
if (size == position){
holder.historyimg.setImageResource(R.drawable.fuelhome6top);
}else
holder.historyimg.setImageResource(R.drawable.fuelhome6);
}else if (tbltype == 2){
if (size == position){
holder.historyimg.setImageResource(R.drawable.expensehome6top);
}else
holder.historyimg.setImageResource(R.drawable.expensehome6);
}else if (tbltype == 3){
if (size == position){
holder.historyimg.setImageResource(R.drawable.servicehome6top);
}else
holder.historyimg.setImageResource(R.drawable.servicehome6);
}
//holder.expand.setVisibility(View.GONE);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.expand.isShown()){
listhistory.get(holder.getLayoutPosition()).setShouldBeExpanded(false);
//holder.expand.setVisibility(View.GONE);
// collapse(holder.expand);
//
// //holder.expand2.collapse();
// final int sdk = android.os.Build.VERSION.SDK_INT;
// if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
// holder.mainview.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.cardview_bg) );
// } else {
// holder.mainview.setBackground(ContextCompat.getDrawable(context, R.drawable.cardview_bg));
// }
//holder.expand2.collapse();
// holder.expand.setVisibility(View.GONE);
//holder.expand2.setVisibility(View.GONE);
}else {
listhistory.get(holder.getLayoutPosition()).setShouldBeExpanded(true);
changeStateOfItemsInLayout(listhistory.get(holder.getLayoutPosition()),holder.getLayoutPosition());
// holder.expand.setVisibility(View.VISIBLE);
//holder.expand2.setVisibility(View.VISIBLE);
//holder.expand.setVisibility(View.VISIBLE);
//expand(holder.expand);
//holder.mainview.setBackgroundResource(0);
//holder.expand2.expand();
//holder.expand2.expand();
}
notifyDataSetChanged();
}
});
holder.edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//listhistory.get(position).getId();
Bundle args = new Bundle();
args.putInt("id", listhistory.get(position).getId());
Integer tbltype = listhistory.get(position).getTxt5();
if (tbltype == 1){
VehicleHome vehicleHome = (VehicleHome) v.getContext();
AddRefuelFrag addRefuelFrag = new AddRefuelFrag();
addRefuelFrag.setArguments(args);
FragmentTransaction fragmentTransaction_view_refuel = vehicleHome.getSupportFragmentManager().beginTransaction();
fragmentTransaction_view_refuel.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.enter, R.anim.exit);
fragmentTransaction_view_refuel.replace(R.id.activity_to_do, addRefuelFrag);
fragmentTransaction_view_refuel.addToBackStack(null);
fragmentTransaction_view_refuel.commit();
//Toast.makeText(context, "edit clicked", Toast.LENGTH_SHORT).show();
}
}
});
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer tbltype = listhistory.get(position).getTxt5();
if (tbltype == 1){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Delete");
builder.setMessage("Are you sure you want to delete?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
isInserted = myDb.deleteDataRefuel(String.valueOf(listhistory.get(position).getId()));
if (isInserted == true) {
Toast.makeText(context,"item deleted", Toast.LENGTH_SHORT).show();
VehicleHome vehicleHome = (VehicleHome) context;
HistoryFrg historyFrg = new HistoryFrg();
FragmentTransaction fragmentTransaction_history = vehicleHome.getSupportFragmentManager().beginTransaction();
fragmentTransaction_history.replace(R.id.activity_to_do,historyFrg);
//fragmentTransaction_refueling.addToBackStack(null);
fragmentTransaction_history.commit();
}else
Toast.makeText(context, "cannot delete", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
});
holder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle args = new Bundle();
args.putInt("id", listhistory.get(position).getId());
Integer tbltype = listhistory.get(position).getTxt5();
if (tbltype == 1){
VehicleHome vehicleHome = (VehicleHome) v.getContext();
RefuelItemViewFrag refuelItemViewFrag = new RefuelItemViewFrag();
refuelItemViewFrag.setArguments(args);
FragmentTransaction fragmentTransaction_view_refuel = vehicleHome.getSupportFragmentManager().beginTransaction();
fragmentTransaction_view_refuel.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.enter, R.anim.exit);
fragmentTransaction_view_refuel.replace(R.id.activity_to_do, refuelItemViewFrag);
fragmentTransaction_view_refuel.addToBackStack(null);
fragmentTransaction_view_refuel.commit();
}
}
});
}
public static void expand(View view) {
view.setVisibility(View.VISIBLE);
final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(widthSpec, heightSpec);
ValueAnimator mAnimator = slideAnimator(view, 0, view.getMeasuredHeight());
mAnimator.start();
}
public static void collapse(final View view) {
int finalHeight = view.getHeight();
ValueAnimator mAnimator = slideAnimator(view, finalHeight, 0);
mAnimator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationEnd(Animator animator) {
view.setVisibility(View.GONE);
}
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
mAnimator.start();
}
private static ValueAnimator slideAnimator(final View v, int start, int end) {
ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
int value = (Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = v.getLayoutParams();
layoutParams.height = value;
v.setLayoutParams(layoutParams);
}
});
return animator;
}
#Override
public int getItemCount() {
return listhistory.size();
}
public class HistoryViewHolder extends RecyclerView.ViewHolder {
public TextView txt1;
public TextView txt2;
public TextView txt3;
public TextView txt4;
public ImageView historyimg;
LinearLayout mainview;
ImageButton edit,delete,view;
//public ExpandableLayout expand,expand2;
//public ExpandableRelativeLayout expand,expand2;
LinearLayout expand;
public HistoryViewHolder(View itemView) {
super(itemView);
txt1 = (TextView)itemView.findViewById(R.id.txt1);
txt2 = (TextView)itemView.findViewById(R.id.txt2);
txt3 = (TextView)itemView.findViewById(R.id.txt3);
txt4 = (TextView)itemView.findViewById(R.id.txt4);
historyimg = (ImageView)itemView.findViewById(R.id.imghistory);
//expand = (ExpandableLayout)itemView.findViewById(R.id.expand);
//expand2 = (ExpandableLayout)itemView.findViewById(R.id.expand2);
mainview = (LinearLayout)itemView.findViewById(R.id.mainview);
expand = (LinearLayout)itemView.findViewById(R.id.expand);
edit = (ImageButton) itemView.findViewById(R.id.btnedit);
delete = (ImageButton) itemView.findViewById(R.id.btndelete);
view = (ImageButton) itemView.findViewById(R.id.btnview);
}
}
}
To add a footer view in recyclerView you have to return the size of data, the recyclerView have to populate, + 1 from the getItemCount() method.
public int getItemCount() {
return listhistory.size() + 1;
}
Create a new viewHolder for the footer view and populate it with the appropriate footer layout that you have created.
Override the method getItemViewType(int position) to return an integer specific to each viewType
public int getItemViewType(int position) {
if (position == listhistory.size()) {
return 0;
} else {
return 1;
}
}
Change your onCreateViewHolder method to return appropriate viewHolder based on viewType;
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 1) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.history_list_layout, parent, false);
return new HistoryViewHolder(view);
} else if (viewType == 0) {
View view = LayoutInflater.from(mContext)
.inflate(R.layout.footer_layout, parent, false);
return new FooterViewHolder(view);
}
return null;
}
Modify your onBindViewHolder() method so that it checks for the instance of the holder i.e., either HistoryViewHolder or FooterViewHolder and write the code accordingly.
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof HistoryViewHolder) {
HistoyViewHolder historyHolder = (HistoryViewHolder) holder;
// All your existing code here and replace holder with history holder
} else {
// if you footer is static ignore this else part otherwise write the appropriate code
}
Hope this helps...✌
You could use an RecyclerView Decorator to achieve what you want, without touching your adapter.
Have a look at RecyclerView.ItemDecoration. Tell me if you want some more info about its usage.

RecyclerView datas last row display with multiple time

I don't understand why my recyclerview is only showing the last row of my database although I initialised it with 150 datas.
I searched a lot in the internet and even here on SO, but not one of the solutions is working. Can you help me to figure out why my recyclerView is only showing the last row of the database? Thanks in advance to all of you.
May be you can help me. Here is my code:
package com.example.frontaddress.matedesignc;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Customer_Activity extends AppCompatActivity {
private List<String> StateListArray =new ArrayList<String>();
private List<String> StateList =new ArrayList<String>();
private List<String> CityListArray ;
private List<String> CityList ;
private Spinner dropdown_state;
private Spinner dropdown_city;
private DBHandler DB = new DBHandler(this);
private static final String BUSINESSNAME = "bussiness_name";
private static final String MOBILE = "mobile";
private static final String ADDRESS = "address";
private static final String ID = "id";
private Toolbar toolbar;
private Customer_list_Adapter adapter;
private RecyclerView recyclerView_Customer;
//ProgressDialog pDialog = new ProgressDialog(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer_list);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
GetStateList(); }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_sub, menu);
return true; }
public void CustomerDetails(String state,String city) throws IOException {
try {
List<customer_search_information> data = null;
data = new ArrayList<>();
customer_search_information current = new customer_search_information();
Cursor RST_CSTInfo = DB.getRows("customer", "id,bussiness_name,mobile,address", " state='" + state + "' AND city='" + city + "'");
while (!RST_CSTInfo.isAfterLast()) {
current.bussiness_name = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(BUSINESSNAME));
current.state = state;
current.city = city;
current.address = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(ADDRESS));
String Mob = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(MOBILE));
current.mobile_no = Mob;
current.e_mail = "mail.isigntech#gmail.com";
current.id = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(ID));
// displayExceptionMessage(current.id+current.bussiness_name+current.state+current.city+current.address+current.mobile+current.email);
data.add(current);
RST_CSTInfo.moveToNext();
}
recyclerView_Customer = (RecyclerView) findViewById(R.id.drawerListCustomer);
recyclerView_Customer.setHasFixedSize(true);
recyclerView_Customer.setHasFixedSize(true);
recyclerView_Customer.setLayoutManager(new LinearLayoutManager(this));
adapter = new Customer_list_Adapter(this, data);
recyclerView_Customer.setAdapter(adapter);
}catch (Exception e){ displayExceptionMessage(e.toString());}
}
private void GetStateList()
{ Cursor Customer= DB.getRows("customer","state", " 1 GROUP BY state");
while(!Customer.isAfterLast()){
String state=Customer.getString(Customer.getColumnIndex("state"));
StateList.add(state);
StateListArray.add(state);
Customer.moveToNext();
}
dropdown_state = (Spinner)findViewById(R.id.SpnSrch_State);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Customer_Activity.this, android.R.layout.simple_spinner_dropdown_item, StateListArray);
dropdown_state.setAdapter(adapter);
dropdown_state.setPrompt("Choose State ");
dropdown_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int item = dropdown_state.getSelectedItemPosition();
String state =StateListArray.get(item);
dropdown_city=(Spinner) findViewById(R.id.SpnSrch_State);
Cursor RstCity= DB.getRows("customer","city", "state='"+state+"' GROUP BY city");
CityListArray =new ArrayList<String>();
CityList =new ArrayList<String>();
while(!RstCity.isAfterLast()){
String city=RstCity.getString(RstCity.getColumnIndex("city"));
CityList.add(city);
CityListArray.add(city);
RstCity.moveToNext();
}
dropdown_city = (Spinner)findViewById(R.id.SpnSrch_City);
ArrayAdapter<String> cityadapter = new ArrayAdapter<String>(Customer_Activity.this, android.R.layout.simple_spinner_dropdown_item, CityListArray);
dropdown_city.setAdapter(cityadapter);
dropdown_city.setPrompt("Choose City ");
dropdown_city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int item = dropdown_state.getSelectedItemPosition();
String state =StateListArray.get(item);
item = dropdown_city.getSelectedItemPosition();
String city =CityListArray.get(item);
try {
CustomerDetails(state,city);
} catch (Exception e) {
displayExceptionMessage(e.toString());
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
displayExceptionMessage("Please Select State.");
}
});
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
displayExceptionMessage("Please Select City.");
}
});
}
public void displayExceptionMessage(String msg) {
//TextView Txterror=(TextView) findViewById(R.id.txterror);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == android.R.id.home) {
// NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItementer code hereSelected(item);
}
}
Here is my custom list adapter code:
package com.example.frontaddress.matedesignc;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
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.Collections;
import java.util.List;
/**
* Created by frontaddress on 10/08/17.
*/
public class Customer_list_Adapter extends RecyclerView.Adapter<Customer_list_Adapter.CustomerViewHolder> {
private LayoutInflater inflater;
private Context contexts;
List<customer_search_information> Cst_data = Collections.emptyList();
public Customer_list_Adapter(Context context, List<customer_search_information> data) {
inflater = LayoutInflater.from(context);
this.Cst_data = data;
// Toast.makeText(contexts, data.size(), Toast.LENGTH_LONG).show();
this.contexts = context;
}
#Override
public CustomerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.content_search_staff, parent, false);
CustomerViewHolder holder = new CustomerViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(CustomerViewHolder holder, int position) {
try {
customer_search_information current = Cst_data.get(position);
Integer Pos=position;
holder.TxtBisinessName.setText(current.bussiness_name);
holder.TxtAddress.setText(current.address);
holder.Statecity.setText(current.state + "-" + current.city);
holder.Txt_Mobile.setText(current.mobile_no.toString());
holder.TxtEmail.setText(current.e_mail);
}catch (Exception e)
{
Toast.makeText(contexts,e.toString(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return Cst_data.size();
}
class CustomerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView TxtBisinessName;
TextView TxtAddress;
TextView Txt_Mobile;
TextView Statecity;
TextView TxtEmail;
ImageView ImgPhoneCall,ImgMailTo;
public CustomerViewHolder(View itemView) {
super(itemView);
TxtBisinessName = (TextView) itemView.findViewById(R.id.Txtbusiness_name);
Txt_Mobile = (TextView) itemView.findViewById(R.id.TxtMobile);
Statecity = (TextView) itemView.findViewById(R.id.Txtstatecity);
TxtAddress = (TextView) itemView.findViewById(R.id.Txtaddress);
TxtEmail=(TextView) itemView.findViewById(R.id.TxtEmail);
ImgPhoneCall = (ImageView) itemView.findViewById(R.id.ImgCallPhone);
ImgMailTo= (ImageView) itemView.findViewById(R.id.Imgmail);
ImgPhoneCall.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
customer_search_information current = Cst_data.get(getPosition());
String MOBILE = current.mobile_no;
try {
if (ActivityCompat.checkSelfPermission(contexts,Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(contexts, "Call Permission Not Granted ", Toast.LENGTH_LONG).show();
return;
}
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:+91" + MOBILE));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
contexts.startActivity(callIntent);
}
catch (Exception e){
Toast.makeText(contexts,e.toString(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
});
/* TxtProfile.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
customer_search_information current = data.get(getPosition());
String SID = current.id;
Intent intent = new Intent(contexts, StudentProfileActivity.class);
intent.putExtra("id", SID);
contexts.startActivity(intent);
}
});*/
ImgMailTo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// TODO Auto-generated method stub
customer_search_information current = Cst_data.get(getPosition());
String EMAIL = current.e_mail;
String BName = current.bussiness_name;
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, EMAIL);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "");
emailIntent.setType("text/plain");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Hi,"+BName);
final PackageManager pm = contexts.getPackageManager();
final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
ResolveInfo best = null;
for (final ResolveInfo info : matches)
if (info.activityInfo.packageName.endsWith(".gm") || info.activityInfo.name.toLowerCase().contains("gmail"))
best = info;
if (best != null)
emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name);
contexts.startActivity(emailIntent);
}
catch (Exception e){ }
}
});
}
#Override
public void onClick(View v) {
int ID=v.getId();
customer_search_information current=Cst_data.get(getPosition());
String SID=current.id;
// Toast.makeText(contexts,"Item Clicked Profile: "+ v.getId(), Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(contexts, StudentProfileActivity.class);
// intent.putExtra("id", SID);
// contexts.startActivity(intent);
}
}
}
I think the problem is here , instead of
while(!RST_CSTInfo.isAfterLast()){
...
..
RST_CSTInfo.moveToNext();
}
try this ....
do(RST_CSTInfo.movetofirst()){
// your logic
}while(cursor.movetonext())

Spinner: AppCompatSpinner cannot be cast to com.example.....MySpinner (Android)

I am trying to trigger an event from same item selected from the spinner. I found class called MySpinner that extends Spinner but obviously i have problems with its implementation.
package com.example.ilija.festivalapp_makedox;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ilija.festivalapp_makedox.MySpinner;
import com.example.ilija.festivalapp_makedox.agendacalendarview.CalendarPickerController;
import java.util.ArrayList;
public class CustomSpinner extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
public ArrayList<SpinnerModel> CustomListViewValuesArr=new ArrayList<>();
public ArrayList<SpinnerModel> CustomListViewValuesArr1=new ArrayList<>();
public ArrayList<SpinnerModel> CustomListViewValuesArr2=new ArrayList<>();
public ArrayList<SpinnerModel> CustomListViewValuesArr3=new ArrayList<>();
public ArrayList<SpinnerModel> CustomListViewValuesArrTest=new ArrayList<>();
/*public ArrayList<SpinnerModel> CustomListViewValuesArr1Test=new ArrayList<>();
public ArrayList<SpinnerModel> CustomListViewValuesArr2Test=new ArrayList<>();
public ArrayList<SpinnerModel> CustomListViewValuesArr3Test=new ArrayList<>();*/
TextView output = null;
CustomSpinner activity = null;
NavigationView navigationView;
CustomAdapter adapter,adapter1,adapter2,adapter3,adapterTest,adapter1Test,adapter2Test,adapter3Test;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_spinner);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Movies");
setSupportActionBar(toolbar);
activity = this;
Spinner SpinnerExample = (Spinner) findViewById(R.id.spinner);
Spinner SpinnerExample1 = (Spinner) findViewById(R.id.spinner1);
Spinner SpinnerExample2 = (Spinner) findViewById(R.id.spinner2);
Spinner SpinnerExample3 = (Spinner) findViewById(R.id.spinner3);
MySpinner SpinnerExampleTest = (MySpinner) findViewById(R.id.spinnerTest);
/* Spinner SpinnerExampleTest = (Spinner) findViewById(R.id.spinnerTest);
Spinner SpinnerExampleTest1 = (Spinner) findViewById(R.id.spinner1Test);
Spinner SpinnerExampleTest2 = (Spinner) findViewById(R.id.spinner2Test);
Spinner SpinnerExampleTest3 = (Spinner) findViewById(R.id.spinner3Test);*/
output = (TextView)findViewById(R.id.output);
setListData();
setListData1();
setListData2();
setListData3();
setListDataTest();
/* setListData1Test();
setListData2Test();
setListData3Test();*/
Resources res = getResources();
adapter = new CustomAdapter(activity,R.layout.spinner_rows,CustomListViewValuesArr,res);
adapter1 = new CustomAdapter(activity,R.layout.spinner_rows,CustomListViewValuesArr1,res);
adapter2 = new CustomAdapter(activity,R.layout.spinner_rows,CustomListViewValuesArr2,res);
adapter3 = new CustomAdapter(activity,R.layout.spinner_rows,CustomListViewValuesArr3,res);
adapterTest = new CustomAdapter(activity,R.layout.spinner_rows,CustomListViewValuesArrTest,res);
/* adapter1Test = new CustomAdapter(activity,R.layout.spinner_rows,CustomListViewValuesArr1Test,res);
adapter2Test = new CustomAdapter(activity,R.layout.spinner_rows,CustomListViewValuesArr2Test,res);
adapter3Test = new CustomAdapter(activity,R.layout.spinner_rows,CustomListViewValuesArr3Test,res);*/
SpinnerExample.setAdapter(adapter);
SpinnerExample.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
i++; //Avoid fist time oppening the OnClick start new intent. First time is for set pic of the first element in the list.
String Movie = ((TextView) view.findViewById(R.id.movieName)).getText().toString();
if(i>1){
Intent intent = new Intent(CustomSpinner.this, MovieTrailer.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
SpinnerExample1.setAdapter(adapter1);
SpinnerExample1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
i++; //Avoid fist time oppening the OnClick start new intent. First time is for set pic of the first element in the list.
String Movie = ((TextView) view.findViewById(R.id.movieName)).getText().toString();
if(i>2){
Intent intent = new Intent(CustomSpinner.this, MovieTrailer.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
SpinnerExample2.setAdapter(adapter2);
SpinnerExample2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "HERE" , Toast.LENGTH_SHORT).show();
i++; //Avoid fist time oppening the OnClick start new intent. First time is for set pic of the first element in the list.
String Movie = ((TextView) view.findViewById(R.id.movieName)).getText().toString();
if(i>3){
Intent intent = new Intent(CustomSpinner.this, MovieTrailer.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView arg0) {
Toast.makeText(getApplicationContext(), (CharSequence) "HERE AGAIN", Toast.LENGTH_SHORT).show();
}
});
SpinnerExample3.setAdapter(adapter3);
SpinnerExample3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
i++; //Avoid fist time oppening the OnClick start new intent. First time is for set pic of the first element in the list.
String Movie = ((TextView) view.findViewById(R.id.movieName)).getText().toString();
if(i>4){
Intent intent = new Intent(CustomSpinner.this, MovieTrailer.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//********************************************************TEST COMPONENTS******************************************************************//
SpinnerExampleTest.setAdapter(adapterTest);
SpinnerExampleTest.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), (CharSequence) "HERE", Toast.LENGTH_SHORT).show();
String Movie = ((TextView) view.findViewById(R.id.movieName)).getText().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(getApplicationContext(), (CharSequence) "HERE AGAIN", Toast.LENGTH_SHORT).show();
}
});
/* SpinnerExampleTest1.setAdapter(adapter1Test);
SpinnerExampleTest1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String Movie = ((TextView) view.findViewById(R.id.movieName)).getText().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
SpinnerExampleTest2.setAdapter(adapter2Test);
SpinnerExampleTest2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String Movie = ((TextView) view.findViewById(R.id.movieName)).getText().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
SpinnerExampleTest3.setAdapter(adapter3Test);
SpinnerExampleTest3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String Movie = ((TextView) view.findViewById(R.id.movieName)).getText().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
*/
//**************************************************TEST COMPONENTS**************************************************************************************//
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
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();
}
});*/
}
public void setListData(){
String moy[] = {"DEN UNGE ZLATAN/BECOMING ZLATAN","THE SWEDISH THEORY OF LOVE","JONAS E O CIRCO SEM LONA/JONAS AND THE BACKYARD CIRCUS","ZID SMRTI, I TAKO TO/WALL OF DEATH, AND ALL",
"ПОСЛАННИКИ БОЛЬШОЙ ЗЕМЛИ/ SIBERIAN FLOATING HOSPITAL","FIGURA/FIGURE","1","2","3","1","2","3"};
for(int i=0;i<moy.length;i++){
final SpinnerModel sched = new SpinnerModel();
sched.setMovieName(moy[i]);
sched.setImage("image1"+i);
CustomListViewValuesArr.add(sched);
}
}
public void setListData1(){
String moy1[] = {"EL BOTÓN DE NÁCAR/PEARL","BRØDRE/BROTHERS 2015 110’","V LUCHAKH SOLNCA/UNDER THE SUN","KANTON JUGOSLAWIEN/LITTLE YUGOSLAVIA","1","2","3","1","2","3","1","2","3","1","2","3"};
for(int i=0;i<moy1.length;i++){
final SpinnerModel sched1 = new SpinnerModel();
sched1.setMovieName(moy1[i]);
sched1.setImage("image2"+i);
CustomListViewValuesArr1.add(sched1);
}
}
public void setListData2(){
String moy2[] = {"JUST ANOTHER DAY IN EGYPT","THE PERFECT CIRCLE","MOJ NAROBE SVET/MY WORLD IS UPSIDE DOWN","1","2","3","1","2","3","1","2","3","1","2","3"};
for(int i=0;i<moy2.length;i++){
final SpinnerModel sched2 = new SpinnerModel();
sched2.setMovieName(moy2[i]);
sched2.setImage("image3"+i);
CustomListViewValuesArr2.add(sched2);
}
}
public void setListData3(){
String moy3[] = {"BREZMEJNO/BEYOND BOUNDARIES","SOMETHING ABOUT LIFE","NA KRAYU/ON THE EDGE","JAMEY’S GEVECHT/JAMEY’S FIGHT","SCHWERELOS/ZERO-G"};
for(int i=0;i<moy3.length;i++){
final SpinnerModel sched3 = new SpinnerModel();
sched3.setMovieName(moy3[i]);
sched3.setImage("image4"+i);
CustomListViewValuesArr3.add(sched3);
}
}
//**************************************************TEST COMPONENTS**************************************************************************************//
public void setListDataTest(){
String moyTest[] = {"MovieTest1","MovieTest2","MovieTest2"};
for(int i=0;i<moyTest.length;i++){
final SpinnerModel schedTest = new SpinnerModel();
schedTest.setMovieName(moyTest[i]);
schedTest.setImage("image"+i);
CustomListViewValuesArrTest.add(schedTest);
}
}
/* public void setListData1Test(){
String moy1Test[] = {"MovieTest1","MovieTest1","Movie1","Movie1"};
for(int i=0;i<moy1Test.length;i++){
final SpinnerModel sched1Test = new SpinnerModel();
sched1Test.setMovieName(moy1Test[i]);
sched1Test.setImage("image"+i);
CustomListViewValuesArr1Test.add(sched1Test);
}
}
public void setListData2Test(){
String moy2Test[] = {"MovieTest1","MovieTest2","Movie3"};
for(int i=0;i<moy2Test.length;i++){
final SpinnerModel sched2Test = new SpinnerModel();
sched2Test.setMovieName(moy2Test[i]);
sched2Test.setImage("image"+i);
CustomListViewValuesArr2Test.add(sched2Test);
}
}
public void setListData3Test(){
String moy3Test[] = {"Movie1","Movie2","Movie3"};
for(int i=0;i<moy3Test.length;i++){
final SpinnerModel sched3Test = new SpinnerModel();
sched3Test.setMovieName(moy3Test[i]);
sched3Test.setImage("image"+i);
CustomListViewValuesArr3Test.add(sched3Test);
}
}
*/
//**************************************************TEST COMPONENTS**************************************************************************************//
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camara) {
Intent intent = new Intent(CustomSpinner.this, MainScreen.class);
startActivity(intent);
Toast.makeText(getBaseContext(), "Program", Toast.LENGTH_LONG).show();
//Set the fragment initially
// Handle the camera action
} else if (id == R.id.nav_gallery) {
Intent i = new Intent(CustomSpinner.this, CustomSpinner.class);
startActivity(i);
Toast.makeText(getBaseContext(), "Movies", Toast.LENGTH_LONG).show();
} else if (id == R.id.nav_slideshow) {
Intent intent = new Intent(CustomSpinner.this, BasicActivity.class);
startActivity(intent);
Toast.makeText(getBaseContext(), "Timeline", Toast.LENGTH_LONG).show();
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
//Intent intent = new Intent(MainScreen.this, MapsActivity.class);
// startActivity(intent);
// Toast.makeText(getBaseContext(), "Maps", Toast.LENGTH_LONG).show();
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
the class MySpinner contains this code:
public class MySpinner extends Spinner {
OnItemSelectedListener listener;
public MySpinner(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void setSelection(int position) {
super.setSelection(position);
if (listener != null)
listener.onItemSelected(null, null, position, 0);
}
public void setOnItemSelectedEvenIfUnchangedListener(
AdapterView.OnItemSelectedListener listener) {
this.listener = listener;
}
}
When open this Activity i have this error, and app crashes.
/com.example.ilija.festivalapp_makedox E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ilija.festivalapp_makedox, PID: 12914
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ilija.festivalapp_makedox/com.example.ilija.festivalapp_makedox.CustomSpinner}: java.lang.ClassCastException: android.support.v7.widget.AppCompatSpinner cannot be cast to com.example.ilija.festivalapp_makedox.MySpinner
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: android.support.v7.widget.AppCompatSpinner cannot be cast to com.example.ilija.festivalapp_makedox.MySpinner
at com.example.ilija.festivalapp_makedox.CustomSpinner.onCreate(CustomSpinner.java:56)
at android.app.Activity.performCreate(Activity.java:5312)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2552)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653) 
at android.app.ActivityThread.access$800(ActivityThread.java:156) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:157) 
at android.app.ActivityThread.main(ActivityThread.java:5872) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674) 
at dalvik.system.NativeStart.main(Native Method) 
I guess that layout.activity_custom_spinner.xml is like this:
<Spinner id="#+id/spinnerTest" ...>
it should be like this:
<MySpinner id="#+id/spinnerTest" ...>
And MySpinner can be extends android.support.v7.widget.AppCompatSpinner.
https://developer.android.com/reference/android/support/v7/widget/AppCompatSpinner.html
This will automatically be used when you use Spinner in your layouts.
You should only need to manually use this class when writing custom
views.

How to add image on header in Navigation Drawer

I am using Gabriele Mariotti navigation drawer library to create the sliding menu. It works perfect, but I'm facing with adding an image, as header in it. It should look something like this:
I mean.. not exactly the same, but the idea of having the image as header. Thanks !
MainActivity:
package ro.volunteer;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
public class NewsFeed extends Activity implements OnClickListener {
private ListView mDrawerList;
private DrawerLayout mDrawer;
private CustomActionBarDrawerToggle mDrawerToggle;
private String[] menuItems;
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsfeed);
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
_initMenu();
mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
mDrawer.setDrawerListener(mDrawerToggle);
}
private void _initMenu() {
NsMenuAdapter mAdapter = new NsMenuAdapter(this);
menuItems = getResources().getStringArray(
R.array.ns_menu_items_icon);
// Add Header
mAdapter.addHeader(R.string.ns_menu_main_header);
// Add first block
menuItems = getResources().getStringArray(
R.array.ns_menu_items);
String[] menuItemsIcon = getResources().getStringArray(
R.array.ns_menu_items_icon);
int res = 0;
for (String item : menuItems) {
int id_title = getResources().getIdentifier(item, "string",
this.getPackageName());
int id_icon = getResources().getIdentifier(menuItemsIcon[res],
"drawable", this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
if (res==1) mItem.counter=0; //it is just an example...
if (res==3) mItem.counter=0; //it is just an example...
mAdapter.addItem(mItem);
res++;
}
mAdapter.addHeader(R.string.ns_menu_main_header2);
menuItems = getResources().getStringArray(
R.array.ns_menu_items2);
String[] menuItemsIcon1 = getResources().getStringArray(
R.array.ns_menu_items_icon3);
int res2 = 0;
for (String item : menuItems) {
int id_title = getResources().getIdentifier(item, "string",
this.getPackageName());
int id_icon = getResources().getIdentifier(menuItemsIcon1[res2],
"drawable", this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
if (res2==1) mItem.counter=0; //it is just an example...
mAdapter.addItem(mItem);
res2++;
}
mDrawerList = (ListView) findViewById(R.id.drawer);
if (mDrawerList != null)
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
/*
* The action bar home/up should open or close the drawer.
* ActionBarDrawerToggle will take care of this.
*/
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle {
public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout){
super(
mActivity,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.ns_menu_open,
R.string.ns_menu_close);
}
#Override
public void onDrawerClosed(View view) {
getActionBar().setTitle(getString(R.string.ns_menu_close));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(getString(R.string.ns_menu_open));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mDrawerList.setItemChecked(position, true);
mDrawer.closeDrawer(mDrawerList);
if (position == 1) {
Intent intent = new Intent(NewsFeed.this, Profile.class);
startActivity(intent);
mDrawer.closeDrawers();
}
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Adapter:
package ro.volunteer;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class NsMenuAdapter extends ArrayAdapter<NsMenuItemModel> {
/*
* public NsMenuAdapter(Context context, int resource, int
* textViewResourceId, String[] objects) { super(context,
* R.layout.ns_menu_row, textViewResourceId, objects); }
*/
public NsMenuAdapter(Context context) {
super(context, 0);
}
public void addHeader(int title) {
add(new NsMenuItemModel(title, -1, true));
}
public void addItem(int title, int icon) {
add(new NsMenuItemModel(title, icon, false));
}
public void addItem(NsMenuItemModel itemModel) {
add(itemModel);
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return getItem(position).isHeader ? 0 : 1;
}
#Override
public boolean isEnabled(int position) {
return !getItem(position).isHeader;
}
public static class ViewHolder {
public final TextView textHolder;
public final ImageView imageHolder;
public final TextView textCounterHolder;
public ViewHolder(TextView text1, ImageView image1,TextView textcounter1) {
this.textHolder = text1;
this.imageHolder = image1;
this.textCounterHolder=textcounter1;
}
}
public View getView(int position, View convertView, ViewGroup parent) {
NsMenuItemModel item = getItem(position);
ViewHolder holder = null;
View view = convertView;
if (view == null) {
int layout = R.layout.ns_menu_row_counter;
if (item.isHeader)
layout = R.layout.ns_menu_row_header;
view = LayoutInflater.from(getContext()).inflate(layout, null);
TextView text1 = (TextView) view.findViewById(R.id.menurow_title);
text1.setTextColor(Color.WHITE);
ImageView image1 = (ImageView) view.findViewById(R.id.menurow_icon);
TextView textcounter1 = (TextView) view.findViewById(R.id.menurow_counter);
view.setTag(new ViewHolder(text1, image1,textcounter1));
}
if (holder == null && view != null) {
Object tag = view.getTag();
if (tag instanceof ViewHolder) {
holder = (ViewHolder) tag;
}
}
if(item != null && holder != null)
{
if (holder.textHolder != null)
holder.textHolder.setText(item.title);
if (holder.textCounterHolder != null){
if (item.counter > 0){
holder.textCounterHolder.setVisibility(View.VISIBLE);
holder.textCounterHolder.setText(""+item.counter);
}else{
holder.textCounterHolder.setVisibility(View.GONE);
}
}
if (holder.imageHolder != null) {
if (item.iconRes > 0) {
holder.imageHolder.setVisibility(View.VISIBLE);
holder.imageHolder.setImageResource(item.iconRes);
} else {
holder.imageHolder.setVisibility(View.GONE);
}
}
}
return view;
}
}
**ItemModel:**
package ro.volunteer;
public class NsMenuItemModel {
public int title;
public int iconRes;
public int counter;
public boolean isHeader;
public NsMenuItemModel(int title, int iconRes,boolean header,int counter) {
this.title = title;
this.iconRes = iconRes;
this.isHeader=header;
this.counter=counter;
}
public NsMenuItemModel(int title, int iconRes,boolean header){
this(title,iconRes,header,0);
}
public NsMenuItemModel(int title, int iconRes) {
this(title,iconRes,false);
}
}

How to add a new set of items in a sliding menu?

I want to add another block, or set, or whatever it is called, of items in my sliding menu but I can't figure out what to change to the code of the first... In my sliding menu I have 6 items, but I to have 4 items to the first title, and then, another title, and another 2 items.. but i can't figure out what do I have to change to my first block code.. Thanks a lot !!!!
Here is my MainActivity.java:
package com.orar.cngcnasaud;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener {
private ListView mDrawerList;
private DrawerLayout mDrawer;
private CustomActionBarDrawerToggle mDrawerToggle;
private String[] menuItems;
private static final String TAG = "AudioDemo";
private static final String isPlaying = "Media is Playing";
private static final String notPlaying = "Media has stopped Playing";
MediaPlayer player;
Button playerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_drawer);
player = MediaPlayer.create(this, R.raw.gc);
player.setLooping(false); // Set looping
// Get the button from the view
playerButton = (Button) this.findViewById(R.id.buttonmp);
playerButton.setText(R.string.play_label);
playerButton.setTextColor(Color.WHITE);
playerButton.setOnClickListener((OnClickListener) this);
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
_initMenu();
mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
mDrawer.setDrawerListener(mDrawerToggle);
}
public void onClick(View v) {
Log.d(TAG, "onClick: " + v);
if (v.getId() == R.id.buttonmp) {
playPause();
}
}
private void demoPause() {
// TODO Auto-generated method stub
player.pause();
playerButton.setText(R.string.play_label);
Log.d(TAG, notPlaying);
}
private void playPause() {
// TODO Auto-generated method stub
if(player.isPlaying()) {
demoPause();
} else {
demoPlay();
}
}
private void demoPlay() {
// TODO Auto-generated method stub
player.start();
playerButton.setText(R.string.stop_label);
Log.d(TAG, isPlaying);
}
private void _initMenu() {
NsMenuAdapter mAdapter = new NsMenuAdapter(this);
// Add Header
mAdapter.addHeader(R.string.ns_menu_main_header);
// Add first block
menuItems = getResources().getStringArray(
R.array.ns_menu_items);
String[] menuItemsIcon = getResources().getStringArray(
R.array.ns_menu_items_icon);
int res = 0;
for (String item : menuItems) {
int id_title = getResources().getIdentifier(item, "string",
this.getPackageName());
int id_icon = getResources().getIdentifier(menuItemsIcon[res],
"drawable", this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
if (res==1) mItem.counter=0; //it is just an example...
if (res==3) mItem.counter=0; //it is just an example...
mAdapter.addItem(mItem);
res++;
}
mDrawerList = (ListView) findViewById(R.id.drawer);
if (mDrawerList != null)
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
/*
* The action bar home/up should open or close the drawer.
* ActionBarDrawerToggle will take care of this.
*/
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle {
public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout){
super(
mActivity,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.ns_menu_open,
R.string.ns_menu_close);
}
#Override
public void onDrawerClosed(View view) {
getActionBar().setTitle(getString(R.string.ns_menu_close));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(getString(R.string.ns_menu_open));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mDrawerList.setItemChecked(position, true);
mDrawer.closeDrawer(mDrawerList);
if (position == 1) {
Intent intent = new Intent(MainActivity.this, Istoric.class);
startActivity(intent);
mDrawer.closeDrawers();
}
else if (position == 2) {
Intent intent2 = new Intent(MainActivity.this, Profesori.class);
startActivity(intent2);
mDrawer.closeDrawers();
}
if (position == 3) {
Intent intent3 = new Intent(MainActivity.this, Elevi.class);
startActivity(intent3);
mDrawer.closeDrawers();
}
if (position == 4) {
Intent intent4 = new Intent(MainActivity.this, ShowImageActivity.class);
startActivity(intent4);
mDrawer.closeDrawers();
}
if (position == 5) {
Intent intent5 = new Intent(MainActivity.this, Despre.class);
startActivity(intent5);
mDrawer.closeDrawers();
}
if (position == 6) {
Intent intent6 = new Intent(MainActivity.this, Feedback.class);
startActivity(intent6);
mDrawer.closeDrawers();
}
}
}
}
Thanks again !
I assume you want to achieve something similar to what is in the following picture:
You will have to modify your list adapter(NsMenuAdapter) to support two types of view - item and title where item is clickable and title is just kind of group header. Adapter should takes array/list of objects and every object should have type attribute. This will probably complicate a little OnItemClickListener.
I'm posting my example of that kind list adapter. In my case I created NavigationDrawerItem model to hold information about item type, item 'clickability' and what action should be triggered after item get clicked.
public class NavigationDrawerAdapter extends ArrayAdapter<NavigationDrawerItem> {
private static final String TAG = "NavigationDrawerAdapter";
public NavigationDrawerAdapter(Context context, int resource, NavigationDrawerItem[] objects) {
super(context, resource, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (null == convertView) {
int itemType = getItemViewType(position);
if (NavigationDrawerItem.TYPE_TITLE == itemType) {
convertView = View.inflate(getContext(), R.layout.item_title_navigation_drawer, null);
} else if (NavigationDrawerItem.TYPE_ITEM_UNDER_TITLE == itemType) {
convertView = View.inflate(getContext(), R.layout.item_under_title_navigation_drawer, null);
} else {
Log.e(TAG, "Returning default title view - Invalid drawer item type" + itemType);
convertView = View.inflate(getContext(), R.layout.item_title_navigation_drawer, null);
}
}
TextView tv = (TextView) convertView.findViewById(R.id.text);
tv.setText(getContext().getString(getItem(position).stringRes));
return convertView;
}
#Override
public int getItemViewType(int position) {
return getItem(position).type;
}
#Override
public int getViewTypeCount() {
return NavigationDrawerItem.NUMBER_OF_ITEM_TYPES;
}
#Override
public boolean isEnabled(int position) {
return NavigationDrawerItem.isItemClickable(getItemViewType(position));
}
}
And the NavigationDrawerItem class:
public final class NavigationDrawerItem {
private static final String TAG = "NavigationDrawerItem";
// Types must have numbers from 0 to n without gaps.
public static final int TYPE_TITLE = 0;// nonclickable
public static final int TYPE_ITEM_UNDER_TITLE = 1;// clickabel
public static final int NUMBER_OF_ITEM_TYPES = 2;
public final int action;
public final String argument;
public final int type;
//Constructors etc.
public static final boolean isItemClickable(int itemType) {
if (TYPE_TITLE == itemType) {
return false;
} else if (TYPE_ITEM_UNDER_TITLE == itemType) {
return true;
} else {
Log.e(TAG, "Invalid item type " + itemType);
return false;
}
}
}

Categories

Resources