onListItemClick throws exception (Android) - java

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.

Related

(Android) How to browse only folders that contains music

I'm trying to make a Fragment that contains a folder browser which shows only folders where there is at least one song.
I've tried to follow several tutorials and to use a Filefilter, but I still see folders that don't contain anything that's useful (eg. Facebook folder), how can I do it?
In other words, I'm trying to make a folder browser like this; could anyone help me?
Code:
FolderFragment.java
public class FolderFragment extends Fragment {
private File file;
private List<String> myList;
private FolderAdapter mAdapter;
private Context mContext;
private LayoutInflater mInflater;
private ViewGroup mContainer;
private LinearLayoutManager mLayoutManager;
View mRootView;
private RecyclerView mRecyclerView;
String root_files;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mContext = container.getContext();
mInflater = inflater;
mContainer = container;
mRootView = inflater.inflate(R.layout.fragment_folders, mContainer, false);
mRecyclerView = (RecyclerView) mRootView.findViewById(R.id.recycler_view_folders);
mLayoutManager = new LinearLayoutManager(mContext);
mRecyclerView.setLayoutManager(mLayoutManager);
if(getActivity() != null)
new loadFolders().execute("");
return mRootView;
}
private class loadFolders extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
Activity activity = getActivity();
if (activity != null) {
mAdapter = new FolderAdapter(activity, new File("/storage"));
}
return "Executed";
}
#Override
protected void onPostExecute(String result){
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
}
}
FolderAdapter.java
public class FolderAdapter extends RecyclerView.Adapter<FolderAdapter.ItemHolder> implements BubbleTextGetter {
private List<File> mFileSet;
private List<Song> mSongs;
private File mRoot;
private Activity mContext;
private boolean mBusy = false;
public FolderAdapter(Activity context, File root){
mContext = context;
mSongs = new ArrayList<>();
updateDataSet(root);
}
#Override
public FolderAdapter.ItemHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_folder_list, viewGroup, false);
return new ItemHolder(v);
}
#Override
public void onBindViewHolder(final FolderAdapter.ItemHolder itemHolder, int i) {
File localItem = mFileSet.get(i);
Song song = mSongs.get(i);
itemHolder.title.setText(localItem.getName());
if (localItem.isDirectory()) {
itemHolder.albumArt.setImageResource("..".equals(localItem.getName()) ? R.drawable.icon_4 : R.drawable.icon_5);
} else {
itemHolder.albumArt.setImageResource(R.drawable.icon_folder);
}
}
#Override
public int getItemCount(){
Log.d("size fileset: ", ""+mFileSet.size());
return mFileSet.size();
}
#Deprecated
public void updateDataSet(File newRoot){
if(mBusy) return;
if("..".equals(newRoot.getName())){
goUp();
return;
}
mRoot = newRoot;
mFileSet = FolderLoader.getMediaFiles(newRoot, true);
getSongsForFiles(mFileSet);
}
#Deprecated
public boolean goUp(){
if(mRoot == null || mBusy){
return false;
}
File parent = mRoot.getParentFile();
if(parent != null && parent.canRead()){
updateDataSet(parent);
return true;
} else {
return false;
}
}
public boolean goUpAsync(){
if(mRoot == null || mBusy){
return false;
}
File parent = mRoot.getParentFile();
if(parent != null && parent.canRead()){
return updateDataSetAsync(parent);
} else {
return false;
}
}
public boolean updateDataSetAsync(File newRoot){
if(mBusy){
return false;
}
if("..".equals(newRoot.getName())){
goUpAsync();
return false;
}
mRoot = newRoot;
new NavigateTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, mRoot);
return true;
}
#Override
public String getTextToShowInBubble(int pos){
if(mBusy || mFileSet.size() == 0) return "";
try{
File f = mFileSet.get(pos);
if(f.isDirectory()){
return String.valueOf(f.getName().charAt(0));
} else {
return Character.toString(f.getName().charAt(0));
}
} catch(Exception e){
return "";
}
}
private void getSongsForFiles(List<File> files){
mSongs.clear();
for(File file : files){
mSongs.add(SongLoader.getSongFromPath(file.getAbsolutePath(), mContext));
}
}
private class NavigateTask extends AsyncTask<File, Void, List<File>>{
#Override
protected void onPreExecute(){
super.onPreExecute();
mBusy = true;
}
#Override
protected List<File> doInBackground(File... params){
List<File> files = FolderLoader.getMediaFiles(params[0], true);
getSongsForFiles(files);
return files;
}
#Override
protected void onPostExecute(List<File> files){
super.onPostExecute(files);
mFileSet = files;
notifyDataSetChanged();
mBusy = false;
//PreferencesUtility.getInstance(mContext).storeLastFolder(mRoot.getPath());
}
}
public class ItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected TextView title;
protected ImageView albumArt;
public ItemHolder(View view) {
super(view);
this.title = (TextView) view.findViewById(R.id.folder_title);
this.albumArt = (ImageView) view.findViewById(R.id.folder_album_art);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mBusy) {
return;
}
final File f = mFileSet.get(getAdapterPosition());
if (f.isDirectory() && updateDataSetAsync(f)) {
albumArt.setImageResource(R.drawable.ic_menu_send);
} else if (f.isFile()) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Toast.makeText(mContext, "", Toast.LENGTH_LONG).show();
}
}, 100);
}
}
}
}
FolderLoader.java
public class FolderLoader {
private static final String[] SUPPORTED_EXT = new String[] {
"mp3",
"m4a",
"aac",
"flac",
"wav"
};
public static List<File> getMediaFiles(File dir, final boolean acceptDirs) {
ArrayList<File> list = new ArrayList<>();
list.add(new File(dir, "/storage"));
if (dir.isDirectory()) {
List<File> files = Arrays.asList(dir.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
if (file.isFile()) {
String name = file.getName();
return !".nomedia".equals(name) && checkFileExt(name);
} else if (file.isDirectory()) {
return acceptDirs && checkDir(file);
} else
return false;
}
}));
Collections.sort(files, new FilenameComparator());
Collections.sort(files, new DirFirstComparator());
list.addAll(files);
}
return list;
}
public static boolean isMediaFile(File file) {
return file.exists() && file.canRead() && checkFileExt(file.getName());
}
private static boolean checkDir(File dir) {
return dir.exists() && dir.canRead() && !".".equals(dir.getName()) && dir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
String name = pathname.getName();
return !".".equals(name) && !"..".equals(name) && pathname.canRead() && (pathname.isDirectory() || (pathname.isFile() && checkFileExt(name)));
}
}).length != 0;
}
private static boolean checkFileExt(String name) {
if (TextUtils.isEmpty(name)) {
return false;
}
int p = name.lastIndexOf(".") + 1;
if (p < 1) {
return false;
}
String ext = name.substring(p).toLowerCase();
for (String o : SUPPORTED_EXT) {
if (o.equals(ext)) {
return true;
}
}
return false;
}
private static class FilenameComparator implements Comparator<File> {
#Override
public int compare(File f1, File f2) {
return f1.getName().compareTo(f2.getName());
}
}
private static class DirFirstComparator implements Comparator<File> {
#Override
public int compare(File f1, File f2) {
if (f1.isDirectory() == f2.isDirectory())
return 0;
else if (f1.isDirectory() && !f2.isDirectory())
return -1;
else
return 1;
}
}
}
A much simpler approach would be if you use ContentProviders
You can list down all the music files or any file as such(You can even provide sorting or more filters to narrow down your list). It is just like using a database.
I can not post the full code right now. But I can give you the idea of how to work out this problem and this approach would be more readable and concise.
Here what you need to do.
1) Create an instance of Cursor.
2) Iterate Cursor to get your media
files
Creating an instance
Cursor cursor = getContentResolver().query(URI uri ,String[] projection, null,null,null);
Let's focus on the first two parameters
a) URI - It could be either Internal or External Storage.
For External Use - MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
For External Use - MediaStore.Audio.Media.INTERAL_CONTENT_URI;
b) Projection is an array which you use to get metadata of your file such as PATH, ARTIST NAME, NO OF SONGS and many more
String[] proj = new String[]{MediaStore.Audio.Media.DISPLAY_NAME,MediaStore.Audio.Media.DATA};
Now you have created Cursor. So the next part is to iterate through it.
while (cursor.moveToNext())
{
name = cursor.getString(cursor.getColumnIndex(modelConst.get_Proj()[0]));
path = cursor.getString(cursor.getColumnIndex(modelConst.get_Proj()[1]));
}
Following code may help you. Be more specific, show some codes you have used if following doesn't work or it is not what you want.
Intent intent;
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("audio/*");
startActivityForResult(Intent.createChooser(intent, "Title"), 89);
on activty result method use following
if (requestCode == 89 && resultCode == Activity.RESULT_OK){
if ((data != null) && (data.getData() != null)){
Uri audioFileUri = data.getData();
// use uri to get path
String path= audioFileUri.getPath();
}
}
Make sure given external storage read permission in manifest and run time permission check for latest sdk.

