duplicate value when showing image in costume gridview - java

Im having a hard time to figure it out why my image are showing duplicate in my costume grid (staggeredgridview)
the progam using lazy method to fetch image from webservice and insert into db , if user access the program without internet or accesss the old image data will be fetch from local db instead.
here is my main class :
private int index;
private Mysecondworker msw;
private main activity;
private String value;
private int filter = 0;
private boolean isLoading = false;
private int Sort = 0;
private StaggeredGridView mystaggerdgridview ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mystaggerdgridview = (StaggeredGridView) findViewById(R.id.grid);
mystaggerdgridview.setColumnCount(2);
activity = this;
loadingisactive(true);
msw = new Mysecondworker(activity, value, String.valueOf(index++), 0,0);
msw.execute();
mystaggerdgridview .setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(ViewGroup view, int scrollState) {
public void onScroll(ViewGroup view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
boolean needtofetchMore = firstVisibleItem + visibleItemCount >= totalItemCount ;
if (needtofetchMore && !loadingisactive){
loadingisactive= true;
hw = new Mysecondworker(activity, value, String.valueOf(index++), filter,Sort);
hw.execute();
}
}
});
}
private Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread() {
#Override
public void run() {
try {
runnable.run();
} finally {
}
}
};
t.start();
return t;
}
public void setloadingisactive(boolean flag){
loadingisactive= flag;
}
and my Mysecondworker class :
public class Mysecondworker
extends
AsyncTask<String, String, AsyncTaskResult<ArrayList<HashMap<String, String>>>> {
private main targetCtx;
private String Mysecondworker_key;
myAdapter myadapter;
private LinearLayout Mysecondworker_progress;
private String Mysecondworker_index , Mysecondworker_sort;
private int Mysecondworker_filter = 0;
private LinearLayout Mysecondworker_pagination;
private ImageView Mysecondworker_imgPagination;
private AnimationDrawable Mysecondworker_frameAnimation;
private String Mysecondworker_lastID = "0";
private StaggeredGridView mystaggerdgridview ;
public Mysecondworker(main mycontext, String mykey, String myindex, int myfilter,int mysort) {
this.targetCtx = mycontext;
Mysecondworker_key = mykey;
mystaggerdgridview = (StaggeredGridView) targetCtx.findViewById(id.grid);
Mysecondworker_index = myindex;
Mysecondworker_filter = myfilter;
Mysecondworker_sort = String.valueOf(mysort);
Mysecondworker_pagination = (LinearLayout) targetCtx.findViewById(id.pagination_load);
Mysecondworker_imgPagination = (ImageView) targetCtx
.findViewById(id.loadingpaginganimation);
#Override
protected void onPreExecute() {
progress = (LinearLayout) targetCtx.findViewById(R.id.progress);
if (Integer.parseInt(index) == 0)
Mysecondworker_progress.setVisibility(View.VISIBLE);
Mysecondworker_pagination.setVisibility(View.VISIBLE);
Mysecondworker_imgPagination.setBackgroundResource(R.anim.loadanimation);
Mysecondworker_frameAnimation = (AnimationDrawable) Mysecondworker_imgPagination.getBackground();
Mysecondworker_frameAnimation.start();
//finding the last id of images
myAdapter mAd = (myAdapter) mystaggerdgridview.getAdapter();
if (mAd != null && mAd.getCount() > 0) {
lastID = mAd.getData().get(mAd.getCount() - 1).get("id");
}else
lastID = "0";
}
#Override
protected AsyncTaskResult<ArrayList<HashMap<String, String>>> doInBackground(
String... param) {
try {
String xml = [[[getting image from web service with unique id for each one]]]
SaxXmlParser mygalleryparser = new SaxXmlParser(xml, "imagegallery");
mygalleryparser.runParser();
if (Integer.parseInt(Mysecondworker_index) == 0 && Integer.parseInt(Mysecondworker_key) > 0) {
table_imagegallery obj_imagegallery = new table_imagegallery();
obj_imagegallery.subjectId = Integer.parseInt(Mysecondworker_key);
obj_imagegallery.DeleteBySubjectId();
}
for (HashMap<String, String> hashMap : mygalleryparser.getParsedData()) {
table_imagegallery imagegallery = new table_imagegallery();
imagegallery.id = Integer.parseInt(hashMap.get("id"));
if (Integer.parseInt(key) < 1) {
imagegallery.Delete();
}
imagegallery.imgageurl = hashMap.get("imageurlfromxml");
imagegallery.Insert();
}
AsyncTaskResult<ArrayList<HashMap<String, String>>> myresult = new AsyncTaskResult<ArrayList<HashMap<String, String>>>(
mygalleryparser.getParsedData());
return myresult;
} catch (Exception e) {
ArrayList<HashMap<String, String>> myresult = new ArrayList<HashMap<String, String>>();
table_imagegallery forofflinefetch = new table_imagegallery();
List<table_imagegallery> Off_imagegallery = new ArrayList<table_imagegallery>();
switch (Integer.parseInt(Mysecondworker_key)) {
case -1:
if (Integer.parseInt(Mysecondworker_index) == 0)
Off_imagegallery = forofflinefetch.GetAllImages();
break;
}
for (table_imagegallery imagegallery : Off_imagegallery) {
HashMap<String, String> mapforimage = new HashMap<String, String>();
mapforimage.put("id", String.valueOf(imagegallery.id));
mapforimage.put("thumb_url1", imagegallery.imgageurl);
myresult.add(mapforimage);
}
AsyncTaskResult<ArrayList<HashMap<String, String>>> myresultReturn = new AsyncTaskResult<ArrayList<HashMap<String, String>>>(
myresult , true);
return myresultReturn;
}
}
#Override
protected void onPostExecute(
AsyncTaskResult<ArrayList<HashMap<String, String>>> myresult) {
Mysecondworker_progress.setVisibility(View.GONE);
Mysecondworker_frameAnimation.stop();
Mysecondworker_pagination.setVisibility(View.GONE);
if (myresult.getError() != null) {
//[[[errorr apear here]]]];
} else {
myAdapter mAd = (myAdapter) mystaggerdgridview.getAdapter();
ArrayList<HashMap<String, String>> outputResult = new ArrayList<HashMap<String, String>>();
if (mAd != null && mAd.getCount() > 0) {
outputResult = mAd.getData();
}
outputResult.addAll(myresult.getResult());
if (mAd == null) {
myadapter = new myAdapter(targetCtx, outputResult);
mystaggerdgridview.setAdapter(myadapter);
} else {
mAd.notifyDataSetChanged();
}
if (!myresult.checkforofline())
targetCtx.setloadingisactive(false);
}
}
}
and here is my async class :
public class AsyncTaskResult<T> {
private T myresult = null;
private Exception error = null;
private boolean _checkforofline = false;
public T getResult() {
return myresult;
}
public Exception getError() {
return error;
}
public AsyncTaskResult(T myresult) {
super();
this.myresult = myresult;
}
public AsyncTaskResult(T myresult,boolean isOffline) {
super();
this.myresult = myresult;
_checkforofline = checkforofline;
}
public AsyncTaskResult() {
super();
}
public AsyncTaskResult(Exception error) {
super();
this.error = error;
}
public boolean checkforofline() {
return _checkforofline;
}
and madapter class :
public myAdapter(Activity act, ArrayList<HashMap<String, String>> listhast) {
myactivity = act;
mydata=listhast;
myinflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myimageLoader=new ImageLoader(activity.getApplicationContext(),true);
}
private Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread() {
#Override
public void run() {
try {
runnable.run();
} finally {
}
}
};
t.start();
return t;
}
public int getCount() {
return mydata.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public ArrayList<HashMap<String, String>> getData(){
return mydata;
}
public View getView(final int position, View convertView, ViewGroup parent) {
try {
final myviewholder viewHolder;
final HashMap<String, String> my_data_base_on_position = mydata.get(position);
if (convertView == null) {
if(Integer.parseInt(my_data_base_on_position.get("id")) % 2 == 1){
convertView = mInflater.inflate(R.layout.layoutright, parent, false);
}else{
convertView = mInflater.inflate(R.layout.layoutleft, parent, false);
}
viewHolder = new myviewholder();
viewHolder.tv0 = (TextView) convertView.findViewById(R.id.textid);
viewHolder.imageurl = (ImageView) convertView.findViewById(R.id.image);
convertView.setTag(viewHolder);
}else{
viewHolder = (myviewholder) convertView.getTag();
}
LayoutParams lp;
if(data.size() > 0 ){
viewHolder.tv0.setText(my_data_base_on_position.get("id"));
viewHolder.tv0.setTag(my_data_base_on_position.get("id"));
classtoloadimagefromurl.DisplayImage(my_data_base_on_position.get("imageurl"), viewHolder.imageurl);
lp = new LayoutParams(convertView.getLayoutParams());
lp.span = 1;
convertView.setLayoutParams(lp);
return convertView;
}else{
convertView = mInflater.inflate(R.layout.noimage, parent, false);
lp = new LayoutParams(convertView.getLayoutParams());
lp.span = 1;
convertView.setLayoutParams(lp);
return convertView;
}
}
intresting if i use listview instead of staggeredgrid in my madapter class everything goes fine but if i choose to show item in uneven ui , dupplicate value apears when it try to fetch !
this is the error :
01-09 11:51:52.656: E/Database(29557): Error inserting imagegallery
01-09 11:51:52.656: E/Database(29557): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
01-09 11:51:52.656: E/Database(29557): at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
01-09 11:51:52.656: E/Database(29557): at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:61)
01-09 11:51:52.656: E/Database(29557): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1584)
01-09 11:51:52.656: E/Database(29557): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1428)
01-09 11:51:52.656: E/Database(29557): at com.imagegallery.Tabel_for_images.Insert(Tabel_for_images.java:109)
01-09 11:51:52.656: E/Database(29557): at com.imagegallery.Mysecondworker.doInBackground(Mysecondworker.java:141)
01-09 11:51:52.656: E/Database(29557): at com.imagegallery.Mysecondworker.doInBackground(Mysecondworker.java:1)
01-09 11:51:52.656: E/Database(29557): at android.os.AsyncTask$2.call(AsyncTask.java:185)
01-09 11:51:52.656: E/Database(29557): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
01-09 11:51:52.656: E/Database(29557): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
01-09 11:51:52.656: E/Database(29557): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
01-09 11:51:52.656: E/Database(29557): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
01-09 11:51:52.656: E/Database(29557): at java.lang.Thread.run(Thread.java:1019)

