I am working on Base adapter in Android and i want to know that which overriden method gets call in BaseAdapter Class if i press onBackPress in some activity. Please help me, I have searched and didnt find any solution.
You probably have listview and you have a custom adapter set for the listview. Listview is in your activity.
class MyActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstancestate)
{
setContentView(R.layout.main);
ListView lv= (ListView) findViewById(R.id.listview);
CustomAdapter cus= new CustomAdapter(MyActivity.this);
lv.setAdapter(cus);
}
}
class CustomAdapter extends BaseAdapter
{
....................
}
So when you press back button the current activity is popped form the back stack, destroyed and previous activity in the back stack takes focus.This the default behaviour.
http://developer.android.com/guide/components/tasks-and-back-stack.html
You can override onKeyDown(params) in your activity
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
public void onBackPressed() {
//do something
finish();
return;
}
Overide onBackPressed in your activity and Change data to adapter accordingly then call notifyDataSetChanged
The onBackPressed will be activated in your Activity class. It is not an event of BaseAdapter class. So override your onBackPressed method in the Activity class.
you can pass activity reference to adapter via constructor like:
CustomAdapter customAdapter=CustomAdapter(getApplicationContext(),arrayList,HomeActivity.this);
and in Your Custom Adapter
public class CustomAdapter extends BaseAdapter {
Context context;
ArrayList<CategoryModel> arrCategoryModel;
AppCompatActivity activity;
public CustomAdapter(Context context, ArrayList<CategoryModel> arrCategoryModel, AppCompatActivity activity)
{
this.context=context;
this.arrCategoryModel=arrCategoryModel;
this.activity=activity;
} }
Now you can call activity.onBackPressed(); wherever you want.
Related
In my app i have a tab layout (4 total), each tab contain a ListFragment managed by a ViewPagerAdapter, what i want to do is update the content of one of these ListFragment when an activity (called with a button in the Action bar) finishes, and possibly set the focus on the right Tab.
I've searched for a solution and i have found this one : update ListFragment when Activity finishes , but seems doesn't works in my case.
For start the activity (the one for adding an user to display in the list) in the MainActivity i've used:
Intent intent = new Intent(this, CreateUser.class);
startActivityForResult(intent, 101);
At the end of the CreateUser activity i've set:
setResult(Activity.RESULT_OK);
finish();
And in the ListFragment class:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == MYACTIVITY_REQUEST_CODE) && (resultCode == Activity.RESULT_OK)){
((BaseAdapter)adapter).notifyDataSetChanged();
}
}
But when the activity finishes nothing happens because onActivityResult is never called. How can i do?
EDIT : Added class for best understanding
CreateUser.java
public class CreateUser extends AppCompatActivity {
//The user creation process is done inside class ProcessCreateUser
//that extend AsycTask
private class ProcessCreateUser extends AsyncTask<String, String, JSONObject> {
//...
//onPreExecute, doInBackground
//...
#Override
protected void onPostExecute() {
super.onPostExecute();
//db op...
//at this point the db is updated with the new user and close the activity
finish();
}
}
public void onDestroy(){
Tab3.updateFragmentList();
}
}
Tab3.java (ListFragment class)
public class Tab3 extends ListFragment implements Observer
{
//in onActivityCreated(Bundle savedInstanceState) i get the data from the db and set the adapter
#Override
public void update(Observable observable, Object data) {
}
public static void updateFragmentList() {
//problem: i can't get the adapter from a static function
//but this must be static for be called from CreateUser
((BaseAdapter)adapter).notifyDataSetChanged();
}
}
I think you can use Observer pattern. For example:
public interface Observer {
public void updateFragmentList();
}
public class YourFragment extends Fragment implement Observer {
public void updateFragmentList() {
// You do some magic code here, such as:
// Update your data for each FragmentList
}
}
public class YourActivity extends Activity {
private ArrayList<Observer> observers = new ArrayList<Observer>();
public void onCreate() {
// Here you add all FragmentList to observers
}
public void onDestroy(){
for(Observer ob in observers) {
ob.updateFragmentList();
}
}
}
I finally got it (without Observer), i've moved the onActivityResult method from ListFragment to MainActivity, in the ListFragment i've added a simple public void updateView() method for all the update jobs of the list, and i've added the following method into the ViewPagerAdapter for call the updateView() method:
#Override
public int getItemPosition(Object object) {
if (object instanceof Tab3) {
((Tab3) object).updateView();
}
return super.getItemPosition(object);
}
I have created my own search view as below
public class MySearchView extends SearchView {
public MySearchView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
// The normal SearchView doesn't clear its search text when
// collapsed, so we will do this for it.
#Override
public void onActionViewCollapsed() {
setQuery("", false);
super.onActionViewCollapsed();
}
}
When i have to create an item of this search View i must pass the context like getActivity()
But since ActionBarActivity does not have getActivity(), what should I pass
Inside the ActionBarActivity extended class, you can access the context by calling the method: getApplicationContext().
Hope this helps!
Nick
I have a method in MainActivity. java
public void spinset(String[] a)
{
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, a);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin_main = (Spinner) findViewById(R.id.spinner);
spin_main.setAdapter(adapter);
spin_main.setPrompt("Член семьи");
spin_main.setSelection(0);
}
I need to call this method on onCLick event in Dialog_mem.java
...
MainActivity ma=new MainActivity();
...
public void onClick(View v) {
switch(v.getId())
{ case R.id.mem_btnOK:
datasource.open();
datasource.putrecord("Mem_Name", memname.getText().toString());
datasource.insertrecord("Members");
date=datasource.curspinner("Members", "Mem_Name");
datasource.close();
//HERE
ma.spinset(date);
default:
dismiss();}
}
But I need this method to work for my MainActivity, not for Dialog_mem.
Or is there a way to know in MainActivity that the button in Dialog_mem was clicked? Or Maybe you know another way to do this?
you can implement your own interfaces to give call back to previous activity this can be done as shown below
public interface myListener {
public void doMyWork(boolean success, Object message);
}
make your mainActivity implement this listener and override unimplemented methods:
public class MainActivity extends Activity implements myListener{
onCreate(Bundle savedInstanceState){
Dialog_mem dm = new Dialog_mem();
dm.setmyListener(this);
}
public void doMyWork(boolean success,Object message){
// your code here
// call spinset from here
}
}
create the setmyListener() method in Dialog_mem
public class Dialog_mem {
myListener listener;
public void setmyListener(myListener listener){
this.listener = listener
}
}
make a callback from Dialog_mem to MainActivity by calling this method when you want to do your work in spinset method.
public void onClick(View v) {
switch(v.getId())
{ case R.id.mem_btnOK:
datasource.open();
datasource.putrecord("Mem_Name", memname.getText().toString());
datasource.insertrecord("Members");
date=datasource.curspinner("Members", "Mem_Name");
datasource.close();
//HERE
listener.doMyWork(success,message);
default:
dismiss();}
}
start Dialog_mem by calling startActivityForResult and in case of ok send a result code.
In your MainActivity onActivityResult will be called when you come back from Dialog_mem here you can check the result code and call your function.
I have 2 activities, Activity1 and Activity2. In Activity1 I have a button to go to Activity2.
Activity2 has a lot of Edittext and other Views.
When I start the app, the memory of the process is 10mb. If I click on the button and Activity2 is loaded, my memory's process is about 59mb.
The issue is, in Activity2, if I push Back Button, I return to Activity1 and my memory's process is about 59mb, and I don't need this information about Activity2.
Now, If I click again the button, I have an OutOfMemory.
How can I force to free up the memory when I push Back Button?
I try to call finish() and System.gc() but It doesn't work.
Thank you
try this one....
first close your activity...
use following code...
public class ur_clss extends Activity {
private ur_class c1;
//ur content here
#Override
public void onBackPressed () {
c1.finishActivity(0);
}
}
You need to override the BackButton and free up the memory when it is pressed.
#Override
public void onBackPressed()
{
Activity.finish() // the activity that you want to terminate
}
Or, there is another way to do it. When you start the new activity, the old activity goes onPause(). You could try calling finish() in the onPause() of the old activity.
This is the structure of the code:
public class Activity2 extends Activity {
// Global variables
private CarregaOperacions carrega_operacions;
private TableLayout taula;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Some code of UI
// Show a ProgressBar
loadProgress();
carrega_operacions = new CarregaOperacions(Activity2.this);
carrega_operacions.execute(null);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
finish();
}
return super.onKeyDown(keyCode, event);
}
static class CarregaOperacions extends AsyncTask<Void, Void, Void> {
WeakReference<Activity2> context;
Activity2 act;
public CarregaOperacions(Activity2 activity) {
context = new WeakReference<Activity2>(activity);
act = context.get();
}
#Override
protected Void doInBackground(Void... arg0) {
act.carregaOperacions();
return null;
}
protected void onPostExecute(Void result) {
ArrayList<LinearLayout> llista = act.getLlistaFiles();
for (int i = 0; i < llista.size(); i++ ) {
act.getTable().addView(llista.get(i));
}
act.getScroll().setVisibility(View.VISIBLE);
act.treuProgres();
}
}
With this code, I explain a bit:
The real case is, Activity1 calls a TabActivity, that has the Activity2. Activity2 loads a lot of registers, and I do this asynchronously. I Override onKeyDown in Activity2 and on the TabActivity, but it seems that only is onKeyDown's Activity2 executed.
I am trying to start an activity from a normal class and I can't figure out how it is done, if it can be done. On an itemClick I want to start an activity that extends the ListView class to show a list of options.
Also the class that receives the onItemClick is not an activity. I will post the code to try to visualize what i mean.
This is my onClick method in the class that wants to start a an activity.
public void onClick(View v) {
if (v.equals(this)) {
notifyObservers(this.getId());
} else if(v.equals(editButton) || v.equals(deleteButton)) {
This is where I want to start the activity to show my ListView...
}
}
This is my class that extends the ListView class.
public class ProfileSettings extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] mainSettings = getResources().getStringArray(R.array.mainSettings);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, mainSettings));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Do something
}
});
}
}
Thanks in advance!
I think this may help you:
"Pass the context of the activity via constructor to your class or make a static context in your activity.
With the context you can start activities like you would start them within the activity class."
class First extends Activity {
...
Second test = new Second(this);
test.start();
...
}
class Second {
private Context mContext;
...
public Second(Context c) { this.mContext = c; }
...
public start() { mContext.startActivity(...); }
}
for more detail check
http://www.anddev.org/view-layout-resource-problems-f27/starting-an-activity-from-a-non-activity-class-t14483.html
Try this in your onClick
Intent i = new Intent(this, ProfileSettings.class);
startActivity(i);
EDIT:
Also dont forget to add the activity to your manifest.