how to create new json listview from existing listview in setonItemClickListener

So I manage to show my list of categories on button click which starts new activity and shows my list. The thing is when I implement onItemClick listener and Toast some data that works or start new activity and display some id in TextView-->works
but when i create a new ListView and even do everything same app crashes.. there are several json files and they are structured: url: http/......com/id so this id presents id of next url json file ->subcategory of present category what am I doing wrong?
MainActivity - getting json file
public class MainActivity extends AppCompatActivity {
String json_string;
String urlEnd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.mipmap.full_logo);
TextView t2 = (TextView) findViewById(R.id.forgot_password_link);
t2.setMovementMethod(LinkMovementMethod.getInstance());
getJson("1");
}
public String setUrl(String importantNumber){
String json_url;
json_url = "http://...." + importantNumber;
return json_url;
}
public void getJson(String idkategorije){
new BackgroundTask(idkategorije).execute();
}
class BackgroundTask extends AsyncTask<Void, Void, String> {
private final String idkategorije;
String json_url;
String line;
public BackgroundTask(String idkategorije) {
this.idkategorije = idkategorije;
}
#Override
protected void onPreExecute() {
json_url = setUrl(idkategorije);
}
#Override
protected String doInBackground(Void... voids) {
try{
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null){
stringBuilder.append(line);
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
json_string = result;
}
}
public void parseJSON(View view){
if (json_string == null){
Toast.makeText(getApplicationContext(), "GetJson", Toast.LENGTH_SHORT).show();
}else{
Intent intent = new Intent(this, DisplayListView.class);
intent.putExtra("json_data", json_string);
startActivity(intent);
}
}
public void forgotPassword(View view) {
//specify an intent --> directs to new activity --> ForgotPassword.class
Intent startForgotPassActivity = new Intent(this, ForgotPassword.class);
startActivity(startForgotPassActivity);
}
public void registration(View view) {
Intent registrationActivity = new Intent(this, registration.class);
startActivity(registrationActivity);
}
public void addfile(View view) {
Intent addfileActivity = new Intent(this, Addfile.class);
startActivity(addfileActivity);
}
public void login(View view) {
Intent loginActivity = new Intent(this, login.class);
startActivity(loginActivity);
}
public void Searchme(View view) {
EditText searchInput = (EditText)findViewById(R.id.id_search_input);
String searchString = searchInput.getText().toString(); //URL nastavak
Intent searchActivity = new Intent(this, search.class);
searchActivity.putExtra("url",searchString);
startActivity(searchActivity);
}
}
working DisplayListView.java
public class DisplayListView extends AppCompatActivity {
String json_string;
JSONArray jsonArray;
CategoryAdapter categoryAdapter;
ListView listView;
String prosljedeni;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_list_view);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.mipmap.full_logo);
listView = (ListView) findViewById(R.id.listview);
categoryAdapter = new CategoryAdapter(this, R.layout.row_layout);
listView.setAdapter(categoryAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Categories categories = (Categories) categoryAdapter.getItem(position);
String idkat = categories.getId(); //dohvati id imena reda
Toast.makeText(getApplicationContext(), idkat, Toast.LENGTH_SHORT).show();
//MainActivity mm = new MainActivity();
//mm.new BackgroundTask(idkat).execute();
Intent intent = new Intent(DisplayListView.this, SubCategory.class);
intent.putExtra("idkat",idkat);
startActivity(intent);
}
});
json_string = getIntent().getExtras().getString("json_data");
//inicjalizacija jsonObject
try {
//jsonObject = new JSONObject(json_string); //starts with [ not {
jsonArray = new JSONArray(json_string); //get the array
int count = 0;
String name;
String urlFromJ;
String parentId;
String idKategorije;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
idKategorije = JO.getString("id");
parentId = JO.getString("parent_id");
name = JO.getString("name");
urlFromJ = JO.getString("url");
Categories categories = new Categories(idKategorije, parentId, name, urlFromJ);
categoryAdapter.add(categories);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
My adapter..CategoryAdapter
public class CategoryAdapter extends ArrayAdapter {
List list = new ArrayList();
public CategoryAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Categories object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Nullable
#Override
public Object getItem(int position) {
return list.get(position);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
CategoryHolder categoryHolder;
if (row == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout, parent, false);
categoryHolder = new CategoryHolder();
categoryHolder.tx_name = (TextView) row.findViewById(R.id.tx_name);
row.setTag(categoryHolder);
}else {
categoryHolder = (CategoryHolder) row.getTag();
}
//set resources for Views
Categories categories = (Categories) this.getItem(position);
//set resource for category holder
categoryHolder.tx_name.setText(categories.getName());
//categoryHolder.tx_name.setText(categories.getUrlFromJson());
return row;
}
static class CategoryHolder{
TextView tx_name;
}
}
Categories.java - getters and setters
public class Categories {
private String name;
private String urlFromJson;
private String parentId;
private String id;
public Categories(String id, String parentId, String name, String urlFromJson) {
this.id = id;
this.parentId = parentId;
this.name = name;
this.urlFromJson = urlFromJson;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrlFromJson() {
return urlFromJson;
}
public void setUrlFromJson(String urlFromJson) {
this.urlFromJson = urlFromJson;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
}
log error
FATAL EXCEPTION: main
Process: hr.oglasnik.perhpethua.oo, PID: 24222
java.lang.RuntimeException: Unable to start activity ComponentInfo{hr.oglasnik.perhpethua.oo/hr.oglasnik.perhpethua.oo.SubCategory}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2439)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495)
at android.app.ActivityThread.access$800(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5633)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:896)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:712)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONArray.<init>(JSONArray.java:92)
at org.json.JSONArray.<init>(JSONArray.java:108)
at hr.oglasnik.perhpethua.oo.SubCategory.onCreate(SubCategory.java:69)
at android.app.Activity.performCreate(Activity.java:5312)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495) 
at android.app.ActivityThread.access$800(ActivityThread.java:153) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:157) 
at android.app.ActivityThread.main(ActivityThread.java:5633) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:896) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:712) 
at dalvik.system.NativeStart.main(Native Method) 