Related

How to use holder.todoCheckbox.setChecked? RecyclerView

How to use holder.todoCheckbox.setChecked (todoBool);
I have a recycler view that contains 3 view holders.
I have got a MainActivity, HeaderFooterAdapter, SimpleItamAdapter.
I have the logic when I click on a checkbox that the list will filter. In the setOnCheckedChangeListener I set the variables todoBool, doneBool, projectBool to the new truth values.
Then I would like to set the checkboxes to true or false depending on these values.
The problem occurs on this line of code
holder.todoCheckbox.setChecked(todoBool);
This causes a crash in the app.
public void onBindHeaderItemViewHolder(#NonNull HeaderViewHolder holder, int localPosition) {
applyFullSpanForStaggeredGridLayoutManager(holder);
//This following 3 lines causes error. how to manage this?
holder.todoCheckbox.setChecked(todoBool);
holder.doneCheckbox.setChecked(doneBool);
holder.projektCheckbox.setChecked(projectBool);
holder.todoCheckbox.setOnCheckedChangeListener(…); //here i set to Bools
holder.doneCheckbox.setOnCheckedChangeListener(…);
holder.projektCheckbox.setOnCheckedChangeListener(…);
}
I tried that. Also causes crash in the app.
holder.todoCheckbox.setChecked(false);
holder.doneCheckbox.setChecked(false);
holder.projektCheckbox.setChecked(false);
What do i do wrong?
I pushed everythink here. The "localBranch" is the not working one. The "devMaster" works. https://github.com/SaschaGolod/T09b.10-Exercise-AddViewModelToAddTaskActivity
Many thanks if someone can help me here
Here is my whole adapter class:
package com.example.android.todolist.adapters;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import com.example.android.todolist.R;
import com.h6ah4i.android.widget.advrecyclerview.utils.RecyclerViewAdapterUtils;
import com.h6ah4i.android.widget.advrecyclerview.utils.WrapperAdapterUtils;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import static com.example.android.todolist.MainActivity.onItemClickedDefault;
import static com.example.android.todolist.MainActivity.onItemClickedDone;
import static com.example.android.todolist.MainActivity.onItemClickedProject;
import static com.example.android.todolist.MainActivity.onItemClickedTodo;
public class DemoHeaderFooterAdapter
extends AbstractHeaderFooterWrapperAdapter<DemoHeaderFooterAdapter.HeaderViewHolder, DemoHeaderFooterAdapter.FooterViewHolder>
implements View.OnClickListener {
private static final String TAG = "DemoHeaderFooterAdapter";
private OnListItemClickMessageListener mOnItemClickListener;
private Context mContext;
private boolean todoBool = false;
private boolean doneBool = false;
private boolean projectBool = false;
static class HeaderViewHolder extends RecyclerView.ViewHolder {
private CheckBox todoCheckbox;
private CheckBox doneCheckbox;
private CheckBox projektCheckbox;
HeaderViewHolder(View itemView) {
super(itemView);
todoCheckbox = itemView.findViewById(R.id.todoCheckboxID);
doneCheckbox = itemView.findViewById(R.id.doneCheckboxID);
projektCheckbox = itemView.findViewById(R.id.projektCheckboxID);
Log.i(TAG, "onCreate finished");
}
}
static class FooterViewHolder extends RecyclerView.ViewHolder {
FooterViewHolder(View itemView) {
super(itemView);
}
}
public DemoHeaderFooterAdapter(RecyclerView.Adapter adapter, OnListItemClickMessageListener clickListener, Context mContext) {
Log.i(TAG, "DemoHeaderFooterAdapter");
setAdapter(adapter);
mOnItemClickListener = clickListener;
this.mContext = mContext;
}
#Override
public int getHeaderItemCount() {
return 1;
}
#Override
public int getFooterItemCount() {
return 1;
}
#NonNull
#Override
public HeaderViewHolder onCreateHeaderItemViewHolder(#NonNull ViewGroup parent, int viewType) {
Log.i(TAG, "HeaderViewHolder");
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.header_item, parent, false);
HeaderViewHolder vh = new HeaderViewHolder(v);
if (mOnItemClickListener != null) {
vh.itemView.setOnClickListener(this);
}
return vh;
}
#NonNull
#Override
public FooterViewHolder onCreateFooterItemViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.footer_item, parent, false);
FooterViewHolder vh = new FooterViewHolder(v);
if (mOnItemClickListener != null) {
vh.itemView.setOnClickListener(this);
}
return vh;
}
#Override
public void onClick(#NonNull View v) {
RecyclerView rv = RecyclerViewAdapterUtils.getParentRecyclerView(v);
RecyclerView.ViewHolder vh = rv.findContainingViewHolder(v);
int rootPosition = vh.getAdapterPosition();
if (rootPosition == RecyclerView.NO_POSITION) {
return;
}
// need to determine adapter local position like this:
RecyclerView.Adapter rootAdapter = rv.getAdapter();
int localPosition = WrapperAdapterUtils.unwrapPosition(rootAdapter, this, rootPosition);
// get segment
long segmentedPosition = getSegmentedPosition(localPosition);
int segment = extractSegmentPart(segmentedPosition);
int offset = extractSegmentOffsetPart(segmentedPosition);
String message;
if (segment == SEGMENT_TYPE_HEADER) {
message = "CLICKED: Header item " + offset;
} else if (segment == SEGMENT_TYPE_FOOTER) {
message = "CLICKED: Footer item " + offset;
} else {
throw new IllegalStateException("Something wrong.");
}
mOnItemClickListener.onItemClicked(message);
}
// --------------------------------------------
// [ OPTIONAL ]
// Set full-span for Grid layout and Staggered Grid layout
#Override
public void onAttachedToRecyclerView(#NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
setupFullSpanForGridLayoutManager(recyclerView);
}
#Override
public void onBindHeaderItemViewHolder(#NonNull HeaderViewHolder holder, int localPosition) {
applyFullSpanForStaggeredGridLayoutManager(holder);
//Maybe here is the mistake?
//Reload State of SharedPreferences
//This following 3 lines causes error :| how to manage this?
holder.todoCheckbox.setChecked(false);
holder.doneCheckbox.setChecked(false);
holder.projektCheckbox.setChecked(false);
holder.todoCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
todoBool = false;
doneBool = false;
projectBool = false;
mOnItemClickListener.onItemClicked(onItemClickedDefault);
}else{
todoBool = true;
doneBool = false;
projectBool = false;
mOnItemClickListener.onItemClicked(onItemClickedTodo);
}
}
});
holder.doneCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
todoBool = false;
doneBool = true;
projectBool = false;
mOnItemClickListener.onItemClicked(onItemClickedDone);
}else{
todoBool = false;
doneBool = false;
projectBool = false;
mOnItemClickListener.onItemClicked(onItemClickedDefault);
}
}
});
holder.projektCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
todoBool = true;
doneBool = false;
projectBool = true;
mOnItemClickListener.onItemClicked(onItemClickedProject);
}else{
todoBool = true;
doneBool = false;
projectBool = false;
mOnItemClickListener.onItemClicked(onItemClickedTodo);
}
}
});
}
#Override
public void onBindFooterItemViewHolder(#NonNull FooterViewHolder holder, int localPosition) {
applyFullSpanForStaggeredGridLayoutManager(holder);
}
// Filling span for GridLayoutManager
private void setupFullSpanForGridLayoutManager(RecyclerView recyclerView) {
RecyclerView.LayoutManager lm = recyclerView.getLayoutManager();
if (!(lm instanceof GridLayoutManager)) {
return;
}
final GridLayoutManager glm = (GridLayoutManager) lm;
final GridLayoutManager.SpanSizeLookup origSizeLookup = glm.getSpanSizeLookup();
final int spanCount = glm.getSpanCount();
glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
final long segmentedPosition = getSegmentedPosition(position);
final int segment = extractSegmentPart(segmentedPosition);
final int offset = extractSegmentOffsetPart(segmentedPosition);
if (segment == SEGMENT_TYPE_NORMAL) {
return origSizeLookup.getSpanSize(offset);
} else {
return spanCount; // header or footer
}
}
});
}
private void applyFullSpanForStaggeredGridLayoutManager(RecyclerView.ViewHolder holder) {
ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
// Filling span for StaggeredGridLayoutManager
if (lp instanceof StaggeredGridLayoutManager.LayoutParams) {
((StaggeredGridLayoutManager.LayoutParams) lp).setFullSpan(true);
}
}
// --------------------------------------------
}
-----------Edit 3----------------
public void notifyTaskEntrysChanged(String message){
switch (message) {
//Here set Booleans
}
filteredTaskEntries.clear();
//Now fill the filteredTaskEntries with new TaskEntries depending on the bools
Log.d(TAG, "notifyDataSetChanged next Step");
notifyDataSetChanged(); //Error 1. Line in Logcat
}
------------Edit2-----------------
In the MainActifity i handle the clicks like this:
#Override
public void onItemClicked(String message) {
switch (message) {
case onItemClickedTodo:
Log.d(TAG, "onItemClickedTriggerd: TodoChecked true");
TodoChecked = true;
DoneChecked = false;
ProjectChecked = false;
break;
case onItemClickedDone:
TodoChecked = false;
DoneChecked = true;
ProjectChecked = false;
break;
case onItemClickedProject:
ProjectChecked = true;
TodoChecked = true;
DoneChecked = false;
break;
default:
ProjectChecked = false;
TodoChecked = false;
DoneChecked = false;
break;
}
saveStateOfButtons();
Log.d(TAG, "mFilteringAdapter.notifyTaskEntrysChanged(message)");
mFilteringAdapter.notifyTaskEntrysChanged(message); //Error 2. Line in Logcat
}
The 3. Line Error is this code:
mOnItemClickListener.onItemClicked(onItemClickedDefault);
------------Edit1-----------------
Here is the Log.
[...]
D/DemoHeaderFooterAdapter: ----------------------------------------------------
03-22 19:50:49.267 13331-13331/com.example.android.todoDB D/DemoHeaderFooterAdapter: TodoSetOnCheckedChangeListener triggerd
03-22 19:50:49.267 13331-13331/com.example.android.todoDB D/MainActivity: onItemClickedTriggerd: TodoChecked true
03-22 19:50:49.267 13331-13331/com.example.android.todoDB D/MainActivity: saveStateButtons
03-22 19:50:49.275 13331-13331/com.example.android.todoDB D/MainActivity: mFilteringAdapter.notifyTaskEntrysChanged(message)
03-22 19:50:49.275 13331-13331/com.example.android.todoDB D/SimpleDemoItemAdapter: notifyTaskEntrysChanged finished
03-22 19:50:49.275 13331-13331/com.example.android.todoDB D/SimpleDemoItemAdapter: notifyDataSetChanged next Step
03-22 19:50:49.275 13331-13331/com.example.android.todoDB D/AndroidRuntime: Shutting down VM
03-22 19:50:49.277 13331-13331/com.example.android.todoDB E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.todoDB, PID: 13331
java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling androidx.recyclerview.widget.RecyclerView{e9fff59 VFED..... .F....ID 0,0-480,680 #7f090090 app:id/recycler_view}, adapter:com.example.android.todolist.adapters.DemoHeaderFooterAdapter#1c3071e, layout:androidx.recyclerview.widget.LinearLayoutManager#b695bff, context:com.example.android.todolist.MainActivity#755b94c
at androidx.recyclerview.widget.RecyclerView.assertNotInLayoutOrScroll(RecyclerView.java:2880)
at [...]
at androidx.recyclerview.widget.RecyclerView$AdapterDataObservable.notifyChanged(RecyclerView.java:11997)
at androidx.recyclerview.widget.RecyclerView$Adapter.notifyDataSetChanged(RecyclerView.java:7070)
at com.example.android.todolist.adapters.SimpleDemoItemAdapter.notifyTaskEntrysChanged(SimpleDemoItemAdapter.java:287)

Insert data from Google Sheets into Listview

I'm developing an Android app using Google Sheets as a database.
I have information about books in a Google Sheet (title, author, cover, date, etc). I want to retrieve this information and show it in a "Listview" in the "Spreadsheets" Activity. I created a "BookItem" object and an "BookAdapter" adapter. In the "Spreadsheets.java" I have the read method, called "getDataFromApi()". I know that this method works, but I don't know how to adapt it to my "BookAdapter" and show the information on the ListView.
This is mi code:
public class BookItem {
static String title_item;
static Drawable cover_item; //probar con String
public BookItem(String title, Drawable cover){
super();
this.title_item = title;
this.cover_item = cover;
}
public String getTitle() {
return title_item;
}
public void setTitle(String title){
this.title_item = title;
}
public static Drawable getCover() {
return cover_item;
}
public void setCover(Drawable cover) {
this.cover_item = cover;}
This is my BookAdapter:
public class BookAdapter extends BaseAdapter {
private ArrayList<BookItem> items;
List<BookItem> items;
private Context context;
public BookAdapter (Context context, List<BookItem> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public BookItem getItem(int position) {
return this.items.get(position);
}
#Override
public long getItemId(int i) {
return 0;
}
private static class ViewHolder {
public final ImageView cover_item;
public final TextView title_item;
public ViewHolder (ImageView cover_item, TextView title_item){
this.cover_item = cover_item;
this.title_item = title_item;
}
}
#Override
public View getView (int position, View view, ViewGroup viewGroup) {
ImageView cover_item;
TextView title_item;
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.fila_lista_miestanteria, viewGroup, false); //se mete aqui en getView por ser baseAdapter
title_item = (TextView) view.findViewById(R.id.book_title_item);
cover_item = (ImageView) view.findViewById(R.id.book_cover_item);
view.setTag(R.id.book_title_item, title_item);
view.setTag(R.id.book_cover_item, cover_item);
}
else {
cover_item = (ImageView) view.getTag(R.id.book_cover_item);
title_item = (TextView)view.getTag(R.id.book_title_item);
}
BookItem bookItem = getItem(position);
cover_item.setImageDrawable(bookItem.getCover());
title_item.setText(bookItem.getTitle());
return view;
}
}
public class Spreadsheets extends Activity {
static String book_title, book_author, book_date, book_category, book_description, book_rating, book_cover;
static String read_only = "no";
static String book_favorite = "no";
static GoogleAccountCredential mCredential;
private ListView bookList;
private TextView mOutputText;
ProgressDialog mProgress;
Context context;
List<String> rst;
List<BookItem> resultados;
BookAdapter adapter;
private static final String[] SCOPES = {SheetsScopes.SPREADSHEETS};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spread);
// mOutputText = (TextView) findViewById(R.id.outputText);
bookList = (ListView) findViewById(R.id.bookList);
// mOutputText.setText("");
mProgress = new ProgressDialog(this);
mProgress.setMessage("Calling Google Sheets...");
// Initialize credentials and service object.
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
System.out.print("read only es igual a "+ read_only);
new MakeRequestTask(mCredential).execute();
}
public void rellenar(){
System.out.println("VOY A HACER NEW BOOK ADAPTER ");
adapter = new BookAdapter(context, resultados);
bookList.setAdapter(adapter);
System.out.println("SETADAPTER");
}
private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
private Exception mLastError = null;
MakeRequestTask(GoogleAccountCredential credential) {
}
#Override
protected List<String> doInBackground(Void... params) {
try {
if(read_only.equals("no")) {
setDataToApi();
return null;
}
else {
return getDataFromApi();
}
} catch (Exception e) {
mLastError = e;
cancel(true);
return null;
}
}
private List<String> getDataFromApi() throws IOException {
String range = "Sheet1!A1:H";
List<String> results = new ArrayList<String>();
ValueRange response = CreateSpreadsheets.mService.spreadsheets().values()
.get(CreateSpreadsheets.spreadsheet_id, range)
.execute();
List<List<Object>> values = response.getValues();
if (values != null) {
for (List row : values) {
results.add(row.get(0) + ", " + row.get(7));
}
}
//funcion();
return results;
}
private void setDataToApi() throws IOException {
String range = "Sheet1!A2:H";
List<List<Object>> values = new ArrayList<>();
List<Object> data1 = new ArrayList<>();
data1.add(book_title);
data1.add(book_author);
data1.add(book_date);
data1.add(book_category);
data1.add(book_description);
data1.add(book_rating);
data1.add(book_cover);
data1.add("a");
values.add(data1);
ValueRange valueRange = new ValueRange();
valueRange.setMajorDimension("ROWS");
valueRange.setRange(range);
valueRange.setValues(values);
ValueRange body = new ValueRange().setValues(values);
AppendValuesResponse response =
CreateSpreadsheets.mService.spreadsheets().values().append(CreateSpreadsheets.spreadsheet_id, range, body)
.setValueInputOption("RAW")
.execute();
}
#Override
protected void onPreExecute() {
//mOutputText.setText("");
mProgress.show();
}
#Override
protected void onPostExecute(List<String> output) {
mProgress.hide();
if (output == null || output.size() == 0) {
// mOutputText.setText("No results returned.");
} else {
if(read_only.equals("no")) {
Intent intent = new Intent(Spreadsheets.this, MainActivity.class);
startActivity(intent);
// mOutputText.setText("Se ha añadido un libro a su lista");
}
else {
System.out.println("VOY A RELLENAR LA LISTA");
rellenar();
}
}
}
#Override
protected void onCancelled() {
}
}
}
The "spread.xml" is a list, and the "fila_list_miestanteria.xml" is a TextView&ImageView to show the book info.
Thank you so much!

