To display an album art from media store in android - android-imageview

I'm not able to display album art from media store while listing albums,I'm getting
error
Bad request for field slot 0,-1. numRows = 32, numColumns = 7
01-02 02:48:16.789: D/AndroidRuntime(4963): Shutting down VM
01-02 02:48:16.789: W/dalvikvm(4963): threadid=1: thread exiting with uncaught exception (group=0x4001e578)
01-02 02:48:16.804: E/AndroidRuntime(4963): FATAL EXCEPTION: main
01-02 02:48:16.804: E/AndroidRuntime(4963): java.lang.IllegalStateException: get field slot from row 0 col -1 failed
Can anyone kindly help with this issue,Thanks in advance
public class AlbumbsListActivity extends Activity {
private ListAdapter albumListAdapter;
private HashMap<Integer, Integer> albumInfo;
private HashMap<Integer, Integer> albumListInfo;
private HashMap<Integer, String> albumListTitleInfo;
private String audioMediaId;
private static final String TAG = "AlbumsListActivity";
Boolean showAlbumList = false;
Boolean AlbumListTitle = false;
ImageView album_art ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.albums_list_layout);
Cursor cursor;
ContentResolver cr = getApplicationContext().getContentResolver();
if (getIntent().hasExtra(Util.ALBUM_ID)) {
int albumId = getIntent().getIntExtra(Util.ALBUM_ID,
Util.MINUS_ONE);
String[] projection = new String[] { Albums._ID, Albums.ALBUM, Albums.ARTIST, Albums.ALBUM_ART, Albums.NUMBER_OF_SONGS };
String selection = null;
String[] selectionArgs = null;
String sortOrder = Media.ALBUM + " ASC";
cursor = cr.query(Albums.EXTERNAL_CONTENT_URI, projection, selection, selectionArgs, sortOrder);
/* final String[] ccols = new String[] {
//MediaStore.Audio.Albums.,
MediaStore.Audio.Albums._ID,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Albums.ARTIST,
MediaStore.Audio.Albums.ALBUM_ART,
MediaStore.Audio.Albums.NUMBER_OF_SONGS
};
cursor = cr.query(MediaStore.Audio.Albums.getContentUri(
"external"), ccols, null, null,
MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);*/
showAlbumList = true;
}
else
{
String order = MediaStore.Audio.Albums.ALBUM + " ASC";
String where = MediaStore.Audio.Albums.ALBUM;
cursor = managedQuery(Media.EXTERNAL_CONTENT_URI,
DbUtil.projection, null, null, order);
showAlbumList = false;
}
albumInfo = new HashMap<Integer, Integer>();
albumListInfo = new HashMap<Integer, Integer>();
ListView listView = (ListView) findViewById(R.id.mylist_album);
listView.setFastScrollEnabled(true);
listView.setOnItemLongClickListener(new ItemLongClickListener());
listView.setAdapter(new AlbumCursorAdapter(this, cursor,
DbUtil.displayFields, DbUtil.displayViews,showAlbumList));
final Uri uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
final Cursor albumListCursor = cr.query(uri, DbUtil.Albumprojection,
null, null, null);
}
private class AlbumCursorAdapter extends SimpleCursorAdapter implements SectionIndexer{
private final Context context;
private final Cursor cursorValues;
private Time musicTime;
private Boolean isAlbumList;
private MusicAlphabetIndexer mIndexer;
private int mTitleIdx;
public AlbumCursorAdapter(Context context, Cursor cursor, String[] from,
int[] to,Boolean isAlbumList) {
super(context, 0, cursor, from, to);
this.context = context;
this.cursorValues = cursor;
//musicTime = new Time();
this.isAlbumList = isAlbumList;
}
String albumName="";
String artistName = "";
String numberofsongs = "";
long albumid;
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater
.inflate(R.layout.row_album_layout, parent, false);
}
this.cursorValues.moveToPosition(position);
String title = "";
String artistName = "";
String albumName = "";
int count;
long albumid = 0;
String songDuration = "";
if (isAlbumList) {
albumInfo.put(
position,
Integer.parseInt(this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums._ID))));
artistName = this.cursorValues
.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums.ARTIST));
albumName = this.cursorValues
.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums.ALBUM));
albumid=Integer.parseInt(this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ID)));
} else {
albumInfo.put(position, Integer.parseInt(this.cursorValues
.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media._ID))));
artistName = this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media.ARTIST));
albumName = this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
albumid=Integer.parseInt(this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)));
}
//code for Alphabetical Indexer
mTitleIdx = cursorValues.getColumnIndex(MediaStore.Audio.Media.ALBUM);
mIndexer = new MusicAlphabetIndexer(cursorValues, mTitleIdx,
getResources().getString(R.string.fast_scroll_alphabet));
//end
TextView metaone = (TextView) rowView.findViewById(R.id.album_name);
TextView metatwo = (TextView) rowView.findViewById(R.id.artist_name);
ImageView metafour = (ImageView) rowView.findViewById(R.id.album_art);
TextView metathree = (TextView) rowView
.findViewById(R.id.songs_count);
metaone.setText(albumName);
metatwo.setText(artistName);
(metafour)getAlbumArt(albumid);
System.out.println("albumid----------"+albumid);
metaThree.setText(DbUtil.makeTimeString(context, secs));
getAlbumArt(albumid);
}
TextView metaone = (TextView) rowView.findViewById(R.id.album_name);
TextView metatwo = (TextView) rowView.findViewById(R.id.artist_name);
album_art = (ImageView) rowView.findViewById(R.id.album_art);
//TextView metathree = (TextView) rowView.findViewById(R.id.songs_count);
metaone.setText(albumName);
metatwo.setText(artistName);
return rowView;
}
}
String albumArtUri = "";
private void getAlbumArt(long albumid) {
Uri uri=ContentUris.withAppendedId(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, albumid);
System.out.println("hhhhhhhhhhh" + uri);
Cursor cursor = getContentResolver().query(
ContentUris.withAppendedId(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, albumid),
new String[] { MediaStore.Audio.AlbumColumns.ALBUM_ART },
null,
null,
null);
if (cursor.moveToFirst()) {
albumArtUri = cursor.getString(0);
}
System.out.println("kkkkkkkkkkkkkkkkkkk :" + albumArtUri);
cursor.close();
if(albumArtUri != null){
Options opts = new Options();
opts.inJustDecodeBounds = true;
Bitmap albumCoverBitmap = BitmapFactory.decodeFile(albumArtUri, opts);
opts.inJustDecodeBounds = false;
albumCoverBitmap = BitmapFactory.decodeFile(albumArtUri, opts);
if(albumCoverBitmap != null)
album_art.setImageBitmap(albumCoverBitmap);
}else {
// TODO:
Options opts = new Options();
Bitmap albumCoverBitmap = BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.drawable.albumart_mp_unknown_list, opts);
if(albumCoverBitmap != null)
album_art.setImageBitmap(albumCoverBitmap);
}
}
}
}