Attempt to invoke interface method 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference

I have trouble loading data from remote server to my list view. It is showing the above mentioned error, and the app crashes as soon as I open the list.
I have highlighted the functions where the error occurs in log cat. I also mentioned where is the fuction in my classes.
public class Library extends Fragment {
private MaterialSearchView searchView;
Librarycontact currentItem;
private SimpleAdapterLibrary adpt;
List<Librarycontact> result;
ListView lView ;
;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.lib, container, false);
setHasOptionsMenu(true);
searchView = (MaterialSearchView)v.findViewById(R.id.search_view);
searchView.setVoiceSearch(true); //or false
// searchView.setSuggestions(getResources().getStringArray(R.array.query_suggestions));
// searchView.setCursorDrawable(R.drawable.custom_cursor);
adpt = new SimpleAdapterLibrary(new ArrayList<Librarycontact>(), getActivity());
lView = (ListView) v.findViewById(R.id.list);
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
for (int i = 0; i < lView.getAdapter().getCount(); i++) {
currentItem = result.get(i);
if (query.contentEquals(currentItem.getitmCode())) {
Intent l = new Intent(getActivity(), SingleBook.class);
l.putExtra("id", currentItem.getid());
l.putExtra("itemname", currentItem.getitemname());
l.putExtra("itmCode", currentItem.getitmCode());
l.putExtra("itmRate", currentItem.getitmRate());
startActivity(l);
break;
} else
{
Toast.makeText(getActivity(), "No Match Found", Toast.LENGTH_SHORT).show();
}
}
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
#Override
public void onSearchViewShown() {
}
#Override
public void onSearchViewClosed() {
}
});
lView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
currentItem = result.get(position);
Intent i = new Intent(getActivity() ,SingleBook.class);
i.putExtra("id", currentItem.getid());
i.putExtra("itemname", currentItem.getitemname());
i.putExtra("itmCode", currentItem.getitmCode());
i.putExtra("itmRate", currentItem.getitmRate());
startActivity(i);
}
});
searchView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
currentItem = result.get(position);
Intent i = new Intent(getActivity(), SingleBook.class);
i.putExtra("id", currentItem.getid());
i.putExtra("itemname", currentItem.getitemname());
i.putExtra("itmCode", currentItem.getitmCode());
i.putExtra("itmRate", currentItem.getitmRate());
startActivity(i);
}
});
if (isAvailable()){ lView.setAdapter(adpt);
// Exec async load task
(new AsyncListViewLoader()).execute("http://minor.esy.es/libraryavailabilityofbooks.php");
}
else{
showAlertDialog(getActivity(), "No Internet Connection",
"Please Check Your Internet Connection And Try Again", false);
}
return v;}
public Boolean isAvailable() {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
if(reachable){
System.out.println("Internet access");
return reachable;
}
else{
System.out.println("No Internet access");
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setCancelable(false);
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView.setMenuItem(item);
}
HERE **private class AsyncListViewLoader extends AsyncTask<String, Void, List<Librarycontact>> {**
private final ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPostExecute(List<Librarycontact> result) {
super.onPostExecute(result);
dialog.dismiss();
adpt.getItemList();
**adpt.setItemList(result);** HERE
adpt.notifyDataSetChanged();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Loading information...");
dialog.show();
}
#Override
protected List<Librarycontact> doInBackground(String... params) {
result = new ArrayList<>();
try {
URL u = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestMethod("GET");
conn.connect();
InputStream is = conn.getInputStream();
// Read the stream
byte[] b = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ( is.read(b) != -1)
baos.write(b);
String JSONResp = new String(baos.toByteArray());
JSONArray arr = new JSONArray(JSONResp);
for (int i=0; i < arr.length(); i++) {
result.add(convertContact(arr.getJSONObject(i)));
}
return result;
}
catch(Throwable t) {
t.printStackTrace();
}
return null;
}
private Librarycontact convertContact(JSONObject obj) throws JSONException {
String itemname = obj.getString("availability");
String itmCode = obj.getString("title");
String id = obj.getString("id");
String itmRate = obj.getString("authorname");
return new Librarycontact(itemname, itmCode, id,itmRate);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MaterialSearchView.REQUEST_VOICE && resultCode == getActivity().RESULT_OK) {
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (matches != null && matches.size() > 0) {
String searchWrd = matches.get(0);
if (!TextUtils.isEmpty(searchWrd)) {
searchView.setQuery(searchWrd, false);
}
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
my data model
public class Librarycontact implements Serializable {
private String itemname;
private String id;
private String itmCode;
private String itmRate;
public Librarycontact(String name, String itmCode, String id,String itmRate) {
super();
this.itemname = name;
this.itmCode = itmCode;
this.id = id;
this.itmRate = itmRate;
}
public String getitemname() {
return itemname;
}
public void setName(String itemname) {
this.itemname = itemname;
}
public String getitmCode() {
return itmCode;
}
public void setitmCode(String itmCode) {
this.itmCode = itmCode;
}
public String getid() {
return id;
}
public void setid(String id) {
this.id = id;
}
public String getitmRate() {
return itmRate;
}
public void setitmRate(String itmRate) {
this.itmRate = itmRate;
}
}
and my adapter
public class SimpleAdapterLibrary extends ArrayAdapter<Librarycontact> {
private List<Librarycontact> itemList;
private Context context;
private ArrayList<Librarycontact> contactListOrigin = new ArrayList<Librarycontact>();
public SimpleAdapterLibrary(List<Librarycontact> itemListt, Context ctx) {
super(ctx, android.R.layout.simple_list_item_1, itemListt);
this.itemList = itemListt;
this.context = ctx;
this.contactListOrigin.addAll(itemListt);
}
public int getCount() {
if (itemList != null)
return itemList.size();
return 0;
}
public Librarycontact getItem(int position) {
if (itemList != null)
return itemList.get(position);
return null;
}
public long getItemId(int position) {
if (itemList != null)
return itemList.get(position).hashCode();
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.liblistitem, null);
}
Librarycontact c = itemList.get(position);
//TextView text = (TextView) v.findViewById(R.id.name);
//text.setText(c.getitemname());
TextView text1 = (TextView) v.findViewById(R.id.name);
text1.setText(c.getitmCode());
String g= c.getitmCode();
Character o = g.charAt(0);
String k = o.toString();
TextDrawable drawable = TextDrawable.builder()
.beginConfig()
.textColor(Color.BLACK)
.useFont(Typeface.DEFAULT)
.fontSize(30)
.bold()
.toUpperCase()
.endConfig()
.buildRoundRect(k, Color.RED, 10); // radius in px
ImageView img = (ImageView) v.findViewById(R.id.imageView2);
img.setImageDrawable(drawable);
/* TextView text2 = (TextView) v.findViewById(R.id.email);
text2.setText(c.getid());
TextView text3 = (TextView) v.findViewById(R.id.phone);
text3.setText(c.getitmRate());
*/
return v;
}
public List<Librarycontact> getItemList() {
if (itemList == null)
return Collections.emptyList();
else
return itemList;
}
public void setItemList(List<Librarycontact> itemListt) {
this.itemList = itemListt;
**contactListOrigin.addAll(itemListt);** HERE
}}
my logcat
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: FATAL EXCEPTION: main
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: Process: essentials.gtbit.com.gtbitessentials, PID: 4998
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at java.util.ArrayList.addAll(ArrayList.java:188)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at essentials.gtbit.com.gtbitessentials.SimpleAdapterLibrary.setItemList(SimpleAdapterLibrary.java:110)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at essentials.gtbit.com.gtbitessentials.Library$AsyncListViewLoader.onPostExecute(Library.java:215)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at essentials.gtbit.com.gtbitessentials.Library$AsyncListViewLoader.onPostExecute(Library.java:206)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at android.os.AsyncTask.finish(AsyncTask.java:632)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at android.os.AsyncTask.access$600(AsyncTask.java:177)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:111)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at android.os.Looper.loop(Looper.java:194)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5576)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956)
11-09 02:01:25.892 4998-4998/essentials.gtbit.com.gtbitessentials E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
You have to do this in class SimpleAdapterLibrary:
public void setItemList(List<Librarycontact> itemListt) {
if(itemListt==null) {
return;
}
this.itemList = itemListt;
contactListOrigin.addAll(itemListt);
}
or in class AsyncListViewLoader:
#Override
protected void onPostExecute(List<Librarycontact> result) {
super.onPostExecute(result);
dialog.dismiss();
if(result!=null){
adpt.setItemList(result);
adpt.notifyDataSetChanged();
}
}

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.

duplicate value when showing image in costume gridview

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)

Categories