Move from an activity to another one in View Class in Android - android

I have an activity that has two classes like these:
public class StartActivity extends Activity {
.
.
.
}
public class StartView extends View {
.
.
.
}
I want to go from this Activity to another one with click on one image.Is there any method (such startActivity method in Activity Class) in View Class that I can use it in the Second Class?

Do you mean something like this:
public class startView extends View {
Activity mActivity;
Context mContext;
public startView(Activity yourActivity, Context context, AttributeSet attrs) {
// TODO Auto-generated constructor stub
super(context, attrs);
this.mActivity = yourActivity;
this.mContext = context;
init();
}
public void init()
{
ImageView iv = (ImageView) findViewById(R.id.IMAGEVIEWID);
iv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent(mActivity, SecondActivity.class);
mContext.startActivity(i);
}
});
}
}

Related

Button in Android Studio interacting with View

I am working on an android application with a DrawingView.
I would like to have a button which clears the drawing view, however I cannot figure out how to make a button that calls a method in somewhere that's not the MainActivity.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
The above text is the only code in the main activity, so I do not have access to a reference of the drawingView.
public DrawingView(Context context, AttributeSet attributeSet){
super(context, attributeSet);
AsyncTask myTask = new AsyncTask() {
#Override
protected Object doInBackground(Object... objects) {
try {
DrawingView dView = (DrawingView) objects[0];
dView.connection = new Connection((DrawingView) objects[0], (Context) objects[1],new Socket("128.199.236.107", 3333));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
Object[] myObjects = new Object[2];
myObjects[0] = this;
myObjects[1] = context;
myTask.execute(myObjects);
getRes();
setupDrawing();
This is the constructor of the class DrawingView.java
There is a method in this class called "refresh", and I am trying to call it using a button. Is there any way I can do this?
The refresh method looks like this
public void refresh(){
Canvas.drawColor(0, Mode.CLEAR);
}
The MAIN ACTIVITY refresh method (called on the button press), looks like this
public void refresh(View v){
final DrawingView DV = (DrawingView) findViewById(R.id.drawing);
DV.refresh();
}
Logcat? I think
Make your shared method static by adding the "static" keyword:
public static void myFunction()
Then use:
Another Activity.myFunction();
One simpe way to cleanup your canvas is to insert this code on the OnDraw method:
Paint p=new Paint();
p.setARGB(255,100,120,140); // your background color
Rect r =new Rect();
canvas.getClipBounds(r);
canvas.drawRect(r,p);`
but it's better to perform the allocations of r and p outside of onDraw.

Pass Data Moving from activity to Class extends View

i'm trying pass data from MainActivity to my class VistaJuego which draws a doll moving on the screen but when it collides with obstacles , the game stops and with an intent should go to another activity. I need the context of my MainActivity to do my intent but Eclipse always show NullPointerException.
my MainActivity
public class MainActivity extends Activity {
RelativeLayout relative;
static Activity ac;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vistafaba=(VistaJuego)findViewById(R.id.faba);
relative=(RelativeLayout)findViewById(R.id.relative);
ac=this.getActivity();
}
public void goToActivityLosed(){
Intent i= new Intent(this,ActivityLosed.class);
startActivity(i);
}
And my VistaJuego
public class VistaJuego extends View {
ThreadJuego juego = new ThreadJuego();
ThreadFaba hiloFaba= new ThreadFaba();
MainActivity main;
public VistaJuego(Context context, AttributeSet attrs) {
super(context, attrs);
//dialogo= new DialogoFinJuego(MainActivity.this);
main= new MainActivity();
}
public void whenBeanCrash(Grafico elementofaba,Grafico elementoBotella){
if((elementofaba.getPosX()+elementofaba.getAncho()>=elementoBotella.getPosX()+15)&&
(elementofaba.getPosX()+elementofaba.getAncho() <= elementoBotella.getPosX()+elementoBotella.getAncho()+15)&&
(elementofaba.getPosY()+elementofaba.getAlto()>=elementoBotella.getPosY())
&& (elementofaba.getPosY()+elementofaba.getAlto() <= elementoBotella.getPosY()+elementoBotella.getAlto())){
juego.detener();
hiloFaba.detener();
main.goToActivityLosed();
}
If you want to start an activity use context not Activity
Example:
public void whenBeanCrash(Grafico elementofaba,Grafico elementoBotella){
// ...
// and not main.goToActivityLosed()
Context context = getContext();
context.startActivity(new Intent(context, YourActivity.class));
}
Or you can create a function to set an activity object:
public void setActivity(MainActivity activity){
this.activity = activity;
// and now in whenBeanCrash() you can use this.activity to call function from this class
}

Restarting activity inside onClick method

I have an app which reads .txt file and displays contents in table layout.
here is my MainActivity.java file:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new TableLayout(this,0));
}
}
Inside TableLayout class when adding first row (headers), i also add on click listeners.
Here is the code that gets executed when click happens:
public class MyOnClickListener extends MainActivity implements OnClickListener {
int rowNumber;
public MyOnClickListener(int rowNumber) {
this.rowNumber = rowNumber;
}
#Override
public void onClick(View v) {
setContentView(new TableLayout(context,rowNumber));
}
};
context is saved from when activity is first started, but i get nullpointexception error with this as an argument.
What i would like to do when header is clicked is to recreate table with header number argument.
So my question is what should i do to restart table creation within onClick method?
Edit: this is how context is saved
Context context;
public TableLayout(Context context, int rowNr) {
super(context);
this.context = context;
I would probably do something like this
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new TableLayout(this, getRowNumber()));
}
protected int getRowNumber(){
return 0;
}
}
and then you do something like
public class MyOnClickListener extends MainActivity implements OnClickListener {
// here you initialize rowNumber
static int rowNumber = 0;
#Override
protected void getRowNumber(){
return rowNumber;
}
#Override
public void onClick(View v) {
// here you set your rowNumber
rowNumber = some_value;
recreate();
}
};
P.S: I haven't compiled this but you can get the idea

List view disappears on moving to another activity from list view

I am facing some weird problem where when I move from Activity 1 to Activity 2 list view that is in activity 1 automatically disappears to see the list view again I need to again start Activity 1.
I am going to activity 2 from button in list view of activity 1.
I don't understand this behavior and I am unsure of problem and solution as well.
Code below:
Activity 1:
public class stockmanager extends Activity{
String getentry;
private int storeID=0;
//Database d;
StockTable st;
StockList sl;
Database d;
private String getstocks;
public Cursor a1;
Intent bd;
Intent sd;
String s,AllStocks;
private String deletestock_sl,deletestock_st;
TextView displaystocks;
ListView popstocks;
poplist populatestocks;
int stockid;
Cursor getid;
static class ViewHolder {
CheckBox cb;
Button view1;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stockmanager);
d=new Database(getApplicationContext());
st=new StockTable(getApplicationContext());
sl=new StockList(getApplicationContext());
new Dboperation().execute();
}
public class poplist extends CursorAdapter{
public poplist(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
}
#Override
public void bindView(View view, Context context, Cursor c) {
// TODO Auto-generated method stub
final ViewHolder myviewholder=new ViewHolder();
myviewholder.cb=(CheckBox) view.findViewById(R.id.checkBox1);
myviewholder.view1=(Button) view.findViewById(R.id.button1);
myviewholder.cb.setText(c.getString(c.getColumnIndexOrThrow(sl.Column2)));
myviewholder.cb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(myviewholder.cb.isChecked())
{
a.add((String) myviewholder.cb.getText());
}
}
});
myviewholder.view1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sd=new Intent(v.getContext(),Detail.class);
sd.putExtra("StockName", myviewholder.cb.getText());
startActivity(sd); //Activity 2 triggered here
}
});
}
#Override
public View newView(Context context, Cursor c, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.stocklist, parent, false);
bindView(v, context, c);
return v;
// return null;
}
}
private class Dboperation extends AsyncTask<Void, Void, Cursor>{
ProgressDialog pd;
#Override
protected Cursor doInBackground(Void... params) {
// TODO Auto-generated method stub
a1=Database.getInstance(getApplicationContext()).getWritableDatabase().rawQuery(sl.getstocks, null);
return a1;
}
protected void onPostExecute(Cursor result) {
if(a1.moveToNext())
{
displaystocks.setVisibility(View.INVISIBLE);
}
else
{
displaystocks.setVisibility(View.VISIBLE);
}
//System.out.println("Entered onpostexecute");
final poplist populatestocks=new poplist(getApplicationContext(),a1) ;
popstocks.setAdapter(populatestocks);
if(pd!=null)
pd.dismiss();
}
#Override
protected void onPreExecute() {
pd=new ProgressDialog(stockmanager.this);
pd.setMessage("Please wait.... Loading Data");
pd.show();
}
protected void onProgressUpdate(Void... values) {
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(a1!=null){
a1.close();
}
if(Database.getInstance(getApplicationContext())!=null){
Database.getInstance(getApplicationContext()).close();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(a1!=null){
a1.close();
}
if(Database.getInstance(getApplicationContext())!=null){
Database.getInstance(getApplicationContext()).close();
}
}
}
This is expected behavior. The Documentation for Activity should help you out in this case. This link should tell you everything you need to know about why you've seen this behavior.
While it is possible to have two activities visible to the user simultaneously, I rarely see this done using anything other than Fragments, and I would not recommend it in general. If what you want is to pop up a window on button click that displays new data, then you probably should instead use something like a Layout that toggles its visibility, or perhaps a Dialog.

Notification on View added to parent?

When I build a View in Android dynamically I have to add it to a "parent" ViewGroup by calling
myLinearLayout.addView(myView);
I know that I can supervise the ViewGroup for any children to be added via the excellent onHierarchyChangeListener, but in my case I need the feedback in the View itself. Therefore my question is:
Is there something like a View.onAddedToParent() callback or a listener that I can build on?
To make things very clear: I want the view to handle everything on its own, I am aware of the fact that I could catch the event in the "parent" and then notify the view about things, but this is not desired here. I can only alter the view
Edit: I just found onAttachStateChangeListener and it would seem to work for most situations, but I'm wondering if this is really the correct solution. I'm thinking a View might just as well be passed on from one ViewGroup to another without being detached from the window. So I would not receive an event even though I want to. Could you please elaborate on this if you have insight?
Thanks in advance
You can create custom view and do your stuff in its onAttachedToWindow
public class CustomView extends View {
public CustomView(Context context) {
super(context);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
Log.d("CustomView", "onAttachedToWindow called for " + getId());
Toast.makeText(getContext(), "added", 1000).show();
}
}
If you want to ensure that your customview added to correct viewgroup which you want
#Override
protected void onAttachedToWindow() {
// TODO Auto-generated method stub
super.onAttachedToWindow();
if(((View)getParent()).getId()== R.id.relativelayout2)
{
Log.d("CustomView","onAttachedToWindow called for " + getId());
Toast.makeText(context, "added", 1000).show();
}
}
According to the Android source code, a view can't be moved to another layout unless removeView() is called first on its parent, and if you look at the code of removeView(), it calls removeViewInternal(), which in turn calls an overload of removeViewInternal(), which, on this line calls view.dispatchDetachedFromWindow(), which, based on the Android source code on this line calls onDetachedFromWindow(). Then the view gets added using addView(), which calls onAttachedToWindow() in the same way.
In my opion you want like this;
CreateViews;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setOnHierarchyChangeListener(new OnHierarchyChangeListener() {
#Override
public void onChildViewRemoved(View parent, View child) {
Log.e("View","removed");
if(child instanceof CustomButton){
CustomButton button = (CustomButton)child;
button.addListener();
}
}
#Override
public void onChildViewAdded(View parent, View child) {
Log.e("View","added");
if(child instanceof CustomButton){
CustomButton button = (CustomButton)child;
button.addListener();
}
}
});
for(int i = 0; i < 10; ++i){
CustomButton view = new CustomButton(this);
view.setText("Button "+i);
layout.addView(view, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
layout.removeViewAt(layout.getChildCount()-1);
}
});
}
setContentView(layout);
}
Listener;
public interface OnAddedListener {
public void addListener();
}
CustomButton class;
public class CustomButton extends Button implements OnAddedListener{
public CustomButton(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public CustomButton(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public CustomButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
#Override
public void addListener() {
Log.e("","In button add listener");
}
}

Categories

Resources