Related

spinner selected value returns to old value when recyclerview row is clicked

i have created an android application using xamarin.android. the application has a recyclerview that contains a spinner. what i want is when the user selects an item from the spinner, i need to change the value of the corresponding column and row in the datatable and i need the new value to be displayed in the spinner in the recyclerview in the row where the spinner value is selected. the problem is that whenever a value is selected, when another row is clicked, the old value of the spinner is displayed. i tried a lot of ways like the code in the following link: https://www.codeproject.com/articles/1033283/android-recycler-view-with-spinner-item-change-sel, but it didn't work. this is my code:
public class recyclerview_viewholder : RecyclerView.ViewHolder
{
public TextView rownbr, laborname;
public EditText overtime;
public LinearLayout linearLayout;
public Spinner days;
public recyclerview_viewholder(View itemView, Action<int> listener)
: base(itemView)
{
rownbr = itemView.FindViewById<TextView>(Resource.Id.rownbr);
laborname = itemView.FindViewById<TextView>(Resource.Id.laborname);
days = itemView.FindViewById<Spinner>(Resource.Id.days);
overtime = itemView.FindViewById<EditText>(Resource.Id.overtime);
linearLayout = itemView.FindViewById<LinearLayout>(Resource.Id.linearLayout);
itemView.Click += (sender, e) => listener(base.LayoutPosition);
}
public class recyclerviewAdapter : RecyclerView.Adapter
{
// Event handler for item clicks:
public event EventHandler<int> ItemClick;
// public event EventHandler<AdapterView.ItemSelectedEventArgs> SpinnerItemSelectionChanged;
public static DataTable summary_Requests = new DataTable();
//Context context;
public readonly new_schedule context;
public static int selected_pos = -1;
RecyclerView recyclerView;
FloatingActionButton delete;
public recyclerviewAdapter(new_schedule context, DataTable sum_req, RecyclerView recyclerView)
{
this.context = context;
summary_Requests = sum_req;
this.recyclerView = recyclerView;
}
public override RecyclerView.ViewHolder
OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.recycler_view_new_schedule_data, parent, false);
recyclerview_viewholder vh = new recyclerview_viewholder(itemView, OnClick);
vh.days.ItemSelected += (sender, e) =>
{
Spinner spinner = (Spinner)sender;
int position = Convert.ToInt32(spinner.Tag);
summary_Requests.Rows[position]["dayNbr"] = Convert.ToDecimal(spinner.GetItemAtPosition(e.Position).ToString());
};
vh.overtime.TextChanged += (sender, e) =>
{
if (vh.overtime.Text != "")
try
{
int position = vh.LayoutPosition;
summary_Requests.Rows[position]["overtimeHours"] = Convert.ToInt32(vh.overtime.Text);
user.zero_val = "Not_exist";
}
catch (System.FormatException exp)
{
var icon = AppCompatResources.GetDrawable(context.Context, Resource.Drawable.error_ic);
icon.SetBounds(0, 0, 50, 50);
vh.overtime.SetError("unit must be integer not decimal", icon);
user.zero_val = "exits";
}
else if (vh.overtime.Text == "")
{
var icon = AppCompatResources.GetDrawable(context.Context, Resource.Drawable.error_ic);
icon.SetBounds(0, 0, 50, 50);
vh.overtime.SetError("value can not be empty", icon);
user.zero_val = "exits";
}
};
return vh;
}
public override void
OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
recyclerview_viewholder vh = holder as recyclerview_viewholder;
vh.rownbr.Text = summary_Requests.Rows[position]["rowNumber"].ToString();
vh.laborname.Text = summary_Requests.Rows[position]["laborerName"].ToString();
List<decimal> days_data = new List<decimal>();
days_data.Add((decimal)0.5);
days_data.Add((decimal)1);
var adapter = new ArrayAdapter(this.context.Context, Android.Resource.Layout.SimpleSpinnerItem, days_data);
adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
vh.days.Tag = position;
vh.days.Adapter = adapter;
vh.days.SetSelection(1);
vh.overtime.Text = summary_Requests.Rows[position]["overtimeHours"].ToString();
if (selected_pos == position)
vh.ItemView.SetBackgroundColor(Color.ParseColor("#4fa5d5"));
else
vh.ItemView.SetBackgroundColor(Color.LightGray);
vh.ItemView.Click += (sender, e) =>
{
int pos = vh.LayoutPosition;
user.del_pos = position;
selected_pos = position;
NotifyDataSetChanged();
//fill global variables that need to be passed to detail fragment
};
//delete.Click += delegate
//{
// vh.days.Enabled = false;
//};
}
public DataTable get_dt_final()
{
DataTable final_dt = summary_Requests.Copy();
return final_dt;
}
public override long GetItemId(int position)
{
return position;
}
public void deleteItem(int index)
{
summary_Requests.Rows.RemoveAt(index);
NotifyItemRemoved(index);
}
public override int ItemCount
{
get { return summary_Requests.Rows.Count; }
}
// Raise an event when the item-click takes place:
void OnClick(int position)
{
if (ItemClick != null)
ItemClick(this, position);
// user.req_pos = position;
}
}
}
}
I read the article that you provide, you need to do two things when you change spinner value, firstly, you need to change vegeList's itemPosition quantity by SpinnerItemSelectionChangedEvent, then you need to update TotalAmount in OnBindViewHolder
private void SpinnerItemSelectionChangedEvent(object sender, AdapterView.ItemSelectedEventArgs e)
{
Spinner spinner = (Spinner)sender;
var itemPosition = Convert.ToInt32(spinner.Tag);
//Update the view by Total Amount, after spinner value is been selected.
var currentquantity = vegeList[itemPosition].Quantity;
var selectedQuantity = Convert.ToInt32(spinner.GetItemAtPosition(e.Position).ToString());
if (currentquantity != selectedQuantity)
{
vegeList[itemPosition].Quantity = selectedQuantity;
Madapter.NotifyItemChanged(itemPosition);
}
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
var item = Items[position];
var vh = holder as VegeViewHolder;
var spinnerPos = 0;
var adapter = new ArrayAdapter<String>(Context, Android.Resource.Layout.SimpleSpinnerItem, _quantity);
adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
vh.Name.Text = item.Name;
vh.Price.Text = string.Format("Price: ${0}", item.Price);
vh.ItemView.Tag = position;
if (item.Quantity > 0)
{
spinnerPos = adapter.GetPosition(item.Quantity.ToString());
vh.TotalAmount.Text = string.Format("${0}", item.Price * item.Quantity);
}
else
{
vh.TotalAmount.Text = "";
}
vh.Quantity.Tag = position; //keep reference to list view row position
vh.Quantity.Adapter = adapter;
vh.Quantity.SetSelection(spinnerPos);
vh.Image.SetImageResource(item.ImageId);
}

