i want to show genre in my music app but when app runs and when i switch the tabs my app crashes and app stops working and give below logcat error.i dont know what that error is.please help.
this is the logcat
android.database.sqlite.SQLiteException: no such column: _display_name
(code 1): , while compiling: SELECT name, 0, _display_name FROM
audio_genres
at
android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:179)
at
android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
at
android.content.ContentProviderProxy.query(ContentProviderNative.java:418)
at android.content.ContentResolver.query(ContentResolver.java:754)
at android.content.ContentResolver.query(ContentResolver.java:704)
at android.content.ContentResolver.query(ContentResolver.java:662)
at layout.BlankFragment3.getGenreList(BlankFragment3.java:97)
at layout.BlankFragment3.onCreateView(BlankFragment3.java:77)
at
android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
at
android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at
android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
at
android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
at
android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
at
android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
at
android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1984)
at
android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:626)
at
android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1268)
at
android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:668)
at
android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:630)
at
android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:611)
at
android.support.design.widget.TabLayout$ViewPagerOnTabSelectedListener.onTabSelected(TabLayout.java:2191)
at
android.support.design.widget.TabLayout.dispatchTabSelected(TabLayout.java:1164)
at
android.support.design.widget.TabLayout.selectTab(TabLayout.java:1157)
at
android.support.design.widget.TabLayout.selectTab(TabLayout.java:1127)
at
android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1426)
at
android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:1536)
at android.view.View.onKeyUp(View.java:12222)
at android.view.KeyEvent.dispatch(KeyEvent.java:2712)
at android.view.View.dispatchKeyEvent(View.java:11465)
main activity
public class BlankFragment3 extends Fragment {
ArrayList<genreInfo> genreList = new ArrayList<>();
RecyclerView recyclerView2;
private genreAdapter genreAdapter1;
long id;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public BlankFragment3() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.genrere, container, false);
recyclerView2 = rootView. findViewById(R.id.recyclerView2);
genreAdapter1 = new genreAdapter(genreList, getActivity());
recyclerView2.setAdapter(genreAdapter1);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView2.getContext(),
linearLayoutManager.getOrientation());
recyclerView2.setLayoutManager(linearLayoutManager);
recyclerView2.addItemDecoration(dividerItemDecoration);
getGenreList();
return rootView;
}
public void getGenreList(){
final Uri uri = MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI;
String name=MediaStore.Audio.Genres.NAME;
try {
id = Long.parseLong(MediaStore.Audio.Genres._ID);
}catch (Exception e)
{
e.printStackTrace();
}
String dName=MediaStore.Audio.Media.DISPLAY_NAME;
// final String tracks = MediaStore.Audio.Albums.NUMBER_OF_SONGS;
final String[] columns = { name, String.valueOf(id), dName };
Cursor cursor = getContext().getContentResolver().query(uri, columns, null, null, null);
if(cursor!=null && cursor.moveToFirst()) do {
id = cursor.getLong(cursor.getColumnIndex(String.valueOf(id)));
name = cursor.getString(cursor.getColumnIndex(name));
dName = cursor.getString(cursor.getColumnIndex(dName));
//String artPath = cursor.getString(cursor.getColumnIndex(albumart));
//Bitmap art = BitmapFactory.decodeFile(artPath);
// int nr = Integer.parseInt(cursor.getString(cursor.getColumnIndex(tracks)));
genreInfo g = new genreInfo(id, name,dName);
genreList.add(g);
} while (cursor.moveToNext());
if (cursor != null) {
cursor.close();
}
recyclerView2.setAdapter(genreAdapter1);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
genreAdapter
public class genreAdapter extends RecyclerView.Adapter<genreAdapter.AlbumHolder> {
ArrayList<genreInfo> genreList=new ArrayList<>();
Context context;
public genreAdapter(ArrayList<genreInfo> genreList, Context context) {
this.genreList = genreList;
this.context = context;
}
#Override
public genreAdapter.AlbumHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View myView = LayoutInflater.from(context).inflate(R.layout.genre,parent,false);
return new AlbumHolder(myView);
}
#Override
public void onBindViewHolder(AlbumHolder holder, int position) {
final genreInfo a = genreList.get(position);
holder.album.setText(genreList.get(position).getName());
holder.artist.setText(genreList.get(position).getdName());
// holder.album_art.setImageDrawable(Drawable.createFromPath(String.valueOf(albumList.get(position).getAlbumImg())));
}
#Override
public int getItemCount() {
return genreList.size();
}
public class AlbumHolder extends RecyclerView.ViewHolder {
public TextView album;
public TextView artist;
//public ImageView album_art;
public AlbumHolder(View itemView) {
super(itemView);
// album_art = (ImageView) itemView.findViewById(R.id.albumArt);
artist = (TextView) itemView.findViewById(R.id.artistName);
album = (TextView) itemView.findViewById(R.id.songName);
}
}
}
The problem is with the column named _display_name .Check the spelling of this column. Also check whether this column is created when creating audio_genres table.
Related
I am having trouble with RecyclerView and cuscom Apdapter and I don't know why. My code isn't throwing error when I'm building but a
E/RecyclerView: No adapter attached; skipping layout
is showing at Run Logs.
I already watch a lot youtube tutorials and read other answers here at stockoverflow but still I am not able to fix my problem.
Here are my codes:
AccountFragment.java
public class AccountFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: MY VARIABLES
private RecyclerView listAccounts;
private ArrayList<Account> arrayAccount = new ArrayList<>();
private AdapterAccount adapterAccount;
private RecyclerView.LayoutManager layoutAccount;
private Context context;
private static final String accountURL = "LINK";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public AccountFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static AccountFragment newInstance(String param1, String param2) {
AccountFragment fragment = new AccountFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
public void loadJSON(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, accountURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray accounts = new JSONArray(response);
for (int i = 0; i < accounts.length(); i++) {
JSONObject accountsObject = accounts.getJSONObject(i);
int id = accountsObject.optInt("accntID");
String username = accountsObject.optString("accntName");
String type = accountsObject.optString("accntType");
int station = accountsObject.optInt("statID");
String name = accountsObject.optString("lastName");
String address = accountsObject.optString("homeAddress");
String email = accountsObject.optString("emailAddress");
int contact = accountsObject.optInt("contactNumber");
Account account = new Account();
account.accountEntry(id, username, type, station, name, address, email, contact);
arrayAccount.add(account);
}
adapterAccount = new AdapterAccount(getContext());
listAccounts.setAdapter(adapterAccount);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(getActivity()).add(stringRequest);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_account, container, false);
listAccounts = view.findViewById(R.id.accountRV);
layoutAccount = new LinearLayoutManager(getActivity());
listAccounts.setLayoutManager(layoutAccount);
loadJSON();
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
AdapterAccount.java:
public class AdapterAccount extends RecyclerView.Adapter<AdapterAccount.ViewHolderAdapterAccount> {
private ArrayList<Account> arrayAccount = new ArrayList<>();
private LayoutInflater layoutInflater;
private Context context;
public AdapterAccount(Context context) {
this.context = context;
}
public AdapterAccount(ArrayList<Account> arrayAccount) {
this.arrayAccount = arrayAccount;
}
#Override
public ViewHolderAdapterAccount onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.profile_item, parent, false);
ViewHolderAdapterAccount viewHolder = new ViewHolderAdapterAccount(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolderAdapterAccount holder, int position) {
Account currentAccount = arrayAccount.get(position);
holder.accountID.setText(currentAccount.getId());
holder.accountUsername.setText((currentAccount.getUsername()));
holder.accountType.setText(currentAccount.getType());
holder.accountStation.setText((currentAccount.getStation()));
holder.accountName.setText(currentAccount.getName());
holder.accountAddress.setText(currentAccount.getAddress());
holder.accountEmail.setText((currentAccount.getEmail()));
holder.accountContact.setText(currentAccount.getContact());
}
#Override
public int getItemCount() {
return arrayAccount.size();
}
static class ViewHolderAdapterAccount extends RecyclerView.ViewHolder {
private TextView accountID;
private TextView accountUsername;
private TextView accountType;
private TextView accountStation;
private TextView accountName;
private TextView accountAddress;
private TextView accountEmail;
private TextView accountContact;
public ViewHolderAdapterAccount(View accountView) {
super(accountView);
accountID = (TextView) itemView.findViewById(R.id.idPlaceXML);
accountUsername = (TextView) itemView.findViewById(R.id.usernamePlaceXML);
accountType = (TextView) itemView.findViewById(R.id.typePlaceXML);
accountStation = (TextView) itemView.findViewById(R.id.stationPlaceXML);
accountName = (TextView) itemView.findViewById(R.id.namePlaceXML);
accountAddress = (TextView) itemView.findViewById(R.id.addressPlaceXML);
accountEmail = (TextView) itemView.findViewById(R.id.emailPlaceXML);
accountContact = (TextView) itemView.findViewById(R.id.contactPlaceXML);
}
}
}
Account.java:
public class Account {
private int id;
private String username;
private String type;
private int station;
private String name;
private String address;
private String email;
private int contact;
public void accountEntry(int id,String username,String type,int station,String name,String address,String email,int contact){
this.id = id;
this.username = username;
this.type = type;
this.station = station;
this.name = name;
this.address = address;
this.email = email;
this.contact = contact;
}
public int getId(){
return id;
}
public String getUsername(){
return username;
}
public String getType() {
return type;
}
public int getStation() {
return station;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getEmail() {
return email;
}
public int getContact() {
return contact;
}
}
Add following method in AdapterAccount:
public setAccountList(ArrayList<Account> arrayAccount) {
this.arrayAccount = arrayAccount;
}
Change onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_account, container, false);
listAccounts = view.findViewById(R.id.accountRV);
layoutAccount = new LinearLayoutManager(getActivity());
listAccounts.setLayoutManager(layoutAccount);
adapterAccount = new AdapterAccount(getContext());
listAccounts.setAdapter(adapterAccount);
loadJSON();
return view;
}
Change onResponse
public void onResponse(String response) {
try {
...
for (int i = 0; i < accounts.length(); i++) {
...
arrayAccount.add(account);
}
adapterAccount.setAccountList(arrayAccount);
adapterAccount.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
i m trying to get genre in list from below code.in the same way i got songs and albums bu t not getting genres.when app runs it nothing shows any error but shows blank activity.i have no idea what is wrong in this code.please give me some solution.let me know if you want another details.
genreActivity
public class BlankFragment3 extends Fragment {
ArrayList<genreInfo> genreList = new ArrayList<>();
RecyclerView recyclerView2;
private genreAdapter genreAdapter1;
String id;
Cursor cursor;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public BlankFragment3() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.genrere, container, false);
recyclerView2 = rootView. findViewById(R.id.recyclerView2);
genreAdapter1 = new genreAdapter(genreList, getActivity());
recyclerView2.setAdapter(genreAdapter1);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView2.getContext(),
linearLayoutManager.getOrientation());
recyclerView2.setLayoutManager(linearLayoutManager);
recyclerView2.addItemDecoration(dividerItemDecoration);
getGenreList();
return rootView;
}
public void getGenreList() {
String[] proj1 = new String[]{
MediaStore.Audio.Genres.NAME,
MediaStore.Audio.Genres._ID
};
ContentResolver cr = getContext().getContentResolver();
cursor = cr.query(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, proj1, null, null, null);
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
int index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Genres.NAME);
String genre = cursor.getString(index);
index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Genres._ID);
long genreId = Long.parseLong(cursor.getString(index));
Uri uri = MediaStore.Audio.Genres.Members.getContentUri("external", genreId);
Cursor tempCursor = cr.query(uri, null, null, null, null);
if (tempCursor.moveToFirst()) {
while (tempCursor.moveToNext()) {
index = tempCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
String title = tempCursor.getString(index);
index = tempCursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.ARTIST);
String artist = tempCursor.getString(index);
index = tempCursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM);
String album = tempCursor.getString(index);
genreInfo g = new genreInfo(artist, title, album, genre);
genreList.add(g);
}
tempCursor.close();
}
}
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
genreAdapter
public class genreAdapter extends RecyclerView.Adapter<genreAdapter.GenreHolder> {
ArrayList<genreInfo> genreList=new ArrayList<>();
Context context;
MediaMetadataRetriever metaRetriver;
byte[] art;
public genreAdapter(ArrayList<genreInfo> genreList, Context context) {
this.genreList = genreList;
this.context = context;
}
#Override
public genreAdapter.GenreHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View myView = LayoutInflater.from(context).inflate(R.layout.genre,parent,false);
return new GenreHolder(myView);
}
#Override
public void onBindViewHolder(GenreHolder holder, int position) {
final genreInfo a = genreList.get(position);
holder.album.setText(genreList.get(position).getAlbum());
holder.title.setText(genreList.get(position).getTitle());
holder.artist.setText(genreList.get(position).getArtist());
/*
holder.artist.setText(genreList.get(position).getdName());
holder.album_art.setImageDrawable(Drawable.createFromPath(String.valueOf(albumList.get(position).getAlbumImg())));
*/
/* metaRetriver = new MediaMetadataRetriever();
metaRetriver.setDataSource(String.valueOf(genreList.get(position).getID()));
try {
art = metaRetriver.getEmbeddedPicture();
Bitmap songImage = BitmapFactory.decodeByteArray(art,0,art.length);
holder.album_art.setImageBitmap(songImage);
} catch (Exception e)
{
holder.album_art.setBackgroundColor(Color.GRAY);
}*/
}
#Override
public int getItemCount()
{
return genreList.size();
}
public class GenreHolder extends RecyclerView.ViewHolder {
public TextView album;
public TextView artist;
public TextView title;
// public ImageView album_art;
public GenreHolder(View itemView) {
super(itemView);
// album_art = (ImageView) itemView.findViewById(R.id.albumArt);
artist = (TextView) itemView.findViewById(R.id.artistName);
title = (TextView) itemView.findViewById(R.id.titleName);
album = (TextView) itemView.findViewById(R.id.songName);
}
}
}
you are filling your ArrayList after creating adapter but at that time ArrayList is empty,
call getGenreList(); before creating adapter.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.genrere, container, false);
recyclerView2 = rootView. findViewById(R.id.recyclerView2);
getGenreList();
genreAdapter1 = new genreAdapter(genreList, getActivity());
recyclerView2.setAdapter(genreAdapter1);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView2.getContext(),
linearLayoutManager.getOrientation());
recyclerView2.setLayoutManager(linearLayoutManager);
recyclerView2.addItemDecoration(dividerItemDecoration);
return rootView;
}
I have this ListView adapter:
public class UpicksAdapter extends BaseAdapter
{
Context context;
List<Upick> upick_list;
public UpicksAdapter(List<Upick> listValue, Context context)
{
this.context = context;
this.upick_list = listValue;
}
#Override
public int getCount()
{
return this.upick_list.size();
}
#Override
public Object getItem(int position)
{
return this.upick_list.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewItem viewItem = null;
if(convertView == null)
{
viewItem = new ViewItem();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInfiater.inflate(R.layout.listview_items, null);
viewItem.SubNameTextView = (TextView)convertView.findViewById(R.id.SubjectNameTextView);
viewItem.SubFullFormTextView = (TextView)convertView.findViewById(R.id.SubjectFullFormTextView);
convertView.setTag(viewItem);
}
else
{
viewItem = (ViewItem) convertView.getTag();
}
viewItem.SubNameTextView.setText(upick_list.get(position).Subject_Name);
viewItem.SubFullFormTextView.setText(upick_list.get(position).Subject_Full_Form);
return convertView;
}
}
class ViewItem
{
TextView SubNameTextView;
TextView SubFullFormTextView;
}
The ListView is in a fragment.
I need to get data from the listview selected item. I have this listener:
UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = UpicksListView.getItemAtPosition(position).toString();
Log.d("VALOR","VALOR "+item);
}
});
How can I get the values of the selected item?
EDIT:
Complete Fragment code:
public class MisUpicksFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private SessionManager session;
private ProgressDialog loading;
private EditText txtbusqueda;
private Button botonbuscar,botonrefrescar;
//movies
private static final String TAG = MainActivity.class.getSimpleName();
public List<Upick> upicks;
private RecyclerView recyclerView;
private GridLayoutManager gridLayout;
private UpicksAdapter adapter;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private String user_id;
private Button btnNew;
ListView UpicksListView;
ProgressBar progressBar;
String HttpURL = "http://***/upicks_todos.php";
private OnFragmentInteractionListener mListener;
public MisUpicksFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MensajesFragment.
*/
// TODO: Rename and change types and number of parameters
public static MisUpicksFragment newInstance(String param1, String param2) {
MisUpicksFragment fragment = new MisUpicksFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_misupicks, container, false);
UpicksListView = (ListView) view.findViewById(R.id.UpicksListView);
progressBar = (ProgressBar) view.findViewById(R.id.ProgressBar1);
new ParseJSonDataClass(getActivity()).execute();
UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = UpicksListView.getItemAtPosition(position).toString();
Log.d("VALOR","VALOR "+item);
}
});
return view;
}
private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
public Context context;
String FinalJSonResult;
List<Upick> upickFullFormList;
public ParseJSonDataClass(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpServiceClass httpServiceClass = new HttpServiceClass(HttpURL);
try {
httpServiceClass.ExecutePostRequest();
if (httpServiceClass.getResponseCode() == 200) {
FinalJSonResult = httpServiceClass.getResponse();
if (FinalJSonResult != null) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonResult);
JSONObject jsonObject;
Upick upick;
upickFullFormList = new ArrayList<Upick>();
for (int i = 0; i < jsonArray.length(); i++) {
upick = new Upick();
jsonObject = jsonArray.getJSONObject(i);
upick.Subject_Name = jsonObject.getString("id_servicio");
upick.Subject_Full_Form = jsonObject.getString("cliente_servicio");
upickFullFormList.add(upick);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
UpicksListView.setVisibility(View.VISIBLE);
if (upickFullFormList != null) {
UpicksAdapter adapter = new UpicksAdapter(upickFullFormList, context);
UpicksListView.setAdapter(adapter);
}
}
}
private void logoutUser() {
session.setLogin(false);
// Launching the login activity
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
//finish();
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Change this code to setters.
upick.Subject_Name = jsonObject.getString("id_servicio");
upick.Subject_Full_Form = jsonObject.getString("cliente_servicio");
eg:
upick.setSubjectname(jsonObject.getString("id_servicio"));
Then inside onclick you can take values using getters
String item = upicks.get(position).getSubjectname();
parent.getItemAtPosition(position) will return an Object (the model used in your adapter).To get some field from your Object don't call Object.toString(); it will return the object reference not the value that you're looking for. Use Object.yourField; instead.
The ArrayList.get() method is used to get the element of a specified
position within the list.
String str_ITEM= upicks.get(position).yourGETMETHOD();
in your callback listener you have adapter object just use that like below.
UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = parent.getSelectedItem().toString();
Log.d("VALOR","VALOR "+item);
}
});
The pager returns the 1st object in the array list, and keeps returning the 1st object even if i swing left and right, did a lot of debugging, and for some reason when the pager get's to getItem(int position) it start's going crazy, it FINDS the corresponding object , then looks a the previous object(pos-1) then does some other weird things and returns the 1st obj in arrayList.
This method is called within the ViewHolder of RecyclerViewAdapter
#Override
public void onClick(View v) {
Intent i = ProductPageActivity.newIntent(v.getContext(),mProduct.getId());
v.getContext().startActivity(i);
}
}
public class ProductFragment extends Fragment {
private static final String TAG = "ProductFragment";
private static final String ARGUMENT_PROD_ID = "prod_id";
private TextView mTitle,mDesc,mImgUrl,mPrice;
private List<Product> mProducts;
private Product product;
public static Fragment newInstance(UUID productID) {
Bundle args = new Bundle();
args.putSerializable(ARGUMENT_PROD_ID,productID);
ProductFragment frag = new ProductFragment();
frag.setArguments(args);
return frag;
}
public ProductFragment() {}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getArguments() != null) {
UUID id = (UUID) getArguments().getSerializable(ARGUMENT_PROD_ID);
product = ProductHolder.get(getContext()).getProduct(id);
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.product_fragment,container,false);
setWidgets(v);
setDataOnText();
return v;
}
private void setDataOnText(){
mTitle.setText(product.getTitle());
mDesc.setText(product.getDesc());
mPrice.setText(product.getPrice());
}
private void setWidgets(View v) {
mTitle = (TextView) v.findViewById(R.id.title);
mDesc = (TextView) v.findViewById(R.id.desc);
mPrice = (TextView) v.findViewById(R.id.price);
}
}
public class ProductPageActivity extends AppCompatActivity {
private static final String PRODUCT_ID = "com.example.cmd.testproject.Activitys.ProductPageActivity.product_id";
private UUID productId;
private ViewPager mPager;
private List<Product> mProducts;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_page_activity);
productId = (UUID) getIntent().getSerializableExtra(PRODUCT_ID);
mPager = (ViewPager) findViewById(R.id.viewPager);
mProducts = ProductHolder.get(this).getProducts();
FragmentManager fragmentManager = getSupportFragmentManager();
mPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
Product pr = mProducts.get(position);
return ProductFragment.newInstance(pr.getId());
}
#Override
public int getCount() {
return mProducts.size();
}
});
for (int i = 0; i < mProducts.size(); i++) {
if (mProducts.get(i).getId().equals(productId)) {
mPager.setCurrentItem(i);
break;
}
}
}
public static Intent newIntent(Context packageContext, UUID productID) {
Intent intent = new Intent(packageContext, ProductPageActivity.class);
intent.putExtra(PRODUCT_ID, productID);
return intent;
}
}
public class ProductHolder {
private static final String TAG = "ProductHolder";
private static ProductHolder sProductHolder;
private List<Product> mProducts;
public static ProductHolder get(Context ctx) {
if(sProductHolder == null) {
sProductHolder = new ProductHolder(ctx);
}
return sProductHolder;
}
private ProductHolder(Context ctx) {
mProducts = new ArrayList<>();
for (int i = 0; i < 4; i++) {
Product product = new Product("Product = " + i, "Desc = "
+ i, "ImgUrl = " + i, "Price = " + i + 2.2);
mProducts.add(product);
}
}
public Product getProduct(UUID prodId) {
for (Product pr:mProducts) {
if(pr.getId().equals(prodId));
return pr;
}
return null;
}
public List<Product> getProducts() {
return mProducts;
}
}
This is what I've got so far, but it only puts the value inside the database. I need to be able to see what's already inside it but I don't know how. Another good indicator would be to print a toast message with the number of entries on the database.
PS. bonus points if you can help me with crating a new activity expecting an object and retrieving a value when it is done to use it in the father activity. thank y'all.
public class DBHelper extends SQLiteOpenHelper{
private static final String TABLE = "Students";
private static final String DATABASE = "demo.db";
private static final int VERSION = 1;
private static final String C_ID = "id";
private static final String C_NAME = "name";
private static final String C_MAJOR = "major";
public DBHelper(Context context){
super(context, DATABASE, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String creationQuery = "CREATE TABLE " +
TABLE +
" (" +
C_ID +
" INTEGER PRIMARY KEY, " +
C_NAME +
" TEXT, " +
C_MAJOR +
" TEXT)";
sqLiteDatabase.execSQL(creationQuery);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String[] tables = {TABLE};
// prepared statements - check it out for your DB knowledge! yeah!
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS ?", tables);
onCreate(sqLiteDatabase);
// getWritableDatabase
}
public void saveRecord(String name, String major){
// retrieve a reference to the db that we're working with
SQLiteDatabase db = getWritableDatabase();
/*
String query = "INSERT INTO " + TABLE + "(" + C_NAME +", " + C_MAJOR + ") VALUES(?, ?)";
String[] params = {name, major};
db.execSQL(query, params);
*/
ContentValues cv = new ContentValues();
cv.put(C_NAME, name);
cv.put(C_MAJOR, major);
db.insert(TABLE, null, cv);
}
public int getRecord(String name){
SQLiteDatabase db = getWritableDatabase();
int result = -1;
String selection = "name = ?";
String[] params = {name};
Cursor c = db.query(TABLE, null, selection, params, null, null, null);
if(c.moveToFirst()){
result = c.getInt(0);
}
return result;
}
public int deleteRecord(String name) {
SQLiteDatabase db = getWritableDatabase();
String selection = "name = ?";
String[] params = {name};
return db.delete(TABLE, selection, params);
}
}
First this one on fragment
public class fragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
///
private ListView lista;
private MyAdapter_Amigos adapter_amigos;
private OnFragmentInteractionListener mListener;
public fragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static fragment newInstance(String param1, String param2) {
fragment fragment = new fragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_fragment, container, false);
lista = (ListView) v.findViewById(R.id.list);
return v;
}
//Llena arreglo de amigos
public void Lista(ArrayList<Amigo> amigos){
adapter_amigos = new MyAdapter_Amigos(getActivity(), amigos);
lista.setAdapter(adapter_amigos);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
Then on main:
public class MainActivity extends AppCompatActivity implements fragment.OnFragmentInteractionListener, JSONCallback {
ArrayList<Amigo> amigos;
fragment frag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frag = (fragment) getFragmentManager().findFragmentById(R.id.fragment);
}
#Override
public void callBack(JSONObject jo) {
try {
amigos = new ArrayList<Amigo>();
JSONArray arreglo = jo.getJSONArray("result");
for (int i = 0; i < arreglo.length(); i++){
JSONObject objeto = arreglo .getJSONObject(i);
Amigo amigo = new Amigo(objeto.getString("Nombre"),objeto.getString("Hobby"));
amigos.add(amigo);
}
}catch (Exception e){
}
//Log.d("xx",jo.toString());
frag.Lista(amigos);
}
public void LoadJson(View v){
JSONRequest reques = new JSONRequest(this);
reques.execute("https://raw.githubusercontent.com/my.json");
}
#Override
public void onFragmentInteraction(Uri uri) {
}
Then on Someone:
public class Amigo {
//ALT INSERT Constructor / ALT INSERT Setters and Getters
public String nombre;
public String hobby;
public Amigo(String nombre, String hobby) {
this.hobby = hobby;
this.nombre = nombre;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
Then on my adapter:
public class MyAdapter_Amigos extends BaseAdapter {
private Activity activity;
private ArrayList<Amigo> amigos;
public MyAdapter_Amigos(Activity activity, ArrayList<Amigo> amigos) {
this.activity = activity;
this.amigos = amigos;
}
#Override
public int getCount() {
return amigos.size();
}
#Override
public Object getItem(int position) {
return amigos.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if(view == null){
view = activity.getLayoutInflater().inflate(R.layout.row,null);
}
TextView nombre = (TextView) view.findViewById(R.id.nombre);
TextView hobby = (TextView) view.findViewById(R.id.hobby);
nombre.setText((amigos.get(position).getNombre()));
hobby.setText(amigos.get(position).getHobby());
return view;
}
Then on JSONCallback:
import org.json.JSONObject;
public interface JSONCallback {
void callBack(JSONObject jo);
}
For last JSONRequest:
public class JSONRequest extends AsyncTask<String, Void, JSONObject> {
private JSONCallback activity;
public JSONRequest(JSONCallback activity){
this.activity = activity;
}
#Override
protected JSONObject doInBackground(String... params) {
JSONObject resultado = null;
try {
URL url = new URL(params[0]);
HttpURLConnection conexion = (HttpURLConnection) url.openConnection();
conexion.connect();
InputStream is = conexion.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String linea = "";
while ((linea = bf.readLine()) != null){
sb.append(linea);
}
resultado = new JSONObject(sb.toString());
}catch (Exception e){
}
return resultado;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
activity.callBack(jsonObject);
}
This is Fragment 2:
public class fragment extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private ListView lista;
private TextView texto;
private EditText edit;
private Button boton;
private ArrayList<Amigo> friend;
private MyAdapter_Amigos adapter_amigos;
private OnFragmentInteractionListener mListener;
public fragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment fragment.
*/
// TODO: Rename and change types and number of parameters
public static fragment newInstance(String param1, String param2) {
fragment fragment = new fragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_fragment, container, false);
lista = (ListView) v.findViewById(R.id.lista);
texto = (TextView) v.findViewById(R.id.textView3);
edit = (EditText) v.findViewById(R.id.editText2);
boton = (Button) v.findViewById(R.id.button3);
boton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.BotonComunicacion(edit.getText().toString());
}
}
);
lista.setOnItemClickListener(this);
return v;
}
// TODO: Rename method, update argument and hook method into UI event
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public void LlenarLista(ArrayList<Amigo> amigos){
friend = amigos;
MyAdapter_Amigos adapter_amigos = new MyAdapter_Amigos(amigos ,getActivity());
lista.setAdapter(adapter_amigos);
}
public void cambiarATexto(String string){
texto.setText(string);
}
#Override
public void onClick(View v) {
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), vizualizar_datos.class);
intent.putExtra("nombre", friend.get(position).getNombre());
intent.putExtra("hobby", friend.get(position).getHobby());
intent.putExtra("edad", friend.get(position).getEdad());
intent.putExtra("telefono", friend.get(position).getTelefono());
intent.putExtra("direccion", friend.get(position).getDireccion());
startActivity(intent);
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void BotonComunicacion(String string);
//onFragmentInteraction(Uri uri)
}
This is main 2:
public class MainActivity extends AppCompatActivity implements fragment.OnFragmentInteractionListener, JSONCallBack {
private TextView texto;
private EditText edit;
private ArrayList<Amigo> amigos;
private fragment frag;
private JSONRequest request;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
texto = (TextView) findViewById(R.id.texto1);
edit = (EditText) findViewById(R.id.editText);
amigos = new ArrayList<Amigo>();
frag = (fragment) getFragmentManager().findFragmentById(R.id.fragment);
}
#Override
public void CallBack(JSONObject jo) {
try{
JSONArray arreglo = jo.getJSONArray("result");
for(int i =0 ; i < arreglo.length(); i++){
JSONObject o = arreglo.getJSONObject(i);
Amigo amigo = new Amigo(o.getString("Nombre"),o.getString("Hobby"),o.getString("Edad"),o.getString("Telefono"),o.getString("Direccion"));
amigos.add(amigo);
}
}catch (Exception e){
}
frag.LlenarLista(amigos);
}
public void BotonLoad(View v){
request = new JSONRequest(this);
request.execute("https://raw.githubusercontent.com/example.json");
}
#Override
public void BotonComunicacion(String string) {
texto.setText(string);
}
public void MandarInformacion(View v){
frag.cambiarATexto(edit.getText().toString());
}
And the Viewrs:
public class vizualizar_datos extends AppCompatActivity {
private TextView nombre;
private TextView hobby;
private TextView edad;
private TextView direccion;
private TextView telefono;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vizualizar_datos);
nombre = (TextView) findViewById(R.id.nombre_vis);
hobby = (TextView) findViewById(R.id.hobby_vis);
edad = (TextView) findViewById(R.id.edad_vis);
direccion = (TextView) findViewById(R.id.direccion_vis);
telefono = (TextView) findViewById(R.id.telefono_vis);
Intent intent = getIntent();
nombre.setText(intent.getStringExtra("nombre"));
hobby.setText(intent.getStringExtra("hobby"));
edad.setText(intent.getStringExtra("edad"));
direccion.setText(intent.getStringExtra("telefono"));
telefono.setText(intent.getStringExtra("telefono"));
}