I had a single recycler view in MainActivity.I'm adding items to that recycler view from sqlite database. The problem is that it is refreshing continuously when we press back button from app and come back to app again.It is adding duplicates of existing items.
Here is my MainActivity.java file
package bk.acs;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import bk.acs.AddingToDatabase.MyDialog;
import bk.acs.RecyclerView.Data;
import bk.acs.RecyclerView.ListItem;
import bk.acs.RecyclerView.MyAdapter;
public class MainActivity extends AppCompatActivity {
private static final int CONTACTS_PERMISSION = 10;
RecyclerView recview;
MyAdapter adapter;
Data d;
Toolbar toolbar;
NavigationDrawer drawer;
String appName;
LinearLayout main;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
appName = getResources().getString(R.string.app_name);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
recview = (RecyclerView) findViewById(R.id.recview);
drawer = (NavigationDrawer) getSupportFragmentManager().findFragmentById(R.id.navDrawer);
drawer.setUp((DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
d = new Data(this);
adapter = new MyAdapter(d.getList(), this);
recview.setLayoutManager(new LinearLayoutManager(recview.getContext()));
recview.setAdapter(adapter);
main = (LinearLayout) findViewById(R.id.MainLayout);
try {
createFolders();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int res_id = item.getItemId();
if (res_id == R.id.refresh) {
MyDialog dialog = new MyDialog();
dialog.show(getFragmentManager(), "myDialog");
}
return true;
}
public void updateRecView(long num, String subname) {
disableRecView();
adapter.listdata.add(new ListItem(subname, num + ""));
adapter.notifyItemInserted(adapter.listdata.size());
}
public void disableRecView() {
main = (LinearLayout) findViewById(R.id.MainLayout);
main.setVisibility(View.GONE);
}
public void createFolders() throws IOException {
File mainFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath(), appName);
File inputs = new File(mainFolder, "Inputs");
File outputs = new File(mainFolder, "Outputs");
if (mainFolder.exists()) {
Toast.makeText(this, "Welcome", Toast.LENGTH_SHORT).show();
File temp = new File(inputs, "temp.txt");
temp.createNewFile();
} else {
Toast.makeText(this, "Creating Folders", Toast.LENGTH_SHORT).show();
mainFolder.mkdir();
inputs.mkdir();
outputs.mkdir();
File temp = new File(inputs, "temp.txt");
temp.createNewFile();
}
}
public void fetchDataForSub(String s) {
Intent intent = new Intent(this, SubActivity1.class);
intent.putExtra("tv", s);
startActivity(intent);
}
}
Here is my Data.java file from where I'm getting items from database
package bk.acs.RecyclerView;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import bk.acs.MainActivity;
import bk.acs.databases.Main;
/**
* Created by bk on 01-03-2017.
*/
public class Data {
public static ArrayList<String> sample = new ArrayList<>();
public static List<ListItem> list = new ArrayList<>();
String[] cols = {"SubjectName"};
SQLiteDatabase db;
Context ctx;
public Data(Context context) {
this.ctx = context;
Main main = new Main(context, "subjects_db", 1, 1);
db = main.getReadableDatabase();
Cursor cursor = db.query("SubjectsTable", cols, null, null, null, null, null);
while (cursor.moveToNext()) {
sample.add(cursor.getString(0));
}
if (sample.size() != 0) {
((MainActivity) context).disableRecView();
}
}
public List getList() {
for (int i = 0; i < sample.size(); i++) {
ListItem listItem = new ListItem(sample.get(i), (i + 1) + ""); //Fixed crash
list.add(listItem);
}
return list;
}
}
This is MyAdapter.java file
package bk.acs.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import bk.acs.MainActivity;
import bk.acs.R;
import bk.acs.SubActivity1;
/**
* Created by bk on 01-03-2017.
*/
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {
public List<ListItem> listdata;
LayoutInflater inflater;
Context c;
public MyAdapter(List<ListItem> list, Context c) {
this.inflater = LayoutInflater.from(c);
listdata = list;
this.c = c;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.subjects_li, parent, false);
return new Holder(view);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
ListItem item = listdata.get(position);
holder.subjectName.setText(item.subName);
holder.serialNo.setText(item.sno);
}
#Override
public int getItemCount() {
return listdata.size();
}
class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView subjectName;
TextView serialNo;
View container;
public Holder(View itemView) {
super(itemView);
subjectName = (TextView) itemView.findViewById(R.id.subjectTitle);
serialNo = (TextView) itemView.findViewById(R.id.sno);
container = itemView.findViewById(R.id.cont_root);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
((MainActivity) c).fetchDataForSub(subjectName.getText().toString());
}
}
}
How can I prevent duplicates from getting added to this recycler view..Thanks in advance
Because public static List<ListItem> list = new ArrayList<>();,
is always added, so you need to clear the list before you add the items.
public List getList() {
list.clear();
for (int i = 0; i < sample.size(); i++) {
ListItem listItem = new ListItem(sample.get(i), (i + 1) + ""); //Fixed crash
list.add(listItem);
}
return list;
}
Related
This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
Closed 2 years ago.
i'm building an application that connects to my Drupal API. Somehow i'm not getting any data display within my application. I don't see any errors in the code and the debugging online gives the follow error: E/RecyclerView: No adapter attached; skipping layout
Here is my MainActivity code:
package com.example.eindopdrachtcmsapi;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.LinkedList;
public class MainActivity extends AppCompatActivity implements ExampleAdapter.onItemClickListener {
public static final String EXTRA_TITLE = "title";
public static final String EXTRA_BODY = "body";
public static final String EXTRA_LINK = "link";
private RecyclerView mRecyclerView;
private ExampleAdapter mExampleAdapter;
private ArrayList<ExampleItem> mExampleList;
private RequestQueue mRequestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
String url = "http://vistudio.be/api/portfolio";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject portfolio = response.getJSONObject(i);
String title = portfolio.getString("title");
String body = portfolio.getString("body");
String link = portfolio.getString("field_website_url");
mExampleList.add(new ExampleItem(title, body, link));
}
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleAdapter.setOnClickListener(MainActivity.this, new ExampleAdapter.onItemClickListener() {
#Override
public void onItemClick(int position) {
ExampleItem clickedItem = mExampleList.get(position);
String title = clickedItem.getTitle();
String Link = clickedItem.getLink();
Intent mSharingIntent = new Intent(Intent.ACTION_SEND);
mSharingIntent.setType("text/plain");
mSharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Vistudio");
mSharingIntent.putExtra(Intent.EXTRA_TEXT, title + " - "+ Link);
startActivity(Intent.createChooser(mSharingIntent, "Share"));
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(this, DetailActivity.class);
ExampleItem clickedItem = mExampleList.get(position);
detailIntent.putExtra(EXTRA_TITLE, clickedItem.getTitle());
detailIntent.putExtra(EXTRA_BODY, clickedItem.getBody());
detailIntent.putExtra(EXTRA_LINK, clickedItem.getLink());
mExampleAdapter.setOnClickListener(MainActivity.this, new ExampleAdapter.onItemClickListener() {
#Override
public void onItemClick(int position) {
ExampleItem clickedItem = mExampleList.get(position);
String title = clickedItem.getTitle();
String Link = clickedItem.getLink();
Intent mSharingIntent = new Intent(Intent.ACTION_SEND);
mSharingIntent.setType("text/plain");
mSharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Vistudio");
mSharingIntent.putExtra(Intent.EXTRA_TEXT, title + " - "+ Link);
startActivity(Intent.createChooser(mSharingIntent, "Share"));
}
});
startActivity(detailIntent);
}
}
My Adapter code:
package com.example.eindopdrachtcmsapi;
import android.content.Context;
import android.graphics.PorterDuffColorFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.portfolioViewHolder>{
private Context mContext;
private ArrayList<ExampleItem> mExampleList;
private onItemClickListener mListener;
private onItemClickListener mListenerShare;
public interface onItemClickListener{
void onItemClick(int position);
}
public void setOnClickListener(onItemClickListener listener, onItemClickListener listenerShare){
mListener = listener;
mListenerShare = listenerShare;
}
public ExampleAdapter(Context context, ArrayList<ExampleItem> ExampleList) {
mContext = context;
mExampleList = ExampleList;
}
#Override
public portfolioViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.exampleitem, parent, false);
return new portfolioViewHolder(v);
}
#Override
public void onBindViewHolder(portfolioViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
String title = currentItem.getTitle();
String body = currentItem.getBody();
String link = currentItem.getLink();
holder.mTextViewTitle.setText(title);
holder.mTextViewBody.setText(body);
holder.mTextViewLink.setText(link);
}
#Override
public int getItemCount() {
return mExampleList.size();
}
public class portfolioViewHolder extends RecyclerView.ViewHolder{
public TextView mTextViewTitle;
public TextView mTextViewBody;
public TextView mTextViewLink;
public Button mButton;
public portfolioViewHolder(View itemView) {
super(itemView);
mTextViewTitle = itemView.findViewById(R.id.text_view_title);
mTextViewBody = itemView.findViewById(R.id.text_view_body);
mTextViewLink = itemView.findViewById(R.id.text_view_link);
mButton = itemView.findViewById(R.id.share);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListenerShare != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListenerShare.onItemClick(position);
}
}
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
});
}
}
}
first remove inside oncreate()
mRecyclerView.setAdapter(mExampleAdapter);
after this code
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
add this:-
mExampleAdapter.notifyDataSetChanged();
I have been trying to create a ListView with the PlaylistsAdapter. But whenever I try to click on imgCoverArt, the app crashes, stating that the songlist has a size of 0. I have tried changing the types of the variables and just changing the codes overall. But I just couldn't fix it and I don't know the issue.
Thanks in advance.
This was the error I got:
2020-08-10 03:52:56.720 3091-3091/sg.edu.tp.musicstream E/AndroidRuntime: FATAL EXCEPTION: main
Process: sg.edu.tp.musicstream, PID: 3091
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at sg.edu.tp.musicstream.PlaylistsAdapter$1.onClick(PlaylistsAdapter.java:88)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I have tried to include the relevant classes and please let me know if you need anything else.
package sg.edu.tp.musicstream;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import sg.edu.tp.musicstream.util.AppUtil;
public class PlaylistsAdapter extends BaseAdapter {
Context mContext;
LayoutInflater inflater;
Song[] songs;
List<Song> songlist;
ArrayList<Song> arrayList;
public PlaylistsAdapter(Context context, List<Song> songlist, Song[] songs)
{
mContext = context;
inflater = LayoutInflater.from(mContext);
this.songs = songs;
this.songlist = songlist;
this.arrayList = new ArrayList<>();
this.arrayList.addAll(songlist);
}
public class ViewHolder
{
ImageButton imgCoverArt;
TextView txtSongTitle;
TextView txtArtist;
ImageButton btnAddToPlaylist;
}
#Override
public int getCount() {
return songlist.size();
}
#Override
public Object getItem(int position) {
return songlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.playlist_listview, null);
holder.imgCoverArt = convertView.findViewById(R.id.imgCoverArt);
holder.txtSongTitle = convertView.findViewById(R.id.txtSongTitle);
holder.txtArtist = convertView.findViewById(R.id.txtArtist);
holder.btnAddToPlaylist = convertView.findViewById(R.id.btnAddToPlaylist);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.imgCoverArt.setImageResource(songlist.get(position).getCoverArt());
holder.imgCoverArt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int index = 0; index < songs.length; index++)
{
if (songlist.get(position).getId().equals(songs[index].getId())) {
Song song = songs[index];
sendDataToActivity(songs, song);
AppUtil.popMessage(mContext, ""+ songlist.size());
}
}
}
});
holder.txtSongTitle.setText(songlist.get(position).getTitle());
holder.txtArtist.setText(songlist.get(position).getArtist());
if (position >= 10) {
holder.btnAddToPlaylist.setContentDescription("S10" + position);
} else {
holder.btnAddToPlaylist.setContentDescription("S100" + position);
}
return convertView;
}
public void sendDataToActivity(Song[] songs, Song song)
{
// 1. Create a new Intent and specify the source and destination screen/activity.
Intent intent = new Intent(mContext, PlaySongActivity.class);
songlist = HomeFragment.arrayList;
songlist = new ArrayList<>();
// 2. Store the song information into the Intent object to be sent over to the destination screen.
intent.putExtra("id", song.getId());
intent.putExtra("title", song.getTitle());
intent.putExtra("artist", song.getArtist());
intent.putExtra("fileLink", song.getFileLink());
intent.putExtra("coverArt", song.getCoverArt());
intent.putExtra("songs", songs);
intent.putExtra("songlist", (Serializable) songlist);
// 3. Launch the destination screen/activity
mContext.startActivity(intent);
}
public void filter(String charText){
charText = charText.toLowerCase(Locale.getDefault());
songlist.clear();
if (charText.length()==0){
songlist.addAll(arrayList);
}
else {
for (Song song : arrayList){
if (song.getTitle().toLowerCase(Locale.getDefault())
.contains(charText) || song.getArtist().toLowerCase(Locale.getDefault())
.contains(charText)){
songlist.add(song);
}
}
}
notifyDataSetChanged();
}
package sg.edu.tp.musicstream;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.SearchView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import sg.edu.tp.musicstream.ui.main.SectionsPagerAdapter;
import sg.edu.tp.musicstream.util.AppUtil;
public class HomeActivity extends AppCompatActivity {
private SectionsPagerAdapter sectionsPagerAdapter;
private SongCollection songCollection = new SongCollection();
static Song[] playlistSongs = new Song[14];
static ArrayList<Song> playlist = new ArrayList<>();
private Fragment homeFragment;
private Fragment playlistsFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
homeFragment = new HomeFragment();
playlistsFragment = new PlaylistsFragment();
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
setUpViewPager(viewPager);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
private void setUpViewPager(ViewPager viewPager) {
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
sectionsPagerAdapter.addFragment(homeFragment, "Recommended Songs");
sectionsPagerAdapter.addFragment(playlistsFragment, "Playlist");
viewPager.setAdapter(sectionsPagerAdapter);
}
public void addToPlaylist (View view) {
String songId = view.getContentDescription().toString();
Song song = songCollection.searchById(SongCollection.recommendedSongs, songId);
playlist.add(song);
AppUtil.popMessage(this, "Added " + song.getTitle() + " to playlist!");
playlistSongs[playlist.size()] = song;
sectionsPagerAdapter.removeFragment(playlistsFragment, "Playlist");
sectionsPagerAdapter.addFragment(new PlaylistsFragment(), "Playlist");
ViewPager viewPager = findViewById(R.id.view_pager);
setUpViewPager(viewPager);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
public void removeAll(View view) {
playlist.clear();
PlaylistsFragment.songAdapter.notifyDataSetChanged();
}
}
package sg.edu.tp.musicstream;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.text.TextUtils;
import android.view.MenuItem;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
public class HomeFragment extends Fragment {
private PlaylistsAdapter playlistsAdapter;
private ListView listView;
static ArrayList<Song> arrayList = new ArrayList<>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container,false);
for (int index =0; index<SongCollection.recommendedSongs.length; index++) {
arrayList.add(SongCollection.recommendedSongs[index]);
}
listView = view.findViewById(R.id.listView);
playlistsAdapter = new PlaylistsAdapter(getActivity(), arrayList, SongCollection.recommendedSongs);
listView.setAdapter(playlistsAdapter);
setHasOptionsMenu(true);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
MenuItem myActionMenuItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView)myActionMenuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (TextUtils.isEmpty(s)){
playlistsAdapter.filter("");
listView.clearTextFilter();
}
else {
playlistsAdapter.filter(s);
}
return true;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id==R.id.settings){
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
return true;
}
if (id==R.id.logOut){
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
package sg.edu.tp.musicstream;
import java.util.List;
import java.util.Random;
public class SongCollection
{
static Song[] recommendedSongs = new Song[14];
private Song[] playlist1 = new Song[5];
private Song[] playlist2 = new Song[5];
public SongCollection()
{
//Recommended Songs
Song photograph = new Song("S1000", "Photograph", "Ed Sheeran","097c7b735ceb410943cbd507a6e1dfda272fd8a8?cid=null",4.32, R.drawable.photograph);
Song theWayYouLookTonight = new Song("S1001", "The Way You Look Tonight", "Michael Buble","a5b8972e764025020625bbf9c1c2bbb06e394a60?cid=null",4.39,R.drawable.michael_buble_collection);
Song billieJean = new Song("S1002", "Billie Jean", "Michael Jackson","f504e6b8e037771318656394f532dede4f9bcaea?cid=2afe87a64b0042dabf51f37318616965",4.39,R.drawable.billie_jean);
Song spark = new Song("S1003", "Spark", "TAEYEON","e857ae54599f2cca1703b598cef871664f36e72e?cid=2afe87a64b0042dabf51f37318616965", 3.63, R.drawable.spark);
Song darkside = new Song("S1004", "Darkside", "Alan Walker","2acc534ac733f8868c98e13e4f71917fae2e3ce3?cid=2afe87a64b0042dabf51f37318616965", 3.53, R.drawable.darkside);
Song diamondHeart = new Song("S1005", "Diamond Heart", "Alan Walker","d75c2b8e870acb087872bd49eeb5d6efb37cfc9d?cid=2afe87a64b0042dabf51f37318616965", 4.01, R.drawable.diamond_heart);
Song ocean= new Song("S1006", "Ocean (feat. Khalid)", "Martin Garrix","5ce5ed5600e96f1604aff6b05c0dc35319023a1c?cid=2afe87a64b0042dabf51f37318616965", 3.61, R.drawable.ocean);
Song numb = new Song("S1007", "Numb", "Linkin Park","e6ccf7717f8a167bfea4afc1bf7da1a0cd707fbb?cid=2afe87a64b0042dabf51f37318616965", 3.09, R.drawable.numb);
Song sadForever = new Song("S1008", "Sad Forever", "Lauv","1250fb3bea03aee6da908ea67420ddd954ad812a?cid=2afe87a64b0042dabf51f37318616965", 3.39, R.drawable.sad_forever);
Song kyokiranbu = new Song("S1009", "Kyokiranbu", "GARNiDELiA","ec373ab20f18e1a4a7b19b3abaac3ce605690abd?cid=2afe87a64b0042dabf51f37318616965", 4.32, R.drawable.kyokiranbu);
Song gokurakuJoudo= new Song("S1010", "Gokuraku Joudo", "GARNiDELiA","8924599ac778ebfbac7ddc2e5cc87961f82f736c?cid=2afe87a64b0042dabf51f37318616965", 3.65, R.drawable.gokuraku_joudo);
Song connect = new Song("S1011", "Connect", "ClariS","6692db454109aa077ed25e65df82a06d34017da6?cid=2afe87a64b0042dabf51f37318616965", 4.5, R.drawable.connect);
Song wannabe = new Song("S1012", "WANNABE", "ITZY", "2bae7f42bbae3cd75228d6400e37515b79467928?cid=2afe87a64b0042dabf51f37318616965", 3.19, R.drawable.wannabe);
Song icy = new Song("S1013", "ICY", "ITZY", "118a0dea24f229f51ffff23a9d334cf5714dbaf6?cid=2afe87a64b0042dabf51f37318616965", 3.19, R.drawable.icy);
recommendedSongs[0] = photograph;
recommendedSongs[1] = theWayYouLookTonight;
recommendedSongs[2] = billieJean;
recommendedSongs[3] = spark;
recommendedSongs[4] = darkside;
recommendedSongs[5] = diamondHeart;
recommendedSongs[6] = ocean;
recommendedSongs[7] = numb;
recommendedSongs[8] = sadForever;
recommendedSongs[9] = kyokiranbu;
recommendedSongs[10] = gokurakuJoudo;
recommendedSongs[11] = connect;
recommendedSongs[12] = wannabe;
recommendedSongs[13] = icy;
}
In your adapter, you have three different ways of storing the songs:
Song[] songs;
List<Song> songlist;
ArrayList<Song> arrayList;
This is a problem. Pick one type, and use it everywhere.
The adapter is building its logic around the getCount() method:
#Override
public int getCount() {
return songlist.size();
}
Which uses songlist. But your onClick() method uses songs:
#Override
public void onClick(View v) {
for (int index = 0; index < songs.length; index++)
// ...
}
If you change this to use songlist instead, probably the issue will go away.
I am creating an offline application for schoolchildren. In this project, a schoolboy clicking a "RecylerView" to upload a book "Pdf" and save it to an external storage. my problem is that it can only view a book using the Internet. If you turn off the Internet, it's simple not to see the pdf file.
please help
implementation 'com.github.kk121:File-Loader:1.1'
implementation 'com.karumi:dexter:5.0.0'
My Main Activity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.RelativeLayout;
import java.util.ArrayList;
import java.util.List;
> public class MainActivity extends AppCompatActivity {
List<Product> productList;
//the recyclerview
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_about_card_show);
RelativeLayout relativeLayout = findViewById(R.id.rl);
relativeLayout.startAnimation(animation);
//getting the recyclerview from xml
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//initializing the productlist
productList = new ArrayList<>();
//adding some items to our list
productList.add(
new Product(
1,
"TEst 11111 \n",
60000,
R.drawable.android,
"link1"
));
productList.add(
new Product(
1,
" More types, Methods, Conditionals \n",
60000,
R.drawable.android,
"link2"
));
productList.add(
new Product(
1,
"Loops, Arrays ",
60000,
R.drawable.android,
"lin3"
));
productList.add(
new Product(
1,
"Strings",
60000,
R.drawable.android,
"https://firebasestorage.googleapis.com/v0/b/firepdf-4c1d6.appspot.com/o/2.intro.pdf?alt=media&token=75731b04-c1e7-42c4-b988-e50a8f7e5f6b "
));
//creating recyclerview adapter
ProductAdapter adapter = new ProductAdapter(this, productList);
//setting adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
Adapter
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
> public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
//this context we will use to inflate the layout
private Context mCtx;
//we are storing all the products in a list
private List<Product> productList;
//getting the context and product list with constructor
public ProductAdapter(Context mCtx, List<Product> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflating and returning our view holder
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.layout_products, null);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, final int position) {
//getting the product of the specified position
final Product product = productList.get(position);
//binding the data with the viewholder views
holder.textViewTitle.setText(product.getTitle());
holder.imageView.setImageDrawable(mCtx.getResources().getDrawable(product.getImage()));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), pdf.class);
i.putExtra("title",productList.get(position).getTitle());
i.putExtra("product",productList.get(position).getTitle());
i.putExtra("link",productList.get(position).getLink());
mCtx.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder {
TextView textViewTitle;
ImageView imageView;
CardView cardView;
public ProductViewHolder(View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.cardview);// card intial
textViewTitle = itemView.findViewById(R.id.textViewTitle);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
My Pdf Viewer
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;
import com.github.barteksc.pdfviewer.PDFView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class pdf extends AppCompatActivity {
String link="",productList="",product="";
PDFView pdfView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
product =getIntent().getStringExtra("title");
productList=getIntent().getStringExtra("productList");
link=getIntent().getStringExtra("link");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle(productList);
pdfView=findViewById(R.id.pdfv);
//pdfView.fromAsset(link).load();
if (isConnected()) {
Toast.makeText(getApplicationContext(), "Internet Connected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(pdf.this);
builder.setTitle("NoInternet Connection Alert")
.setMessage("GO to Setting ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(pdf.this,"Go Back TO HomePage!",Toast.LENGTH_SHORT).show();
}
});
//Creating dialog box
AlertDialog dialog = builder.create();
dialog.show();
}
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
link = getIntent().getStringExtra("link");
}
new pdf.RetrievePDFStream().execute(link);
}
public boolean isConnected() {
boolean connected = false;
try {
ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();
connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();
return connected;
} catch (Exception e) {
Log.e("Connectivity Exception", e.getMessage());
}
return connected;
}
class RetrievePDFStream extends AsyncTask<String, Void, InputStream> {
ProgressDialog progressDialog;
protected void onPreExecute()
{
progressDialog = new ProgressDialog(pdf.this);
progressDialog.setTitle("getting the book content...");
progressDialog.setMessage("Please wait...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
#Override
protected InputStream doInBackground(String... strings) {
InputStream inputStream = null;
try {
URL urlx = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) urlx.openConnection();
if (urlConnection.getResponseCode() == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}
} catch (IOException e) {
return null;
}
return inputStream;
}
#Override
protected void onPostExecute(InputStream inputStream) {
pdfView.fromStream(inputStream).load();
progressDialog.dismiss();
}
}
#Override public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == android.R.id.home)//means home default hai kya yesok
{
onBackPressed();
return true;
}
return false;
}
}
And LAst Product
public class Product {
private int id;
private String title;
private int image;
private String link;
public Product(int id, String title, double price, int image, String link) {
this.id = id;
this.title = title;
this.image = image;
this.link=link;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public int getImage() {
return image;
}
public String getLink() {
return link;
}
After application download the PDF file to local device, need to update link in your list. Create some database with book information.
I make an application, with CRUD function in Android using Room Database.
When i checked the checkbox like this, Error Pictures 1 i want that application show textview & edittext. But, after i press next button, it won't show textview & edittext based on checked in the checkbox Error Pictures 2 or textview & edittext showed up but that's not based by checkbox isChecked
This is the code :
AdapterTargetIbadah.java
package skripsi.com.ggr.managementibadah.adapter;
import android.arch.persistence.room.Room;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import skripsi.com.ggr.managementibadah.R;
import skripsi.com.ggr.managementibadah.data.factory.AppDatabase;
import skripsi.com.ggr.managementibadah.model.Ibadah;
public class AdapterTargetIbadah extends RecyclerView.Adapter<AdapterTargetIbadah.ViewHolder>{
private ArrayList<Ibadah> targetIbadah;
private Context context;
private AppDatabase db;
public AdapterTargetIbadah(ArrayList<Ibadah> targets, Context ctx) {
targetIbadah = targets;
context = ctx;
db = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, "ibadahdb").allowMainThreadQueries().build();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView tv_target;
EditText et_Target;
ViewHolder(View itemView) {
super(itemView);
tv_target = itemView.findViewById(R.id.tv_target);
et_Target = itemView.findViewById(R.id.et_Target);
}
}
#Override
public AdapterTargetIbadah.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_target, parent, false);
AdapterTargetIbadah.ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(#NonNull AdapterTargetIbadah.ViewHolder holder, int position) {
Ibadah iba = targetIbadah.get(position);
if (iba.getTargetIbadah()!=null) {
holder.tv_target.setText(iba.getTargetIbadah());
iba.setEtTarget(holder.et_Target.getText().toString());
} else {
targetIbadah.remove(position);
}
}
#Override
public int getItemCount() {
return targetIbadah.size();
}
}
AdapterCheckboxTarget.java
package skripsi.com.ggr.managementibadah.adapter;
import android.arch.persistence.room.Room;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import skripsi.com.ggr.managementibadah.R;
import skripsi.com.ggr.managementibadah.data.factory.AppDatabase;
import skripsi.com.ggr.managementibadah.model.Ibadah;
public class AdapterCheckboxTarget extends RecyclerView.Adapter<AdapterCheckboxTarget.ViewHolder> {
private ArrayList<Ibadah> targetIbadah;
private Context context;
private AppDatabase db;
public AdapterCheckboxTarget(ArrayList<Ibadah> targets, Context ctx) {
targetIbadah = targets;
context = ctx;
db = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, "ibadahdb").allowMainThreadQueries().build();
}
class ViewHolder extends RecyclerView.ViewHolder {
CheckBox cbTarget;
ViewHolder(View itemView) {
super(itemView);
cbTarget = itemView.findViewById(R.id.cbTarget);
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_targethome, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
final String name = targetIbadah.get(position).getNamaIbadah();
holder.cbTarget.setText(name);
holder.cbTarget.setChecked(targetIbadah.get(position).getStatus());
holder.cbTarget.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (holder.cbTarget.isChecked()) {
targetIbadah.get(position).setStatus(true);
targetIbadah.get(position).setTargetIbadah(targetIbadah.get(position).getNamaIbadah());
Toast.makeText(context, "checklist", Toast.LENGTH_SHORT).show();
} else {
targetIbadah.get(position).setStatus(false);
Toast.makeText(context, "unchecklist", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public int getItemCount() {
return targetIbadah.size();
}
}
TargetHome.java ==> Activity using AdapterTargetIbadah.java
package skripsi.com.ggr.managementibadah;
import android.app.Activity;
import android.arch.persistence.room.Room;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import skripsi.com.ggr.managementibadah.adapter.AdapterCheckboxTarget;
import skripsi.com.ggr.managementibadah.adapter.AdapterTargetIbadah;
import skripsi.com.ggr.managementibadah.data.factory.AppDatabase;
import skripsi.com.ggr.managementibadah.model.Ibadah;
public class TargetHome extends AppCompatActivity {
private AppDatabase db;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<Ibadah> targetIbadah;
RecyclerView rvTarget;
Button btSimpan;
Context ctx;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.target_ibadah);
setTitle("Target Ibadah");
btSimpan = (Button)findViewById(R.id.btSimpanTarget);
targetIbadah = new ArrayList<>();
db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "ibadahdb").allowMainThreadQueries().build();
rvTarget = findViewById(R.id.rvTar);
rvTarget.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rvTarget.setLayoutManager(layoutManager);
targetIbadah.addAll(Arrays.asList(db.ibadahDAO().selectAllStatus()));
adapter = new AdapterTargetIbadah(targetIbadah, this);
rvTarget.setAdapter(adapter);
Ibadah ib = new Ibadah();
if (ib.getTargetIbadah()!=null) {
ib.setTvTarget(ib.getTargetIbadah());
ib.setEtTarget("");
db.ibadahDAO().insertCapai(ib);
}
btSimpan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(MainActivity.getActIntent(TargetHome.this));
}
});
}
public static Intent getActIntent(Activity activity) {
// kode untuk pengambilan Intent
return new Intent(activity, TargetHome.class);
}
}
CheckboxTarget.java ==> Activity using AdapterCheckboxTarget
package skripsi.com.ggr.managementibadah;
import android.app.Activity;
import android.arch.persistence.room.Room;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import skripsi.com.ggr.managementibadah.adapter.AdapterCatatIbadah;
import skripsi.com.ggr.managementibadah.adapter.AdapterCheckboxTarget;
import skripsi.com.ggr.managementibadah.data.factory.AppDatabase;
import skripsi.com.ggr.managementibadah.model.Ibadah;
public class CheckboxTarget extends AppCompatActivity {
private AppDatabase db;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<Ibadah> targetIbadah;
RecyclerView rvCb;
Button btNext;
Context ctx;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.target_home);
setTitle("Target Ibadah");
btNext = (Button) findViewById(R.id.btNextTarget);
targetIbadah = new ArrayList<>();
db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "ibadahdb").allowMainThreadQueries().build();
rvCb = findViewById(R.id.rvTarHome);
rvCb.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rvCb.setLayoutManager(layoutManager);
targetIbadah.addAll(Arrays.asList(db.ibadahDAO().selectAllStatus()));
adapter = new AdapterCheckboxTarget(targetIbadah, this);
rvCb.setAdapter(adapter);
final Ibadah ibadah = (Ibadah) getIntent().getSerializableExtra("data");
if (ibadah != null) {
Ibadah ib = new Ibadah();
ib.setStatus(ib.status);
db.ibadahDAO().insertTarget(ib);
}
}
public static Intent getActIntent(Activity activity) {
// kode untuk pengambilan Intent
return new Intent(activity, CheckboxTarget.class);
}
}
Ibadah.java ==> Model
package skripsi.com.ggr.managementibadah.model;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import java.io.Serializable;
#Entity(tableName = "tibadah")
public class Ibadah implements Serializable {
#PrimaryKey(autoGenerate = true)
public int idIbadah;
#ColumnInfo(name = "nama_ibadah")
public String namaIbadah;
#ColumnInfo(name = "deskripsi_ibadah")
public String deskripsiIbadah;
#ColumnInfo(name = "target_ibadah")
public String targetIbadah;
#ColumnInfo(name = "tv_target")
public String tvTarget;
#ColumnInfo(name = "et_target")
public String etTarget;
#ColumnInfo(name = "et_capaian")
public String etCapaian;
#ColumnInfo(name = "status")
public boolean status;
public String getTvTarget() {
return tvTarget;
}
public void setTvTarget(String tvTarget) {
this.tvTarget = tvTarget;
}
public String getTargetIbadah() {
return targetIbadah;
}
public void setTargetIbadah(String targetIbadah) {
this.targetIbadah = targetIbadah;
}
public String getEtTarget() {
return etTarget;
}
public void setEtTarget(String etTarget) {
this.etTarget = etTarget;
}
public String getEtCapaian() {
return etCapaian;
}
public void setEtCapaian(String etCapaian) {
this.etCapaian = etCapaian;
}
public String getDeskripsiIbadah() {
return deskripsiIbadah;
}
public void setDeskripsiIbadah(String deskripsiIbadah) {
this.deskripsiIbadah = deskripsiIbadah;
}
public int getIdIbadah() {
return idIbadah;
}
public void setIdIbadah(int idIbadah) {
this.idIbadah = idIbadah;
}
public String getNamaIbadah() {
return namaIbadah;
}
public void setNamaIbadah(String namaIbadah) {
this.namaIbadah = namaIbadah;
}
public boolean getStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}
I hope, you can help me. Thank you very much & sorry for my bad english.
First you have to set your TextView and EditText invisible in your XML, by adding android:visibility="invisible" to the XML of your TextView and EditText.
Then you have to use setVisibility(View.VISIBLE) after you have set the checkbox, like this:
yourcheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
//if checkbox is checked (b == true)
yourTextView.setVisibility(View.VISIBLE);
yourEditText.setVisibility(View.VISIBLE);
}
if (!b) {
//if checkbox is not checked (b == false)
yourTextView.setVisibility(View.INVISIBLE);
yourEditText.setVisibility(View.INVISIBLE);
}
}
});
If you first want to click a button and then check weather checkbox is checked, add this to your OnClickListenter:
if (yourcheckbox.isChecked) {
yourTextView.setVisibility(View.VISIBLE);
yourEditText.setVisibility(View.VISIBLE);
}
I am making a video gallery trying to get videos files from a specific directory i am getting an error parameters cannot be resolved to a variable here is my code of the gallery activity.I am a newbie to java and my English is not that good.Thanks in advance for helping.
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class Main extends Activity implements OnItemClickListener {
Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String selection=MediaStore.Video.Media.DATA +" like?";
String[] selectionArgs=new String[]{"/storage/sdcard0/phd"};
cursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
parameters, selection, selectionArgs, MediaStore.Video.Media.DATE_TAKEN + " DESC");
ListView listView = (ListView) this.findViewById(R.id.ListView);
String[] thumbColumns = { MediaStore.Video.Thumbnails.DATA,
MediaStore.Video.Thumbnails.VIDEO_ID };
String[] mediaColumns = { MediaStore.Video.Media._ID,
MediaStore.Video.Media.DATA, MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.MIME_TYPE };
cursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
mediaColumns, null, null, null);
ArrayList<VideoViewInfo> videoRows = new ArrayList<VideoViewInfo>();
if (cursor.moveToFirst()) {
do {
VideoViewInfo newVVI = new VideoViewInfo();
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.Video.Media._ID));
Cursor thumbCursor = managedQuery(
MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
thumbColumns, MediaStore.Video.Thumbnails.VIDEO_ID
+ "=" + id, null, null);
if (thumbCursor.moveToFirst()) {
newVVI.thumbPath = thumbCursor.getString(thumbCursor
.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
Log.v("", newVVI.thumbPath);
}
newVVI.filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
newVVI.title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
Log.v("", newVVI.title);
newVVI.mimeType = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE));
Log.v("", newVVI.mimeType);
videoRows.add(newVVI);
} while (cursor.moveToNext());
}
listView.setAdapter(new VideoGalleryAdapter(this, videoRows));
listView.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
if (cursor.moveToPosition(position)) {
int fileColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
int mimeColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE);
String videoFilePath = cursor.getString(fileColumn);
String mimeType = cursor.getString(mimeColumn);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
File newFile = new File(videoFilePath);
intent.setDataAndType(Uri.fromFile(newFile), mimeType);
startActivity(intent);
}
}
}
class VideoViewInfo {
String filePath;
String mimeType;
String thumbPath;
String title;
}
class VideoGalleryAdapter extends BaseAdapter {
private Context context;
private List<VideoViewInfo> videoItems;
LayoutInflater inflater;
public VideoGalleryAdapter(Context _context,
ArrayList<VideoViewInfo> _items) {
context = _context;
videoItems = _items;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return videoItems.size();
}
public Object getItem(int position) {
return videoItems.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View videoRow = inflater.inflate(R.layout.row, null);
ImageView videoThumb = (ImageView) videoRow
.findViewById(R.id.ImageView);
if (videoItems.get(position).thumbPath != null) {
videoThumb.setImageURI(Uri
.parse(videoItems.get(position).thumbPath));
}
TextView videoTitle = (TextView) videoRow
.findViewById(R.id.TextView);
videoTitle.setText(videoItems.get(position).title);
return videoRow;
}
}