MediaStore select query returns only one row

I'm trying to develop music player, I've made a loader and adapter for my data retreiving from mediastore, but when I call query from my app it only returns one row, I don't know wat's wrong with my code, would u help me fixing that problem?
That's my loader which should return a list I'll use in another place
public static List<Song> getAllArtistSongs(Context context, long artist_id){
List<Song> ArtistSongList = new ArrayList<>();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] projection = new String[]{
"_id",
"title",
"album_id",
"album",
"artist",
"duration",
"track"
};
String sortorder = MediaStore.Audio.Media.DEFAULT_SORT_ORDER;
String selection = "is_music=1 and artist_id="+artist_id;
Cursor cursor = context.getContentResolver().query(uri, projection, selection, null, sortorder);
assert cursor != null;
if (cursor.moveToFirst()) {
do {
int trackNumber = cursor.getInt(6);
while (trackNumber >= 1000) {
trackNumber -= 1000;
}
Long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
Long albumid = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
String albumname = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
String artistname = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
ArtistSongList.add(new Song(id, title, albumid, albumname, artist_id, artistname, duration, trackNumber));
} while (cursor.moveToNext());
cursor.close();
}
return ArtistSongList;
}
And this is the adapter which I use to bind to a recyclerview
public void onBindViewHolder(#NonNull VH holder, int position) {
Song song = artistSongList.get(position);
if(song!=null){
holder.ttv.setText(song.title);
holder.dtv.setText(song.artistName);
int trackN = song.trackNumber;
if(trackN==0){
holder.ntv.setText("_");
}else holder.ntv.setText(String.valueOf(trackN));
}
}
And this is where I call the query func
private void setupAlbumList() {
System.out.println(artistId);
songList = ArtistSongLoader.getAllArtistSongs(getActivity(), artistId);
adapter = new ArtistSongAdapter(getActivity(), songList);
recy.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
recy.setAdapter(new ArtistSongAdapter(getActivity(), songList));
}
Thx in advance for helping
My example to retrieve all tracks:
private final String track_id = MediaStore.Audio.Media._ID;
private final String track_no = MediaStore.Audio.Media.TRACK;
private final String track_name = MediaStore.Audio.Media.TITLE;
private final String artist = MediaStore.Audio.Media.ARTIST;
private final String artist_id = MediaStore.Audio.Media.ARTIST_ID;
private final String duration = MediaStore.Audio.Media.DURATION;
private final String album = MediaStore.Audio.Media.ALBUM;
private final String composer = MediaStore.Audio.Media.COMPOSER;
private final String year = MediaStore.Audio.Media.YEAR;
private final String path = MediaStore.Audio.Media.DATA;
private final String date_added = MediaStore.Audio.Media.DATE_ADDED;
public Cursor getAllTracks(Context context) {
// gets all tracks
if (context != null) {
ContentResolver cr = context.getContentResolver();
final String[] columns = {track_id, track_no, artist, track_name,
album, duration, path, year, composer};
return cr.query(uri, columns, null, null, null);
} else {
return null;
}
}
then you have
String selection = "is_music=1"
first, you do not need is_music=1. For multiple tracks you of course need more than 1 track by the same artist
The adapter is irrelevant, the query does the selection
To return albums for an artist
public Cursor getArtistsAlbumcursor(Context context, String artistId) {
ContentResolver cr = context.getContentResolver();
final String _id = MediaStore.Audio.Media._ID;
final String album_id = MediaStore.Audio.Media.ALBUM_ID;
final String artistid = MediaStore.Audio.Media.ARTIST_ID;
final String[] columns = {_id, album_id, artistid};
if (artistId != null) {
String where = artistid + " =?";
String[] aId = {artistId};
return cr.query(uri, columns, where, aId, null);
} else {
return null;
}
}

