As noob developer im developing a flashcards app where i am populating cards using recyclerview. The issue is when i add a new card using a FAB, i refresh Main activity. Here i find that when i click on any card it doesnt display any data. Debugging revealed that the position of onClick(int position) in the recyclerview fragment adds on the previous size of the cards and thus im unable to see the data. How to get correct onClick position? Please help..
public class CardFragment extends Fragment {
public static List<String> QArray = new ArrayList<>();
public CardFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final OnSelectFlashListner mCallback = null;
// Inflate the layout for this fragment
final RecyclerView flashRecycler = (RecyclerView) inflater.inflate(R.layout.recy_view , container, false);
try{
SQLiteOpenHelper flashCardsHelper1 = new FlashCardsHelper(getContext());
SQLiteDatabase db = flashCardsHelper1.getReadableDatabase();
Cursor cursor = db.query("Flashdata",new String[]{"question", "answer"},null,null,null,null,null);
Log.d("Flash data", DatabaseUtils.dumpCursorToString(cursor));
if (cursor.moveToFirst()){
do {
QArray.add(cursor.getString(0));
}while (cursor.moveToNext());
}
cursor.close();
db.close();
}catch (Exception e){
e.printStackTrace();
}
flashAdapter flashAdap = new flashAdapter(QArray);
flashRecycler.setAdapter(flashAdap);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
flashRecycler.setLayoutManager(linearLayoutManager);
flashAdap.setListner(new flashAdapter.Listner(){
#Override
public void onClick(int position) {
Intent intent = new Intent(getActivity(),FlashCardOpen.class);
intent.putExtra(FlashCardOpen.EXXTRA_QUESTIONNO,position);
getActivity().startActivity(intent);
}
});
Button button = (Button)flashRecycler.findViewById(R.id.btn_Add);
return flashRecycler;
}
im refreshing the Main activity via FAB:
private void loadFAB() {
FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_box);
dialog.setTitle("Add Flash Card");
final EditText textViewQues = (EditText)dialog.findViewById(R.id.et_dialogQuestion);
final EditText textViewAns = (EditText)dialog.findViewById(R.id.et_dialogAnswer);
Button btn_cancel = (Button)dialog.findViewById(R.id.btn_cancel);
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button btn_add = (Button)dialog.findViewById(R.id.btn_Add);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
writeToDb(textViewQues.getText().toString(),textViewAns.getText().toString());
showNotif();
Intent intent = new Intent(context,MainActivity.class);
context.startActivity(intent);
dialog.dismiss();
}
});
dialog.show();
}
});
}
As it turned out, this was not the problem at all. I was populating an array list which kept on appending the whole list on top of previous one. i simply added the array.clear() at start of view onCreateView() and the problem was resolved.
Debugging rules!
Related
Been trying to add a favorites system to this notes app where I can tap and hold an item in the list view to add it to another activity with a list view. Here is the activity with the first list.
Items are added via the MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.savebutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editTextHeading = (EditText) findViewById(R.id.editTextTextPersonName);
EditText editTextContent = (EditText) findViewById(R.id.contentfield);
String heading = editTextHeading.getText().toString().trim();
String content = editTextContent.getText().toString().trim();
if (!heading.isEmpty()) {
if(!content.isEmpty()) {
try {
FileOutputStream fileOutputStream = openFileOutput(heading + ".txt", Context.MODE_PRIVATE); //heading will be the filename
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else {
editTextContent.setError("Content can't be empty!");
}
}else{
editTextHeading.setError("Heading can't be empty!");
}
editTextContent.setText("");
editTextHeading.setText("");
}
});
Button button2 = (Button) findViewById(R.id.btn_gotosaved);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, saved.class));
}
});
Button button3 = (Button) findViewById(R.id.btn_faves);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, favorites.class));
}
});
}
}
Items added will be viewed here
public class saved extends MainActivity {
public static final String EXTRA_MESSAGE = "com.example.notes.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved);
File files = getFilesDir();
String[] array = files.list();
ArrayList<String> arrayList = new ArrayList<>();
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
for (String filename : array) {
filename = filename.replace(".txt", "");
System.out.println(filename);
adapter.add(filename);
}
final ListView listView = (ListView) findViewById(R.id.lv_saved);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
Intent intent = new Intent(getApplicationContext(), Note.class);
intent.putExtra(EXTRA_MESSAGE, item);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
}
});
}
}
And tapping and holding an item from there should "favorite" it and copy it to this new activity with another listview
public class favorites extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
ListView listView = (ListView) findViewById(R.id.lv_favorites);
}
}
How should I approach this?
With your implementation of creating an individual .txt file in the default directory for each note, this is how you could implement:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
Boolean isItemFavorite = item.contains("_favorite");
if (!isItemFavorite){
File itemFile = new File(item + ".txt");
File favoriteItemFile = new File(item + "_favorite.txt");
itemFile.renameTo(favoriteItemFile);
}
}
});
Then in your "favorites" activity you could access all of your note .txt file the same as you do in your "saved" activity - just filtering out any items that don't contain "_favorite" in your "String[] array = files.list();"
Also, some tips: follow naming convention with your activities. "saved" should at least start with an uppercase letter and really should be named something like "SavedNotesListActivity". Also, you should use a room database to keep track of your notes. You should have a favorites table in your room database to keep track of all of your favorites.
As I am very new to java pls help me on this. I have a custom list view in my main activity and a Custom adapter with it. In my every list item there is a delete button that should delete that item when it clicked. I can not remove data from my arraylist when i am inside my custom adapter. Pls helm me in coding this delete button.
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText getItem;
Button AddButton;
Button DellButton;
public static ArrayList<String> myData = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list = (ListView)
findViewById(R.id.listView);
getItem = (EditText) findViewById(R.id.newItem);
AddButton = (Button) findViewById(R.id.AddButton);
MyAdapter adapter = new MyAdapter(this, myData);
list.setAdapter(adapter);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String result = getItem.getText().toString();
myData.add(result);
adapter.notifyDataSetChanged();
}
});
}
MyAdapter.java
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, ArrayList<String> records) {
super(context, 0, records);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.listview_custom, parent, false);
}
final TextView lst_txt = (TextView) convertView.findViewById(R.id.list_Txt2);
Button plusbut = (Button) convertView.findViewById(R.id.plusbut);
Button minusbut = (Button) convertView.findViewById(R.id.minusbut);
final TextView sum = (TextView) convertView.findViewById(R.id.sum);
Button cal = (Button) convertView.findViewById(R.id.calButton);
Button delete = (Button) convertView.findViewById(R.id.btnDel);
lst_txt.setText(item);
minusbut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int sumAll = Integer.parseInt(sum.getText().toString());
int sum1 = sumAll - 1;
sum.setText(String.valueOf(sum1));
}
});
plusbut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int sumAll = Integer.parseInt(sum.getText().toString());
int sum1 = sumAll + 1;
sum.setText(String.valueOf(sum1));
}
});
cal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = sum.getText().toString();
Intent intent = new Intent(getContext(), calll.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("sumFL", s);
getContext().startActivity(intent);
}
});
return convertView;
}
}
Please first try to remove object from list by using the position of item with check the validation with list size and then call notifyItemadapter to update the list view.
Use ViewHolder class for all view like textview, button etc. And initialize them inside the condition
if(convert view==null){
Initialize holder object here and
Inflate your layout and
Initialize button like
holder.deletebutton = convert view.findviewbyid from xml
settag(holder)
}
Again get the holdet using the gettag in
else{
//Here
}
Put All click event and text update etc. Outside of above condition
holder.deletbutton.setonclicklistener{
int pos = view.getag
list.remove(pos)
Notifyadapter here
}
holder.deletebutton.settag(position)
I am using the following code:
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
});
The activity contains a recycler view, I want the activity to reload when I click on refresh but the Recyclerview doesn't fill again, it has the same information than before reloading. If I go to another activity and come back to this one, then it does change.
What I am doing wrong?
Here is the complete activity code:
public class SyncActivity extends Activity {
private static String TAG = "SynActivity";
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private TextView textView;
private ImageView backArrow;
private ImageView refresh;
// Sesión actual
private Usuario usuario;
private String sessionid;
List<TrafficSign> tsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync);
tsList = new ArrayList<TrafficSign>();
// Sesión actual
sessionid = getIntent().getExtras().getString("sessionid");
usuario = (Usuario) getIntent().getExtras().get("usuario");
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
textView = (TextView) findViewById(R.id.texto);
backArrow = (ImageView) findViewById(R.id.backarrow);
refresh = (ImageView) findViewById(R.id.refresh);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// specify an adapter with the list to show
ConexionSQLiteHelper conexionSQLiteHelper = new ConexionSQLiteHelper(this, NOMBRE_BD, null, 1);
SQLiteDatabase dbread = conexionSQLiteHelper.getReadableDatabase();
Cursor c = dbread.rawQuery(COMRPUEBA_SYNC, new String[]{usuario.getUsername()});
// Si hay conexión a internet y hay datos en SQLite, sincronizamos.
if (c.getCount() > 0) {
textView.setVisibility(View.INVISIBLE);
if (c.moveToFirst()) {
while (!c.isAfterLast()) {
tsList.add(new TrafficSign(c.getDouble(c.getColumnIndex(CAMPO_LONGITUD)),
c.getDouble(c.getColumnIndex(CAMPO_LATITUD)),
c.getDouble(c.getColumnIndex(CAMPO_ANCHO)),
c.getDouble(c.getColumnIndex(CAMPO_ALTO)),
c.getString(c.getColumnIndex(CAMPO_CLASE)),
c.getString(c.getColumnIndex(CAMPO_USERNAME))));
c.moveToNext();
}
}
c.close();
dbread.close();
mAdapter = new SyncAdapter(tsList);
mRecyclerView.setAdapter(mAdapter);
}else{
textView.setVisibility(View.VISIBLE);
}
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SyncActivity.this, MainActivity.class);
intent.putExtra("sessionid", sessionid);
intent.putExtra("usuario", usuario);
startActivity(intent);
}
});
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
});
}
}
You can Simply use
finish();
startActivity(getIntent());
to refresh an Activity from within itself.
There is something I want to ask, I have recycle view where is pass from adapter to activity, my question is :
I need to get value/data checkbox from adapter viewHolder Recycleview to activity who is use the adapter for show recycleview
CartAdapter.java
private Context mContext;
private ArrayList<CartModel> mCartList;
public boolean isSelectedAll = true;
public CartAdapter(Context context, ArrayList<CartModel> CartList){
mContext = context;
mCartList = CartList;
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.masteritem_cardview_cart, viewGroup, false);
return new CartViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull CartViewHolder cartViewHolder, int i) {
CartModel currentItem = mCartList.get(i);
cartViewHolder.mCartCheckbox.setChecked(true); //i want pass this value
ShoppingCartActivity.java
private RecyclerView mRecyclerView;
private CartAdapter mCartAdapter;
private ArrayList<CartModel> mCartModelList;
private RequestQueue mRequestQueue;
boolean cartfirst;
private Button mButtonCheckout;
public CheckBox mCartCheckAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
cartfirst = false;
mNavigationView = findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.cart_drawer);
mToogle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToogle);
mToogle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRecyclerView = findViewById(R.id.recycler_view_cart);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mCartModelList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJsonCartItem();
mButtonCheckout = findViewById(R.id.checkOut_btn);
mCartCheckAll = findViewById(R.id.cartChecKall_checkBox);
//firsttime checkall
mCartCheckAll.setChecked(true);
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ShoppingCartActivity.this);
builder.setTitle("Confirm Checkout");
builder.setMessage("Do you really want to Checkout?");
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
for (int i = 0; i < mCartModelList.size(); i++){
//to here, for checking value if true they will checkout, else do nothing
//checkOutChartJSON();
}
}
startActivity(new Intent(getApplicationContext(),ShoppingCartActivity.class));
finish(); //finish current activity
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}});
builder.setNegativeButton(android.R.string.no, null);
builder.create().show();
}
});
To check validation if checkbox is true they will do function checkOutChartJSON, else do nothing
If you wanna pass the data or value from an adapter to new activity then you can do it by using Intent and if you wanna pass the value to existing activity then interface is the best way to do it.
For new activity.
// Passing data to TargetActivity.class
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
intent.putExtra("message", str);
startActivity(intent);
// Get the data in TargetActivity.class
Intent intent=getIntent();
String msg = intent.getStringExtra("message");
For existing activity.
First, make an interface. OnPassingData
public interface OnPassingData {
void onPassing(int value1, String value2,...,int valueN);
}
In the adapter.
OnPassingData onPassingData;
if (onPassingData != null) {
onPassingData .onPassing(value1, value2,..,valueN);
}
public void setOnPassingData(OnPassingData onPassingData) {
this.onPassingData= onPassingData;
}
At the adapter calling in activity.
adapter.setOnPassingData((value1, value2,...,valueN) -> {
Log.i(TAG, "value1 : " + value1);
Log.i(TAG, "value2 : " + value2);
});
I've been struggling for few days on this issue. My project is having 4 fragments which share the same floating button. I have managed to reference the fragments in order to allow the floating button to access each, however although I'm shifting between each fragment, it showing the position of the first one only. here's my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setNavigationViewListener();
//set the drawer layout and navigation view
mDrawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
//set item selected persist highlight
menuItem.setChecked(true);
//close drawer
mDrawerLayout.closeDrawers();
//set action as per the item selected
return true;
}
});
//create an adapter that knows where each fragment is
final LocationFragmentAdapter adapter = new LocationFragmentAdapter(this, getSupportFragmentManager());
mViewPager = findViewById(R.id.viewPager);
mViewPager.setAdapter(adapter);
adapter.getItem(position);
//set the function for the floating button to add a new item
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(LOG_TAG, "the current fragment " + adapter.getPageTitle(position));
if(position == 0) {
Intent intent = new Intent(MainActivity.this, EditorActivity.class);
startActivity(intent);
}
else if (position == 1) {
Intent intent = new Intent(MainActivity.this, RecipeEditor.class);
startActivity(intent);
}
}
});
}
this is my fragmentAdapter
public class LocationFragmentAdapter extends FragmentPagerAdapter {
final int count = 4;
private int [] tabTitle = {R.string.inventory_platform, R.string.product_platform, R.string.customer_platform, R.string.order_platform};
private Context mContext;
public LocationFragmentAdapter(Context context, FragmentManager fm){
super(fm);
mContext = context;
}
#Override
public Fragment getItem(int position) {
if(position == 0) {
return new InventoryFragment();
}else if(position == 1) {
return new RecipeFragment();
}else if(position == 2) {
return new CustomerFragment();
}else {
return new OrderFragment();
}
}
thats my InventoryFragment
#Override
public void onActivityCreated(Bundle savedInstanceState){
getActivity().getSupportLoaderManager().initLoader(STOCK_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){
final View rootView = inflater.inflate(R.layout.activity_main, container, false);
//set empty activity
ListView listView = rootView.findViewById(R.id.display_view);
View emptyView = rootView.findViewById(R.id.empty_view);
listView.setEmptyView(emptyView);
//create a new cursor adapter
mCursorAdapter = new PlatformCursorAdapter(getActivity(),null);
listView.setAdapter(mCursorAdapter);
//create onClick listener to inflate the editor view
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//create new intent to opend the editor
Intent intent = new Intent(getActivity(), EditorActivity.class);
//create Uri to pass the contents of the item selected to the edit view
Uri currentItem = ContentUris.withAppendedId(StoreEntry.CONTENT_URI, id);
intent.setData(currentItem);
startActivity(intent);
}
});
getLoaderManager().initLoader(STOCK_LOADER, null, this);
return rootView;
}
and my RecipeFragment
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
getActivity().getSupportLoaderManager().initLoader(RECIPE_lOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){
final View rootView = inflater.inflate(R.layout.activity_main, container, false);
//set empty activity
ListView listView = rootView.findViewById(R.id.display_view);
View emptyView = rootView.findViewById(R.id.empty_view);
listView.setEmptyView(emptyView);
//create a new cursor adapter
mCursorAdapter = new RecipeCursorAdapter(getActivity(),null);
listView.setAdapter(mCursorAdapter);
//create onClick listener to inflate the editor view
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//create new intent to opened the editor
Intent intent = new Intent(getActivity(), EditorActivity.class);
//create Uri to pass the contents of the item selected to the edit view
Uri currentItem = ContentUris.withAppendedId(RecipeEntry.CONTENT_URI, id);
intent.setData(currentItem);
startActivity(intent);
}
});
return rootView;
}
I haven't created the last two fragments yet. Please let me know if you can find the error.
The log message is always showing the Inventory Fragment
You will have to update the position every time a page is selected using a pager listener
mPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
this.position = position
}
});