I have deveolped a method to call methods from another calss.I have created an adapter and inside that I have an override getView(). What I need to do is to get values from a listview and display as a report. I have tried this exact code inside another activity in the same project. It works perfectly. But when ever I moved this into another activity it doesn't give any error.But the overrided method is not calling. What should I do to make it run?
public class ViewList extends ActionBarActivity {
ArrayAdapter<Units> unitsAdapterView;
ListView ViewAll;
List<Units> Unit = new ArrayList<Units>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_list);
ViewAll = (ListView) findViewById(R.id.viewList);
populateListView();
viewView();
}
private void viewView(){
Button m=(Button)findViewById(R.id.tryBtn);
m.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// startActivity(new Intent(getApplicationContext(),ViewList.class));
populateListView();
}
});
}
private void populateListView(){
unitsAdapterView =new UnitListAdaptorView();
ViewAll.setAdapter(unitsAdapterView);
// unitsAdapterView.getView();
}
private class UnitListAdaptorView extends ArrayAdapter<Units> {
public UnitListAdaptorView() {
super (ViewList.this, R.layout.list,Unit);
Log.i("","A");
// A();
}
#override
public View getView(int position, View view, ViewGroup parent) {
Log.i("","Resue connceted bulb 5");
if (view == null) {
view = getLayoutInflater().inflate(R.layout.list,parent ,false);
}
Units currentUnit = Unit.get(position);
TextView name = (TextView)view.findViewById(R.id.lblViewName);
name.setText(currentUnit.getName());
TextView bulb=(TextView) view.findViewById(R.id.lblViewBulb);
bulb.setText(currentUnit.getBulbNo());
TextView fan=(TextView) view.findViewById(R.id.lblViewFan);
fan.setText(currentUnit.getFanNo());
return view;
}
}
}
The problem was solved after adding the codes to get all the existing data from database. After adding the below codes to the onCreate method the function is working now!
DatabaseHandler dbHandler = new DatabaseHandler(getApplicationContext());
if (dbHandler.getUnitsCount() != 0)
Unit.addAll(dbHandler.getAllUnit());
Related
I pass data from my RecyclerView Adapter to my MainActiviy. I also use an interface in the Adapter to capture the CardView item position in the MainActivity's onItemClick() and pass that position to a new Activity (CardViewDetails) using an intent. Problem is the CardViewDetails loads the wrong CardView. How do I use the CardView "position" to launch the correct CardView? What am I missing here?
MainActivity
...
public void passDataFromAdapter(Bundle bundle) {
data = bundle.getString("spantimeinhours");
data2 = bundle.getLong("timeinhours");
}
// This method works with an interface in the Adapter to capture the
// CardView item position.
#Override
public void onItemClick(int position, final View view) {
Intent intent = new Intent(this,Details.class);
intent.putExtra("adapterSpanTimeInHours",data);
intent.putExtra("adapterTimeInHours",data2);
startActivity(intent);
}
Details
...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Bundle extras = getIntent().getExtras();
msgFromAdapter = extras.getString("adapterSpanTimeInHours");
msg2FromAdapter = extras.getLong("adapterTimeInHours", 0);
}
Adapter
public class MyRecylerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private void passDataFromAdapter(Bundle bundle) {
if (context == null)
return;
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
activity.passDataFromAdapter(bundle); // this method must be implemented inside `MainActivity`
}
}
}
paste this in your onBindViewHolder
viewHolder.myView.setOnClickListener(new View.OnClickListener() {
// Handles the row being clicked.
#Override
public void onClick(View view) {
int adapterPos = itemHolder.getAdapterPosition(); // get the item position.
if (adapterPos != RecyclerView.NO_POSITION) {
if (recyclerItemClickListener != null) {
recyclerItemClickListener.onItemClick(adapterPos, itemHolder.itemView);
}
}
}
});
I have searched but could not find answer of my question.
This is what I have:
private class BoxView extends View {
private String caption;
private OnClickListener bvClickListener = null
public BoxView(Context context) {
super(context);
this.bvClickListener = new this.OnClickListener(){
public void onClick (View v){
/*v.setCaption("X"); view don't have this method */
}}
}
public void setCaption(String s){
this.caption=s;
invalidate();
}
}
This is what I want to have:
private class BoxView extends View {
private String caption;
private OnClickListener bvClickListener = null
public BoxView(Context context) {
super(context);
this.bvClickListener = new this.OnClickListener(){
public void onClick (BoxView bv){
bv.setCaption("X");
}}
}
public void setCaption(String s){
this.caption=s;
invalidate();
}
}
I may need custom methods for my custom views. And I want to be able to pass my custom view instead of view version of it when onclick is triggered so I can access to it directly.
Updated
And I want to have access to real object not a converted one. So I want to avoid this:
public void onClick (View v){
((BoxView)v).setCaption("X");
}
Call setCaption method as in onClick :
public void onClick (View v){
((BoxView)v).setCaption("X");
}
Try this
class Main extents Activity
{
BoxView boxView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// if view is used using layout then
boxView = (BoxView)findViewByID(id);
//else if directly used
boxView = new BoxView(this);
box.setOnClickListener(new onClickListener()
{
#Override
public void onClick(View view) {
boxView.setCaption("X");
boxView.invalidate();
}
});
}
}
I am using an animation to slide a view to the top of the screen. The code for the animation is contained within a method called LoopAnimation() which is called from main.
public class MainActivity extends AppCompatActivity {
final View view = findViewById(R.id.view);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoopAnimation(view); \\ The animation loop method
}
This LoopAnimation() method uses a nested setOnClickListener to create an animation loop
public void LoopAnimation(View view){
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starts the animation
view.animate().translationY(-100);
view.animate().setDuration(1500);
// reverses the animation
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do some job here
view.animate().translationY(100);
view.animate().setDuration(1500);
LoopAnimation(view); // Method calls itself
// to create loop effect
}
});
}
});
}
The problem is that I am getting a trivial error that I can't understand. Although I have declared view as global and final, I get this error in LoopAnimation()
Variable 'view' is accessed from within inner class, needs to be declared final.
You are using the variable view that is defined within your method's scope. Notice that your method's parameter is also called view so you are not actually using the global variable that you think you are using.
public void LoopAnimation(View view){
Edit: I've looked more into the way that you are trying to do this, and the approach isn't what I would do. Here is something more reasonable:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = findViewById(R.id.view);
view.setOnClickListener(new View.OnClickListener() {
private boolean _forwards = true;
#Override
public void onClick(View v) {
if (_forwards) {
// starts the animation
v.animate().translationY(-100);
v.animate().setDuration(1500);
_forwards = false;
} else {
// reverses the animation
v.animate().translationY(100);
v.animate().setDuration(1500);
_forwards = true;
}
}
}
}
}
I want to create by code an array of objects that are subclasses of Button.
public class MyButton extends Button {
private Context ctx;
private int status;
public MyButton(Context context) {
super(context);
ctx = context;
status = 0;
}
private click() {
status = 1;
// OTHER CODE THAT NEEDS TO STAY HERE
}
}
In the main activity I do this:
public class myActivity extends Activity {
private MyButton[] myButtons = new MyButton[100];
#Override
public onCreate(Bundle si) {
super.onCreate(si);
createButtons();
}
private void createButtons() {
for (int w=0; w<100; w++) {
myButtons[w] = new MyButton(myActivity.this);
myButtons[w].setOnClickListener(new View.onClickListener() {
public void onClick(View v) {
// ... (A)
}
});
}
}
}
Now I want the click() method inside MyButton to be run each time the button is clicked.
Seems obvious but it is not at my eyes.
If I make the click() method public and run it directly from (A), I get an error because myButtons[w].click() is not static and cannot be run from there.
In the meantime, I an not able to understand where to put the code in the MyButton class to intercept a click and run click() from there. Should I override onClick? Or should I override onClickListener? Or what else should I do?
How can I run click() whenever one of myButtons[] object is clicked?
Thanks for the help.
You can cast View v you got in listener to MyButton and call click on it:
private void createButtons() {
View.OnClickListener listener = new View.onClickListener() {
public void onClick(View v) {
((MyButton) v).click();
}
};
for (int w=0; w<100; w++) {
myButtons[w] = new MyButton(myActivity.this);
myButtons[w].setOnClickListener(listener);
}
}
you can add:
View.onClickListener onclick = new View.onClickListener() {
public void onClick(View v) {
((MyButton)v).click();
//since v should be instance of MyButton
}
};
to your Activity
then use:
myButtons[w].setOnClickListener(onclick);
//one instance of onclick is enough, there is no need to create it for every button
in createButtons()
but ... why, oh why array of buttons we have ListView in android ...
I have a SherlockListFragment in which I have a custom list item (checkbox, icon and some text) - works fine. The list is populated from a custom CursorAdapter and it is in here that I trap the Checkbox events (so I can preserve the data through orientation changes as well - also works). I want to be able to raise an event in the ListFragment when the user checks one or more checkboxes to display an actionbar item.
I've implemented an interface in the fragment to accept the event but just cannot work out the syntax for raising the fragment event in the cursoradapter's checkbox onClick listener - the event triggers ok but a can't call the listener, can't suss the object to use.
Fragment:
public class ContactListFragment extends SherlockListFragment implements
LoaderManager.LoaderCallbacks<Cursor>
{
public interface ListItemCheckedListener
{
public void OnListItemChecked(int count);
}
private SimpleCursorAdapter mAdapter;
public ListItemCheckedListener checkListener;
public void setListItemListener(ListItemCheckedListener listener)
{
checkListener = listener;
}
<snip>
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
<snip>
setListItemListener(new ListItemCheckedListener()
{
#Override
public void OnListItemChecked(int count)
{
// Turn on/off Action Bar Item
//if (count > 0)...
}
});
CursorAdapter:
public class ContactCursorAdapter extends SimpleCursorAdapter
{
<snip>
#Override
public void bindView(View view, Context context, Cursor cursor)
{
<snip>
CheckBox cBox = (CheckBox)view.findViewById(R.id.checkBox);
final int pos = cursor.getPosition();
cBox.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
CheckBox cb = (CheckBox)view.findViewById(R.id.checkBox);
if (cb.isChecked())
{
itemChecked.set(pos, true);
countChecked++;
<something>.checkListener(countChecked); // <----- Umm?
}
else if (!cb.isChecked())
{
itemChecked.set(pos, false);
countChecked--;
<something>.checkListener(countChecked); // <----- ditto
}
}
});
cBox.setChecked(itemChecked.get(pos));
}
I've tried all manner of objects for "something" but can't seem to quite get the right one.
Help... please...!
Well, after quite a few dead ends I finally came up with a solution. Don't know if it is a good solution or if it is the "correct" way to do it but it works...
I simply added a public ListItemCheckedListener variable to the CursorAdapter class, assigned my ListFragment ListItemCheckedListener instance to it straight after setting up the adapter and then could call the local instance of the listener within the CursorAdapter and the event would propagate out to the ListFragment.
ListFragment:
public class ContactListFragment extends SherlockListFragment implements
LoaderManager.LoaderCallbacks<Cursor>// , OnQueryTextListener
{
private ContactCursorAdapter _adapter; // <----- HERE
<snip>
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
setListItemListener(new ContactListItemCheckedListener()
{
#Override
public void OnListItemChecked(int count)
{
if (count > 0)
{
if (_mode == null)
{
_loaderManager = getLoaderManager();
ContactsActivity activity = (ContactsActivity)getActivity();
_mode = activity.startActionMode(_actionModeCallback);
}
if (_contactInvite != null)
_contactInvite.setRecipCount(count);
}
else
{
if (_mode != null)
{
_mode.finish();
_mode = null;
}
}
}
});
_fragment = this;
setListProcessedListener(new ContactListProcessedListener()
{
public void OnListProcessed(int contactMethod)
{
for (int i = 0; i < _adapter.itemChecked.size(); i++)
_adapter.itemChecked.set(i, false);
_fragment.setListAdapter(_adapter);
_loaderManager.initLoader(0, null, _fragment);
}
});
setEmptyText(this.getString(R.string.contacts_none));
setHasOptionsMenu(true);
_adapter = new ContactCursorAdapter(getActivity(),
R.layout.contact_list_item,
null,
new String[] { Contacts._ID,
Contacts.DISPLAY_NAME,
Contacts.CONTACT_STATUS },
CONTACT_SUMMARY_FIELDS,
0);
_adapter.checkListener = checkListener;
boolean[] iChecked = null;
if (savedInstanceState != null)
{
if (savedInstanceState.containsKey("itemChecked"))
{
iChecked = savedInstanceState.getBooleanArray("itemChecked");
for (int i = 0; i < iChecked.length; i++)
_adapter.itemChecked.add(i, iChecked[i]);
_adapter.countChecked = savedInstanceState.getInt("countChecked");
checkListener.OnListItemChecked(_adapter.countChecked);
}
}
try
{
setListAdapter(_adapter);
setListShown(false);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
((ContactsActivity)getActivity()).setSearchTextListener(new ContactsActivity.SearchTextListener()
{
#Override
public void OnSearchTextChange(String text)
{
onQueryTextChange(text);
}
});
}
catch (Exception e)
{
Singletons.Logger().error(TAG + ".onActivityCreated() failed",
e.getMessage());
}
}
CursorAdapter:
public class ContactCursorAdapter extends SimpleCursorAdapter
{
<snip>
public ListItemCheckedListener checkListener; // <----- HERE
<snip>
#Override
public void bindView(View view, Context context, Cursor cursor)
{
<snip>
cBox.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
CheckBox cb = (CheckBox)view.findViewById(R.id.checkBox);
if (cb.isChecked())
{
itemChecked.set(pos, true);
countChecked++;
checkListener.OnListItemChecked(countChecked); // <----- HERE
}
else if (!cb.isChecked())
{
itemChecked.set(pos, false);
countChecked--;
checkListener.OnListItemChecked(countChecked); // <----- HERE
}
}
});
cBox.setChecked(itemChecked.get(pos));
}
Quite simple and fairly elegant, if I do say so myself. Well... at least it is in comparison to some of my earlier failed attempts(!). I still get the feeling that it isn't the best way to do it, somehow just feels wrong, but hey... it works.
If anyone has any better ways of doing this, I'd love to hear them. In the meanwhile, I hope this helps someone else.