How to set image from drawable into imageview in Android

I want show image into RecyclerView and i should use this images from drawable folder. I write below codes, but show me this error :
java.lang.IllegalArgumentException: Unknown type class [I. You must provide a Model of a type for which there is a registered ModelLoader, if you are using a custom model, you must first call Glide#register with a ModelLoaderFactory for your custom model class
at com.bumptech.glide.RequestManager.loadGeneric(RequestManager.java:629)
at com.bumptech.glide.RequestManager.load(RequestManager.java:598)
at com.tellfa.colony.Adapters.ColoniesAdapter.onBindViewHolder(ColoniesAdapter.java:66)
at com.tellfa.colony.Adapters.ColoniesAdapter.onBindViewHolder(ColoniesAdapter.java:29)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5768)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5801)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5037)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4913)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2029)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1414)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1377)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:578)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3260)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3069)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3518)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1705)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1559)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1468)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1705)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1559)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1468)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2101)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1858)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1077)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5845)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at jav
Model codes:
public class MainDataModel implements Serializable {
private static final long serialVersionUID = 1L;
private String category;
private String categoryID;
private String categoryDescription;
private int[] categoryImages;
private TimeInterpolator interpolator;
public MainDataModel(String categoryID, String category, String categoryDescription, int[] categoryImages,
TimeInterpolator interpolator) {
this.categoryID = categoryID;
this.category = category;
this.categoryDescription = categoryDescription;
this.categoryImages = categoryImages;
this.interpolator = interpolator;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getCategoryID() {
return categoryID;
}
public void setCategoryID(String caategoryID) {
this.categoryID = caategoryID;
}
public String getCategoryDescription() {
return categoryDescription;
}
public void setCategoryDescription(String categoryDescription) {
this.categoryDescription = categoryDescription;
}
public TimeInterpolator getInterpolator() {
return interpolator;
}
public void setInterpolator(TimeInterpolator interpolator) {
this.interpolator = interpolator;
}
public int[] getCategoryImages() {
return categoryImages;
}
public void setCategoryImages(int[] categoryImages) {
this.categoryImages = categoryImages;
}
}
AsyncTask codes and set image :
public class ColoniesDataInfo {
private static Context mContext;
private String ServerAddress = ServerIP_colonies.getColoniesIP();
public void getColoniesDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress);
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
#Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
//String url = (String) params[0];
Request request = new Request.Builder()
.url(ServerAddress)
//.cacheControl(CacheControl.FORCE_NETWORK)
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("categories");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
String colID = postObject.getString("id");
String colTitle = postObject.getString("title");
String colDescription = postObject.getString("description");
final int[] colImages = {
R.drawable.colonies_image_food,
R.drawable.colonies_image_medical,
R.drawable.colonies_image_tecgnolegy,
R.drawable.colonies_image_entertenement,
R.drawable.colonies_image_car,
R.drawable.colonies_image_model,
R.drawable.colonies_image_sport,
};
Log.d("Data", "Colonies ID: " + colID);
Log.d("Data", "Colonies title: " + colTitle);
Log.d("Data", "Colonies Desc: " + colDescription);
Log.d("Data", "---------------------------------");
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(colID, colTitle, colDescription, colImages,
Utils.createInterpolator(Utils.BOUNCE_INTERPOLATOR)));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
} else {
Toast.makeText(mContext, "Empty", Toast.LENGTH_SHORT).show();
}
}
}
}
Adapter codes and set image into adapter :
public class ColoniesAdapter extends RecyclerView.Adapter<ColoniesAdapter.ViewHolder> {
private List<MainDataModel> mDateSet;
private Context mContext;
private SparseBooleanArray expandState = new SparseBooleanArray();
public ColoniesAdapter(Context context, List<MainDataModel> dataSet) {
this.mContext = context;
this.mDateSet = dataSet;
for (int i = 0; i < mDateSet.size(); i++) {
expandState.append(i, false);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.colonies_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.colonies_title.setText(mDateSet.get(position).getCategory());
holder.colonies_title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getPosition();
MainDataModel model = mDateSet.get(pos);
v.getContext().startActivity(new Intent(v.getContext(), Category_page.class)
.putExtra("categoryTitle", model.getCategory())
.putExtra("categoryID", model.getCategoryID()));
}
});
Glide.with(mContext)
.load(mDateSet.get(position).getCategoryImages())
.placeholder(R.drawable.post_image)
.crossFade()
.override(700, 400)
.into(holder.colonies_image);
holder.colonies_description.setText(mDateSet.get(position).getCategoryDescription());
holder.expandableLayout.setInterpolator(mDateSet.get(position).getInterpolator());
holder.expandableLayout.setExpanded(expandState.get(position));
holder.expandableLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
createRotateAnimator(holder.buttonLayout, 0f, 180f).start();
expandState.put(position, true);
}
#Override
public void onPreClose() {
createRotateAnimator(holder.buttonLayout, 180f, 0f).start();
expandState.put(position, false);
}
});
holder.buttonLayout.setRotation(expandState.get(position) ? 180f : 0f);
holder.buttonLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
onClickButton(holder.expandableLayout);
}
});
}
private void onClickButton(final ExpandableLayout expandableLayout) {
expandableLayout.toggle();
}
#Override
public int getItemCount() {
return mDateSet.size();
}
public void remove(int position) {
mDateSet.remove(position);
notifyItemRemoved(position);
}
public void clear() {
mDateSet.clear();
notifyDataSetChanged();
}
public void add(List<MainDataModel> models) {
mDateSet.addAll(models);
notifyDataSetChanged();
}
public void update(List<MainDataModel> models) {
mDateSet.clear();
mDateSet.addAll(models);
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView colonies_title, colonies_description;
private ImageView colonies_image;
private ExpandableLinearLayout expandableLayout;
private RelativeLayout buttonLayout;
public ViewHolder(View itemView) {
super(itemView);
colonies_title = (TextView) itemView.findViewById(R.id.colonies_colony_title_text);
colonies_image = (ImageView) itemView.findViewById(R.id.colonies_cover_image);
colonies_description = (TextView) itemView.findViewById(R.id.colonies_expandable_description_text);
buttonLayout = (RelativeLayout) itemView.findViewById(R.id.colonies_expandable_button);
expandableLayout = (ExpandableLinearLayout) itemView.findViewById(R.id.colonies_expandable_layout);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* v.getContext().startActivity(new Intent(v.getContext(), PostShow_page.class)
.putExtra("title", model.getTitle())
.putExtra("image", model.getThumbnail()));*/
}
});
}
}
public ObjectAnimator createRotateAnimator(final View target, final float from, final float to) {
ObjectAnimator animator = ObjectAnimator.ofFloat(target, "rotation", from, to);
animator.setDuration(300);
animator.setInterpolator(Utils.createInterpolator(Utils.LINEAR_INTERPOLATOR));
return animator;
}
}
How can i fix it?
First of all why are you loading all the array of images into a single imageView? Your method getCategoryImages() gives you an integer array of images. retrieve one by one corresponding to the position.
If the problem still persists you can refer to the below link with the same issue
https://github.com/bumptech/glide/issues/588
Glide.with(mContext)
.load(mDateSet.get(position).getCategoryImages()[position])
.placeholder(R.drawable.post_image)
.crossFade()
.override(700, 400)
.into(holder.colonies_image);
You are trying to load a list of ints and that is why Glide isn't working.
As you gave one ImageView as destination, only one image can be loaded there.
What you need to do is extract the image you wish to load and then pass it to Glide.