Read Data attributes or Custom Attributes in SQL server from string

I want in SQL prepared dynamic query based on the shortcode.
For Eg.
DECLARE #ShortCode VARCHAR(MAX)
SET #ShortCode = '[User data="Name" data="MobileNumber"]';
User = table name
Name = User table field
MobileNumber = User table field
Query output be like
SELECT [Name],[MobileNumber] FROM [dbo].[User]
SET #ShortCode = '[Country data="Name" ID="1"]';
Country = table name
Name = Country table field
ID = User table field
Query output be like
SELECT [Name] FROM [dbo].[Country] WHERE [ID] = 1
How to extract all data attributes values and how to get User in the []
This functionality is done in C#
Here My c# code
// Model class
public class ShortCodeResult
{
public Guid? ID { get; set; }
public string TableName { get; set; }
public bool IsValidShortCode { get; set; }
public string Message { get; set; }
public Dictionary<string,object> KeyValue { get; set; }
public ShortCodeResult() {
KeyValue = new Dictionary<string, object>();
ID = Guid.NewGuid();
}
}
//Regex Filter
public class RegexFilter
{
private string oPattern = #"(\w+)=[\""]([a-zA-Z0-9_.:\""]+)";
public ShortCodeResult GetShortCodeValues(string Code)
{
var oShortCodeModel = new ShortCodeResult();
var oRegex = new Regex(oPattern, RegexOptions.IgnoreCase);
var oTableNameRegex = Regex.Match(Code, #"\b[A-Za-z]+\b", RegexOptions.Singleline).Value;
var lstMatchCollection = oRegex.Matches(Code).Cast<Match>().Where(x=>x.Value.StartsWith("data")).ToList();
if (lstMatchCollection != null && lstMatchCollection.Count > 0)
{
for (int i = 0; i < lstMatchCollection.Count; i++)
{
var oSelected = new Regex("[^=]+$").Match(Convert.ToString(lstMatchCollection[i]));
if (oSelected != null)
{
oShortCodeModel.KeyValue.Add(i.ToString(), oSelected.Value.Trim('"'));
}
}
}
oShortCodeModel.TableName = oTableNameRegex;
return oShortCodeModel;
}
}
//HtmlHelper Extension
public static MvcHtmlString RenderShortCode(this HtmlHelper htmlHelper, string IdOrExprssion)
{
#region Get short code data
var oShortCode = ShortCodeHelper.GetShortCode(IdOrExprssion);
#endregion
var oMvcHtmlString = new MvcHtmlString(IdOrExprssion);
var oRegexFilter = new RegexFilter();
var shortCodeModel = oRegexFilter.GetShortCodeValues(oShortCode.Expression);
var ostringBuilder = new StringBuilder();
if (!string.IsNullOrEmpty(shortCodeModel.TableName))
{
ostringBuilder.AppendLine("SELECT ");
ostringBuilder.AppendLine((shortCodeModel.KeyValue.Count > 0 ? string.Join(",", shortCodeModel.KeyValue.Select(x => x.Value)) : "*"));
ostringBuilder.AppendLine(" FROM ");
ostringBuilder.AppendLine(oShortCode.TableName);
ostringBuilder.AppendLine(" WITH(NOLOCK) ");
if (oShortCode.FilterCode.Count() > 0)
{
ostringBuilder.AppendLine("WHERE ");
foreach (var filterCode in oShortCode.FilterCode)
{
ostringBuilder.AppendLine(filterCode.FilterColumnName);
ostringBuilder.AppendLine(filterCode.Operator);
ostringBuilder.AppendLine(filterCode.FilterColumnValue);
}
}
}
var oDyanamicData = DBHelper.GetDataTable(ostringBuilder.ToString(), System.Data.CommandType.Text, new List<SqlParameter>());
if (oDyanamicData != null)
{
if (oShortCode.IsHtmlRender)
{
for (int i = 0; i < oDyanamicData.Rows.Count; i++)
{
for (int j = 0; j < oDyanamicData.Columns.Count; j++)
{
string key = Convert.ToString(oDyanamicData.Columns[j]);
string value = Convert.ToString(oDyanamicData.Rows[i].ItemArray[j]);
if (oShortCode.DisplayCode.Count > 0)
{
var displayCode = oShortCode.DisplayCode.FirstOrDefault(x => x.DisplayColumnName == key);
if (displayCode != null && !string.IsNullOrEmpty(displayCode?.ReplaceKey))
{
oShortCode.DefinedHtml = oShortCode.DefinedHtml.Replace(displayCode.ReplaceKey, value);
}
}
}
}
return new MvcHtmlString(oShortCode.DefinedHtml);
}
else
{
string key = string.Empty, value = string.Empty;
#region For Json
List<JObject> dataList = new List<JObject>();
for (int i = 0; i < oDyanamicData.Rows.Count; i++)
{
JObject eachRowObj = new JObject();
for (int j = 0; j < oDyanamicData.Columns.Count; j++)
{
key = Convert.ToString(oDyanamicData.Columns[j]);
value = Convert.ToString(oDyanamicData.Rows[i].ItemArray[j]);
eachRowObj.Add(key, value);
}
dataList.Add(eachRowObj);
}
return new MvcHtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(dataList));
#endregion
}
}
return oMvcHtmlString;
}
Can anyone help me solved above in SQL server or prepared query in store procedure