Android YouTubeSupportFragment player returning null

I have been working on a personal Android project related to YouTube based off a demo, however I have ran into an issue that I can't seem to figure out (or understand).
The original code uses a basic PlayerView whereas this uses a YouTubePlayerSupportFragment.
The app plays videos just fine as long as player.cueVideo("VIDEOID") is inside onInitializationSuccess. But will crash with a NullPointerException on player variable if placed inside the method playVideoAtSelection.
** The original code had the following line inside onInitializationSuccess, however for me it's telling me that player cannot be resolved. **
I've never seen this used like this before so it has been throwing me off.
this.player = player;
MainActivity.java code:
public class MainActivity extends FragmentActivity implements
AdapterView.OnItemClickListener,
AdapterView.OnItemSelectedListener {
private final String LOG_TAG = MainActivity.class.getSimpleName();
AutoCompleteTextView atvSearch;
public String thumbnailURL;
public String mediaTitle;
public String videoID;
private TextView autoItem;
private ImageView autoImage;
private ArrayList<ArrayList<String>> resultList;
private static final String KEY_CURRENTLY_SELECTED_ID = "currentlySelectedId";
private YouTubePlayer mPlayer;
private YouTubePlayer player = null;
private ArrayAdapter<ListEntry> videoAdapter;
private Spinner videoChooser;
private MyPlayerStateChangeListener playerStateChangeListener;
private int currentlySelectedPosition;
private String currentlySelectedId;
private static final ListEntry[] ENTRIES = {
new ListEntry("Androidify App", "irH3OSOskcE", false),
new ListEntry("Chrome Speed Tests", "nCgQDjiotG0", false),
new ListEntry("Playlist: Google I/O 2012", "PL56D792A831D0C362", true)};
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.v(LOG_TAG, "IN onCreate!");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_playlist, new PlaylistFragment())
.commit();
}
//YouTubePlayerFragment playerFragment = YouTubePlayerFragment.newInstance("irH3OSOskcE");
//getSupportFragmentManager().beginTransaction().replace(R.id.youtube_fragment, playerFragment).commit();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
YouTubePlayerSupportFragment youTubePlayerFragment = new YouTubePlayerSupportFragment();
fragmentTransaction.add(R.id.youtube_fragment, youTubePlayerFragment);
fragmentTransaction.commit();
youTubePlayerFragment.initialize(DeveloperKey.DEVELOPER_KEY, new OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
mPlayer = player;
mPlayer.setPlayerStateChangeListener(playerStateChangeListener);
mPlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
if (!wasRestored) {
playVideoAtSelection();
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
//error
}
});
AutoCompleteTextView autoCompView = (AutoCompleteTextView) findViewById(R.id.atv_search);
autoCompView.setAdapter(new QueryAutoCompleteAdapter(this, R.layout.list_item));
autoCompView.setOnItemClickListener(this);
playerStateChangeListener = new MyPlayerStateChangeListener();
videoChooser = (Spinner) findViewById(R.id.video_chooser);
videoAdapter = new ArrayAdapter<ListEntry>(this, android.R.layout.simple_spinner_item, ENTRIES);
videoAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
videoChooser.setOnItemSelectedListener(this);
videoChooser.setAdapter(videoAdapter);
}
public void playVideoAtSelection() {
if (mPlayer == null) {
Log.v(LOG_TAG, "WE DUN GOOFD PLAYER IS NULL... ");
}
player.cueVideo("nCgQDjiotG0");
Log.v(LOG_TAG, "WE HAVE ENTERED PLAYVIDEOATSELECTION... ");
/*ListEntry selectedEntry = videoAdapter.getItem(currentlySelectedPosition);
if (selectedEntry.id != currentlySelectedId && player != null) {
currentlySelectedId = selectedEntry.id;
if (selectedEntry.isPlaylist) {
player.cuePlaylist(selectedEntry.id);
} else {
player.cueVideo(selectedEntry.id);
}
}*/
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
currentlySelectedPosition = pos;
playVideoAtSelection();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
#Override
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putString(KEY_CURRENTLY_SELECTED_ID, currentlySelectedId);
}
#Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
currentlySelectedId = state.getString(KEY_CURRENTLY_SELECTED_ID);
}
private final class MyPlayerStateChangeListener implements YouTubePlayer.PlayerStateChangeListener {
String playerState = "UNINITIALIZED";
#Override
public void onLoading() {
playerState = "LOADING";
}
#Override
public void onLoaded(String videoId) {
playerState = String.format("LOADED %s", videoId);
}
#Override
public void onAdStarted() {
playerState = "AD_STARTED";
}
#Override
public void onVideoStarted() {
playerState = "VIDEO_STARTED";
}
#Override
public void onVideoEnded() {
playerState = "VIDEO_ENDED";
}
#Override
public void onError(YouTubePlayer.ErrorReason reason) {
playerState = "ERROR (" + reason + ")";
if (reason == YouTubePlayer.ErrorReason.UNEXPECTED_SERVICE_DISCONNECTION) {
// When this error occurs the player is released and can no longer be used.
player = null;
//setControlsEnabled(false);
}
}
}
private static final class ListEntry {
public final String title;
public final String id;
public final boolean isPlaylist;
public ListEntry(String title, String videoId, boolean isPlaylist) {
this.title = title;
this.id = videoId;
this.isPlaylist = isPlaylist;
}
#Override
public String toString() {
return title;
}
}
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String str = (String) adapterView.getItemAtPosition(position);
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
public class QueryAutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
public QueryAutoCompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public String getItem(int index) {
return resultList.get(index).toString();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutInflater inflater = LayoutInflater.from(getContext());
if (row == null) {
row = inflater.inflate(R.layout.list_item_query, parent, false);
}
ArrayList<String> text = resultList.get(position);
String title = text.get(2);
String url = text.get(1);
videoID = text.get(0);
Log.v(LOG_TAG, "YOOOOOO BAIIII: " + title + url);
autoItem = (TextView) row.findViewById(R.id.list_item_title);
autoImage = (ImageView) row.findViewById(R.id.list_item_thumbnail);
autoItem.setText(title);
Bitmap bm = null;
try {
InputStream in = new java.net.URL(url).openStream();
bm = BitmapFactory.decodeStream(in);
} catch (Exception e) {
//Log.e("ERROR", e.getMessage());
e.printStackTrace();
}
autoImage.setImageBitmap(bm);
return row;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
// Constraint is the input given by the user
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
int size = resultList.size();
for (int i=0; i<size; i++) {
//temp = resultList.get(i);
Log.v(LOG_TAG, "YOOOOOO: " + resultList.get(i));
thumbnailURL = resultList.get(i).get(1);
mediaTitle = resultList.get(i).get(2);
}
Log.v(LOG_TAG, "YOOOOOO: " + thumbnailURL + " " + mediaTitle);
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
}
else {
notifyDataSetInvalidated();
}
}};
return filter;
}
}
private ArrayList<ArrayList<String>> autocomplete(String input) {
ArrayList<ArrayList<String>> queries = null;
// If there's no query, there is nothing to look up
if (input.length() == 0) {
return null;
}
String songQuery = input;
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String queryJsonStr = null;
String part = "id,snippet";
String order = "relevance";
String q = songQuery;
String type = "video";
String categoryID = "kind";
String key = DeveloperKey.DEVELOPER_KEY;
try {
// Construct the URL for the query
final String BASE_URL = "https://www.googleapis.com/youtube/v3/search?";
final String PART_PARAM = "part";
final String ORDER_PARAM = "order";
final String QUERY_PARAM = "q";
final String TYPE_PARAM = "type";
final String CATEGORYID_PARAM = "videoCategoryId";
final String KEY_PARAM = "key";
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(PART_PARAM, part)
.appendQueryParameter(ORDER_PARAM, order)
.appendQueryParameter(QUERY_PARAM, q)
.appendQueryParameter(TYPE_PARAM, type)
.appendQueryParameter(CATEGORYID_PARAM, categoryID)
.appendQueryParameter(KEY_PARAM, key)
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "BUILT URI: " + builtUri.toString());
// Create the request to YouTube, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
queryJsonStr = buffer.toString();
Log.v(LOG_TAG, "Query JSON String: " + queryJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "ERROR ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
try {
JSONObject jsonObject = new JSONObject(queryJsonStr);
QueryJSONParser queryJSONParser = new QueryJSONParser();
// Getting the parsed data as a list construct
queries = queryJSONParser.parse(jsonObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return queries;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Relevant XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
android:id="#+id/youtube_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:orientation="horizontal"
android:gravity="top">
<include
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
layout="#layout/player_controls_container" />
</LinearLayout>
Any help would be greatly appreciated!
LOGCAT:
08-08 19:52:23.404 6040-6040/com.android.youtube V/MainActivity﹕ WE DUN GOOFD PLAYER IS NULL...
08-08 19:52:23.404 6040-6040/com.android.youtube D/AndroidRuntime﹕ Shutting down VM
08-08 19:52:23.404 6040-6040/com.android.youtube W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41894da0)
08-08 19:52:23.414 6040-6040/com.android.youtube E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.android.youtube, PID: 6040
java.lang.NullPointerException
at com.android.youtube.MainActivity.playVideoAtSelection(MainActivity.java:132)
at com.android.youtube.MainActivity.onItemSelected(MainActivity.java:148)
You are getting NullPointerException because your player variable is not initialized. You have commented this line:
this.player = player;
And for the question what is this.player = player?
this refers to the current object
For example:
public class myClass{
int x;
public myClass(int x){
this.x = x;
}
}
In the above example, you have used this because, you want to assign value of x to the x(attribute of myClass).
PS: If you are confused with this you can easily do the following:
Change your variable name to something else, may be mPlayer
and change
this.player = player to mPlayer = player;
Edited:
You have declared the YouTubePlayer outside the class. Move it inside i.e. Before overriding onCreate(..) method.
Updated:
Since the player is not attribute of the class, it won't know what it is. This is similar to not declaring any variable.

onListItemClick throws exception (Android)

I copied some Code and it works, but when I try to make some changes it throws an exception, but I don't know why, because I don't understand all of the code, perhaps someone can help me:
MainActivity.java:
public class MainActivity extends ListActivity {
private File currentDir;
private FileArrayAdapter adapter;
private String SearchString = "test";
List<Option>dir = new ArrayList<Option>();
List<Option>fls = new ArrayList<Option>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
currentDir = new File("/sdcard/Test");
fill(currentDir);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Log.d("TEST", adapter.getItem(position).getPath());//aktuellen Pfad ins Syslog schreiben
Option o = adapter.getItem(position);
onFileClick(o);
}
private void onFileClick(Option o)
{
Log.d("TEST", o.getPath());//aktuellen Pfad ins Syslog schreiben
File file = new File(o.getPath());
Intent opdf = new Intent(Intent.ACTION_VIEW);
opdf.setDataAndType(Uri.fromFile(file), "application/pdf");
opdf.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(opdf);
}
public static String removeExtension(String s) {
String separator = System.getProperty("file.separator");
String filename;
// Remove the path upto the filename.
int lastSeparatorIndex = s.lastIndexOf(separator);
if (lastSeparatorIndex == -1) {
filename = s;
} else {
filename = s.substring(lastSeparatorIndex + 1);
}
// Remove the extension.
int extensionIndex = filename.lastIndexOf(".");
if (extensionIndex == -1)
return filename;
return filename.substring(0, extensionIndex);
}
private void fill(File f)
{
File[]dirs = f.listFiles();
try{
for(File ff: dirs)
{
if(ff.isDirectory()){
File r = new File (ff.getPath());
Log.d("TEST", ff.getPath());//aktuellen Pfad ins Syslog schreiben
fill2(r);
}
else
{
}
}
}catch(Exception e)
{
}
Collections.sort(dir);
Collections.sort(fls);
dir.addAll(fls);
adapter = new FileArrayAdapter(MainActivity.this,R.layout.activity_main,dir);
this.setListAdapter(adapter);
}
private void fill2(File f)
{
File[]dirs = f.listFiles();
try{
for(File ff: dirs)
{
if(ff.isDirectory()){
fill2(ff);
}
else{
String Name = (ff.getName().toLowerCase(Locale.GERMAN));
if (Name.contains(SearchString.toLowerCase(Locale.GERMAN))){
fls.add(new Option(removeExtension(ff.getName()),"",null));
}
}
}
}catch(Exception e)
{
}
}
}
FileArrayAdapter.java:
public class FileArrayAdapter extends ArrayAdapter<Option>{
private Context c;
private int id;
private List<Option>items;
public FileArrayAdapter(Context context, int textViewResourceId,
List<Option> objects) {
super(context, textViewResourceId, objects);
c = context;
id = textViewResourceId;
items = objects;
}
public Option getItem(int i)
{
return items.get(i);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
}
final Option o = items.get(position);
if (o != null) {
TextView t1 = (TextView) v.findViewById(R.id.TextView01);
TextView t2 = (TextView) v.findViewById(R.id.TextView02);
if(t1!=null)
t1.setText(o.getName());
if(t2!=null)
t2.setText(o.getData());
//int drawableID = R.drawable.file_icon;
//t1.setCompoundDrawablesWithIntrinsicBounds(drawableID, 0,
// 0, 0);
t1.setEllipsize(null);
t1.setTextSize(54);
t1.setBackgroundColor(Color.LTGRAY);
t2.setBackgroundColor(Color.LTGRAY);
}
return v;
}
}
Option.java:
public class Option implements Comparable<Option>{
private String name;
private String data;
private String path;
public Option(String n,String d,String p)
{
name = n;
data = d;
path = p;
}
public String getName()
{
return name;
}
public String getData()
{
return data;
}
public String getPath()
{
return path;
}
#Override
public int compareTo(Option o) {
if(this.name != null)
return this.name.toLowerCase().compareTo(o.getName().toLowerCase());
else
throw new IllegalArgumentException();
}
}
Logcat:
E/AndroidRuntime(30173): FATAL EXCEPTION: main
E/AndroidRuntime(30173): java.lang.NullPointerException
E/AndroidRuntime(30173): at java.io.File.fixSlashes(File.java:185)
E/AndroidRuntime(30173): at java.io.File.<init>(File.java:134)
E/AndroidRuntime(30173): at com.example.test.MainActivity.onFileClick(MainActivity.java:47)
E/AndroidRuntime(30173): at com.example.test.MainActivity.onListItemClick(MainActivity.java:41)
E/AndroidRuntime(30173): at android.app.ListActivity$2.onItemClick(ListActivity.java:319)
E/AndroidRuntime(30173): at android.widget.AdapterView.performItemClick(AdapterView.java:297)
E/AndroidRuntime(30173): at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
E/AndroidRuntime(30173): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2754)
E/AndroidRuntime(30173): at android.widget.AbsListView$1.run(AbsListView.java:3428)
E/AndroidRuntime(30173): at android.os.Handler.handleCallback(Handler.java:725)
E/AndroidRuntime(30173): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(30173): at android.os.Looper.loop(Looper.java:152)
E/AndroidRuntime(30173): at android.app.ActivityThread.main(ActivityThread.java:5132)
E/AndroidRuntime(30173): at java.lang.reflect.Method.invokeNative(NativeMethod)
E/AndroidRuntime(30173): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(30173): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(30173): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(30173): at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager( 2112): Force finishing activity com.example.test/.MainActivity
In the fill2 method of MainActivity, you're creating an Option object with a null path :
fls.add(new Option(removeExtension(ff.getName()),"",null));
Then you're calling :
File file = new File(o.getPath());
which is throwing the NullPointerException.
Change the above line to :
fls.add(new Option(removeExtension(ff.getName()),"",ff.getPath()));
The "path" from your object "Option" is'nt correct I think.
this line cause the crash :
File file = new File(o.getPath());
on your method "onFileClick".
Try to print o.getPath() to see what's his value, but I think he may be null.

Categories