how to use getItemCount for show all ViewHolder in recyclerAdapter?

how to use getItemCount for show all ViewHolder in recyclerAdapter?
I want show all viewHolder in recycler and in getItemCount What should i write؟
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<ModelItem_slider> requestItemsSlider;
private ArrayList<ModelItem_volume> requestItemsVolume;
private ArrayList<ModelItem_volume2> requestItemsVolume2;
private ArrayList<ModelItem_numbers> requestItemsNumber;
private ArrayList<ModelItem_news> requestItemsNews;
private Object[] myData;
private Context context;
public RecyclerAdapter(Context context
, ArrayList<ModelItem_slider> requestItems
, ArrayList<ModelItem_volume> requestItems1
, ArrayList<ModelItem_numbers> requestItems2
, ArrayList<ModelItem_news> requestItems3
, ArrayList<ModelItem_volume2> requestItems4
) {
this.context = context;
this.requestItemsSlider = requestItems;
this.requestItemsVolume = requestItems1;
this.requestItemsNumber = requestItems2;
this.requestItemsNews = requestItems3;
this.requestItemsVolume2 = requestItems4;
}
// viewHolders
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 0:
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_slider, parent, false);
return new SliderViewHolder(view);
case 1:
View view2 = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_volume, parent, false);
return new VolumeViewHolder(view2);
case 2:
View view3 = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_news, parent, false);
return new NewsViewHolder(view3);
case 3:
View view4 = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_volume2, parent, false);
return new Volume2ViewHolder(view4);
default:
View view1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_number, parent, false);
return new NumberViewHolder(view1);
}
}
/// onBind and position
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof SliderViewHolder) {
final ModelItem_slider modelItem = requestItemsSlider.get(position);
((SliderViewHolder) holder).textSliderView.image(modelItem.getUrl());
((SliderViewHolder) holder).sliderLayout.addSlider(((SliderViewHolder) holder).textSliderView);
} else if (holder instanceof NumberViewHolder) {
final ModelItem_numbers modelItem_numbers = requestItemsNumber.get(position);
((NumberViewHolder) holder).name_number.setText(modelItem_numbers.getName_number());
((NumberViewHolder) holder).value_nubmer.setText(modelItem_numbers.getValue_number());
((NumberViewHolder) holder).profit_number.setText(modelItem_numbers.getProfit_number());
} else if (holder instanceof NewsViewHolder) {
final ModelItem_news modelItem1 = requestItemsNews.get(position);
((NewsViewHolder) holder).news.setText(modelItem1.getNews());
((NewsViewHolder) holder).news1.setText(modelItem1.getNews1());
} else if (holder instanceof VolumeViewHolder) {
ModelItem_volume modelItem_volume = requestItemsVolume.get(position);
((VolumeViewHolder) holder).name_volume.setText(modelItem_volume.getName_volume());
((VolumeViewHolder) holder).value_volume.setText(modelItem_volume.getValue_volume());
((VolumeViewHolder) holder).profit_volume.setText(modelItem_volume.getProfit_volume());
}else if (holder instanceof Volume2ViewHolder) {
ModelItem_volume2 modelItem_volume2 = requestItemsVolume2.get(position);
((Volume2ViewHolder) holder).name2.setText(modelItem_volume2.getName2());
((Volume2ViewHolder) holder).value2.setText(modelItem_volume2.getValue2());
((Volume2ViewHolder) holder).profit2.setText(modelItem_volume2.getProfit2());
}
}
#Override
public int getItemViewType(int position) {
return position > 0 ? 1 : 0;
}
/// i need help here
#Override
public int getItemCount() {
return requestItemsSlider.size();
}
in my activity and recuclerAdapter is not null in my project
this is for example
recyclerAdapter = new RecyclerAdapter(BaseActivity.getContext(), null, null, null, null, null);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(BaseActivity.getContext());
linearLayoutManager.setOrientation(LinearLayout.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(recyclerAdapter);
Inside the return.What amount to put To show all the cells.
I think you can use it like this:
#Override
public int getItemCount() {
return 2;
}

Bukkit NullPointerException onEnable()

I've been working on a new plugin, and when I load it up, it gives me a "NullPointerException" error, and I can't seem to find where it could find an error. Here is the error:
[20:15:45] [Server thread/INFO]: [EntityManager] Enabling EntityManager v3.0.0.4
[20:15:45] [Server thread/INFO]: [0;31;1mEntityManager [0;32;1m3.0.0.4[0;36;1m Enabled![m
[20:15:45] [Server thread/ERROR]: Error occurred while enabling EntityManager v3.0.0.4 (Is it up to date?)
java.lang.NullPointerException
at me.AngryCupcake274.EntityManager.EntityManager.loadConfiguration(EntityManager.java:296) ~[?:?]
at me.AngryCupcake274.EntityManager.EntityManager.onEnable(EntityManager.java:63) ~[?:?]
at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:316) ~[spigot.jar:git-Spigot-1649]
at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:332) [spigot.jar:git-Spigot-1649]
at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:417) [spigot.jar:git-Spigot-1649]
at org.bukkit.craftbukkit.v1_7_R4.CraftServer.loadPlugin(CraftServer.java:476) [spigot.jar:git-Spigot-1649]
at org.bukkit.craftbukkit.v1_7_R4.CraftServer.enablePlugins(CraftServer.java:394) [spigot.jar:git-Spigot-1649]
at net.minecraft.server.v1_7_R4.MinecraftServer.n(MinecraftServer.java:360) [spigot.jar:git-Spigot-1649]
at net.minecraft.server.v1_7_R4.MinecraftServer.g(MinecraftServer.java:334) [spigot.jar:git-Spigot-1649]
at net.minecraft.server.v1_7_R4.MinecraftServer.a(MinecraftServer.java:290) [spigot.jar:git-Spigot-1649]
at net.minecraft.server.v1_7_R4.DedicatedServer.init(DedicatedServer.java:210) [spigot.jar:git-Spigot-1649]
at net.minecraft.server.v1_7_R4.MinecraftServer.run(MinecraftServer.java:458) [spigot.jar:git-Spigot-1649]
at net.minecraft.server.v1_7_R4.ThreadServerApplication.run(SourceFile:628) [spigot.jar:git-Spigot-1649]
package me.AngryCupcake274.EntityManager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.*;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
public class EntityManager extends JavaPlugin implements Listener {
RemoveEntities reme;
CommandHandler comh;
CleanEntities cent;
int loopdelay;
String oneminutemessage;
String oneminutecolor;
String threesecondsmessage;
String threesecondscolor;
String twosecondsmessage;
String twosecondscolor;
String onesecondmessage;
String onesecondcolor;
String finalmessage;
String finalcolor;
String oneMinWarn;
String threeSecWarn;
String twoSecWarn;
String oneSecWarn;
String removeInfo;
String[] worldNames;
Server server = Bukkit.getServer();
ConsoleCommandSender console = server.getConsoleSender();
PluginDescriptionFile pdf = this.getDescription();
String pdfEnable = ChatColor.RED + pdf.getName() + " " + ChatColor.GREEN
+ pdf.getVersion() + ChatColor.AQUA + " Enabled!";
String pdfDisable = ChatColor.RED + pdf.getName() + " " + ChatColor.GREEN
+ pdf.getVersion() + ChatColor.DARK_PURPLE + " Enabled!";
Player cleaner;
int counter = 0;
int totalcounter = 0;
#Override
public void onEnable() {
console.sendMessage(pdfEnable);
BukkitScheduler scheduler = Bukkit.getServer().getScheduler();
saveDefaultConfig();
loadConfiguration();
scheduler.scheduleSyncRepeatingTask(this, new Runnable() {
#Override
public void run() {
for (int first = 0; first >= 1; first++) {
cleanUp();
}
}
}, 0L, 12000L);
}
#Override
public void onDisable() {
console.sendMessage(pdfDisable);
}
#SuppressWarnings("deprecation")
public void cleanUp() {
// warn
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(oneMinWarn);
}
console.sendMessage(oneMinWarn);
BukkitScheduler warn3 = Bukkit.getServer().getScheduler();
warn3.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(threeSecWarn);
}
console.sendMessage(threeSecWarn);
}
}, 1220L);
BukkitScheduler warn2 = Bukkit.getServer().getScheduler();
warn2.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(twoSecWarn);
}
console.sendMessage(twoSecWarn);
}
}, 1240L);
BukkitScheduler warn1 = Bukkit.getServer().getScheduler();
warn1.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(oneSecWarn);
}
console.sendMessage(oneSecWarn);
}
}, 1260L);
BukkitScheduler doAction = Bukkit.getServer().getScheduler();
doAction.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
reme.removeEntities();
}
}, 1280L);
}
#SuppressWarnings("deprecation")
public void cleanUpCommand() {
// warn
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(threeSecWarn);
}
console.sendMessage(threeSecWarn);
BukkitScheduler warn2c = Bukkit.getServer().getScheduler();
warn2c.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(twoSecWarn);
}
console.sendMessage(twoSecWarn);
}
}, 20L);
BukkitScheduler warn1c = Bukkit.getServer().getScheduler();
warn1c.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(oneSecWarn);
}
console.sendMessage(oneSecWarn);
}
}, 40L);
BukkitScheduler doAction = Bukkit.getServer().getScheduler();
doAction.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
player.sendMessage(removeInfo);
}
console.sendMessage(removeInfo);
}
}, 60L);
}
public void cleanUpCommand2() {
BukkitScheduler doAction = Bukkit.getServer().getScheduler();
doAction.scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
reme.removeEntities();
}
}, 0L);
}
public void loadConfiguration() {
String ltime = "looptime";
String onemmsg = "oneminute.message";
String onemcolor = "oneminute.color";
String threesmsg = "threeseconds.message";
String threescolor = "threeseconds.color";
String twosmsg = "twoseconds.message";
String twoscolor = "twoseconds.color";
String onesmsg = "onesecond.message";
String onescolor = "onesecond.color";
String fmsg = "final.message";
String fcolor = "final.color";
String arrowr = "arrow";
String boatr = "boat";
String itemr = "dropped_item";
String eggr = "egg";
String enderdragonr = "ender_dragon";
String enderpearlr = "ender_pearl";
String endersignalr = "ender_signal";
String xporbr = "experience_orb";
String fireballr = "fireball";
String fireworkr = "firework";
String fishinghookr = "fishing_hook";
String itemframer = "item_frame";
String leashr = "leash_hitch";
String lightningr = "lightning";
String minecartr = "minecart";
String minecartchestr = "minecart_chest";
String minecartcommandr = "minecart_command";
String minecartfurnacer = "minecart_furnace";
String minecarthopperr = "minecart_hopper";
String minecartmobspawnerr = "minecart_mob_spawner";
String minecarttntr = "minecart_tnt";
String paintingr = "painting";
String primedtntr = "primed_tnt";
String sfireballr = "small_fireball";
String snowballr = "snowball";
String splashpotionr = "splash_potion";
String expbottler = "exp_bottle";
String thrownxpbottler = "thrown_exp_bottle";
String witherskullr = "wither_skull";
getConfig().addDefault(ltime, (10 * 60 * 20));
getConfig().addDefault(onemmsg,
"Ground items will be removed in 1 minute!");
getConfig().addDefault(onemcolor, "AQUA");
getConfig().addDefault(threesmsg,
"Ground items will be removed in 3 seconds!");
getConfig().addDefault(threescolor, "DARK_GREEN");
getConfig().addDefault(twosmsg, "2 seconds!");
getConfig().addDefault(twoscolor, "GOLD");
getConfig().addDefault(onesmsg, "1 second!");
getConfig().addDefault(onescolor, "RED");
getConfig().addDefault(fmsg, "Ground items will be removed!");
getConfig().addDefault(fcolor, "DARK_RED");
getConfig().addDefault(arrowr, true);
getConfig().addDefault(boatr, false);
getConfig().addDefault(itemr, true);
getConfig().addDefault(eggr, true);
getConfig().addDefault(enderdragonr, false);
getConfig().addDefault(enderpearlr, true);
getConfig().addDefault(endersignalr, true);
getConfig().addDefault(xporbr, true);
getConfig().addDefault(fireballr, true);
getConfig().addDefault(fireworkr, true);
getConfig().addDefault(fishinghookr, false);
getConfig().addDefault(itemframer, false);
getConfig().addDefault(leashr, false);
getConfig().addDefault(lightningr, true);
getConfig().addDefault(minecartr, false);
getConfig().addDefault(minecartchestr, false);
getConfig().addDefault(minecartcommandr, false);
getConfig().addDefault(minecartfurnacer, false);
getConfig().addDefault(minecarthopperr, false);
getConfig().addDefault(minecartmobspawnerr, false);
getConfig().addDefault(minecarttntr, false);
getConfig().addDefault(paintingr, false);
getConfig().addDefault(primedtntr, true);
getConfig().addDefault(sfireballr, true);
getConfig().addDefault(snowballr, true);
getConfig().addDefault(splashpotionr, true);
getConfig().addDefault(expbottler, true);
getConfig().addDefault(thrownxpbottler, true);
getConfig().addDefault(witherskullr, true);
getConfig().options().copyDefaults(true);
saveConfig();
loopdelay = getConfig().getInt("looptime");
oneminutemessage = getConfig().getString("oneminute.message");
oneminutecolor = getConfig().getString("oneminute.color");
threesecondsmessage = getConfig().getString("threeseconds.message");
threesecondscolor = getConfig().getString("threeseconds.color");
twosecondsmessage = getConfig().getString("twoseconds.message");
twosecondscolor = getConfig().getString("twoseconds.color");
onesecondmessage = getConfig().getString("onesecond.message");
onesecondcolor = getConfig().getString("onesecond.color");
finalmessage = getConfig().getString("final.message");
finalcolor = getConfig().getString("final.color");
oneMinWarn = ChatColor.valueOf(oneminutecolor) + oneminutemessage;
threeSecWarn = ChatColor.valueOf(threesecondscolor)
+ threesecondsmessage;
twoSecWarn = ChatColor.valueOf(twosecondscolor) + twosecondsmessage;
oneSecWarn = ChatColor.valueOf(onesecondcolor) + onesecondmessage;
removeInfo = ChatColor.valueOf(finalcolor) + finalmessage;
reme.arrow = getConfig().getBoolean("arrow");
reme.boat = getConfig().getBoolean("boat");
reme.droppeditem = getConfig().getBoolean("dropped_item");
reme.egg = getConfig().getBoolean("egg");
reme.enderpearl = getConfig().getBoolean("ender_pearl");
reme.endersignal = getConfig().getBoolean("ender_signal");
reme.experienceorb = getConfig().getBoolean("experience_orb");
reme.fireball = getConfig().getBoolean("fireball");
reme.firework = getConfig().getBoolean("firework");
reme.fishinghook = getConfig().getBoolean("fishing_hook");
reme.itemframe = getConfig().getBoolean("item_frame");
reme.leashhitch = getConfig().getBoolean("leash_hitch");
reme.lightning = getConfig().getBoolean("lightning");
reme.minecart = getConfig().getBoolean("minecart");
reme.minecartchest = getConfig().getBoolean("minecart_chest");
reme.minecartcommand = getConfig().getBoolean("minecart_command");
reme.minecartfurnace = getConfig().getBoolean("minecart_furnace");
reme.minecarthopper = getConfig().getBoolean("minecart_hopper");
reme.minecartmobspawner = getConfig().getBoolean("minecart_mob_spawner");
reme.minecarttnt = getConfig().getBoolean("minecart_tnt");
reme.painting = getConfig().getBoolean("painting");
reme.primedtnt = getConfig().getBoolean("primed_tnt");
reme.smallfireball = getConfig().getBoolean("small_fireball");
reme.snowball = getConfig().getBoolean("snowball");
reme.splashpotion = getConfig().getBoolean("splash_potion");
reme.thrownexpbottle = getConfig().getBoolean("exp_bottle");
reme.witherskull = getConfig().getBoolean("wither_skull");
saveDefaultConfig();
}
public void reloadPlugin() {
reloadConfig();
loopdelay = getConfig().getInt("looptime");
oneminutemessage = getConfig().getString("oneminute.message");
oneminutecolor = getConfig().getString("oneminute.color");
threesecondsmessage = getConfig().getString("threeseconds.message");
threesecondscolor = getConfig().getString("threeseconds.color");
twosecondsmessage = getConfig().getString("twoseconds.message");
twosecondscolor = getConfig().getString("twoseconds.color");
onesecondmessage = getConfig().getString("onesecond.message");
onesecondcolor = getConfig().getString("onesecond.color");
finalmessage = getConfig().getString("final.message");
finalcolor = getConfig().getString("final.color");
reme.arrow = getConfig().getBoolean("arrow");
reme.boat = getConfig().getBoolean("boat");
reme.droppeditem = getConfig().getBoolean("dropped_item");
reme.egg = getConfig().getBoolean("egg");
reme.enderpearl = getConfig().getBoolean("ender_pearl");
reme.endersignal = getConfig().getBoolean("ender_signal");
reme.experienceorb = getConfig().getBoolean("experience_orb");
reme.fireball = getConfig().getBoolean("fireball");
reme.firework = getConfig().getBoolean("firework");
reme.fishinghook = getConfig().getBoolean("fishing_hook");
reme.itemframe = getConfig().getBoolean("item_frame");
reme.leashhitch = getConfig().getBoolean("leash_hitch");
reme.lightning = getConfig().getBoolean("lightning");
reme.minecart = getConfig().getBoolean("minecart");
reme.minecartchest = getConfig().getBoolean("minecart_chest");
reme.minecartcommand = getConfig().getBoolean("minecart_command");
reme.minecartfurnace = getConfig().getBoolean("minecart_furnace");
reme.minecarthopper = getConfig().getBoolean("minecart_hopper");
reme.minecartmobspawner = getConfig().getBoolean("minecart_mob_spawner");
reme.minecarttnt = getConfig().getBoolean("minecart_tnt");
reme.painting = getConfig().getBoolean("painting");
reme.primedtnt = getConfig().getBoolean("primed_tnt");
reme.smallfireball = getConfig().getBoolean("small_fireball");
reme.snowball = getConfig().getBoolean("snowball");
reme.splashpotion = getConfig().getBoolean("splash_potion");
reme.thrownexpbottle = getConfig().getBoolean("exp_bottle");
reme.witherskull = getConfig().getBoolean("wither_skull");
getServer().getScheduler().cancelTasks(this);
getServer().getPluginManager().disablePlugin(this);
getServer().getPluginManager().enablePlugin(this);
}
}
me.AngryCupcake274.EntityManager.EntityManager.loadConfiguration(EntityManager.java:296)
The exception is thrown at line 296 of your EntityManager.java file.
reme.arrow = getConfig().getBoolean("arrow");
At this point of time reme is still null and therefore you can't assign arrow.
You should ensure that RemoveEntitites is already instantiated once you call loadConfiguration() in your onEnable() method.
Also see What is a NPE and how do I fix it?.
I did it!
Instead of setting the RemoveEntities variables, I told the RemoveEntities class to find the variables in the EntityManager class.