Android: Overriding onCreate method of main activity - java

I have a Java activity like so.
package com.xxx.yyy.overrideoncreate;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("DEBUG","Original oncreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
I wish to split some of the onCreate instructions to a separate class, so I created this too.
package com.xxx.yyy.overrideoncreate;
import android.os.Bundle;
import android.util.Log;
/**
* Created by oox on 26/6/17.
*/
public class SubClass extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("DEBUG","Overridden");
super.onCreate(savedInstanceState);
}
}
I intend for subClass.onCreate to override MainActivity.onCreate -- both Overridden and original oncreate messages should be displayed. However, that did not seem to happen, the overridden message did not appear in the Logcat.
Any idea what I did wrong?
Thanks in advance.

In order for SubClass's onCreate to be called, an instance of SubClass should be created instead of an instance of MainActivity when the application is launched.
For that to happen, SubClass should become the actual main activity of your application (i.e. the activity class registered in the AndroidManifest.xml which gets launched when the application is launched).

Related

activity error in manifest file in android studio

I have a manifest error. It was fine at first time.
But i chagned it to "public class color_dia extends Dialog implements View.OnClickListener"
and it was red line on color_dia in manifest file.
when i click a button related to color_dia. it makes error
"java.lang.RuntimeException: Unable to instantiate activity ComponentInfo"
what should i do?
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import static android.graphics.Color.rgb;
public class color_dia extends Dialog implements View.OnClickListener {
private MainActivity mActivity;
public color_dia(Context context) {
super(context);
mActivity = (MainActivity) context;
}
public color_dia(Context context, int themeResId) {
super(context, themeResId);
mActivity = (MainActivity) context;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Pick Line Color");
setContentView(R.layout.color_dia);
}
}
You cannot launch a Dialog using startActivity() or startActivityForResult(). You can only launch activities (class that extends Activity). A Dialog is shown in an Activity by calling showDialog() (or use DialogFragment). Please read about the difference between Dialog and Activity in the Android documentation or find a suitable tutorial to follow.

Load PowerPoint file in Android

I am trying to make a PPT viewer app.I have added the pptViewer library in my project from https://github.com/itsrts/pptviewer-android.
But I am getting an error called "cannot resolve symbol 'activity'" on this line pptViewer.loadPPT(activity,"/home/waheed/lab6.pptx").Please help.
Below is my code:
package com.example.waheed.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.itsrts.pptviewer.PPTViewer;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PPTViewer pptViewer = (PPTViewer) findViewById(R.id.pptviewer);
pptViewer.setNext_img(R.drawable.next)
.setPrev_img(R.drawable.prev)
.setSettings_img(R.drawable.settings)
.setZoomin_img(R.drawable.zoomin)
.setZoomout_img(R.drawable.zoomout);
pptViewer.loadPPT(activity,"/home/waheed/lab6.pptx");
}
}
activity isn't a defined symbol, but . In this case, since the code is in an activity, use the current object:
pptViewer.loadPPT(this, "/home/waheed/lab6.pptx");
You probably copy-pasted from the readme, as the activity used as sample method input in the readme means you have to pass an activity instance. You don't declare Activity activity = ..., but since you're in an activity you can use this
pptViewer.loadPPT(this,"/home/waheed/lab6.pptx");
Try this:
pptViewer.loadPPT(MainActivity.this,"/home/waheed/lab6.pptx");
You reference activity in your code which is not defined. Pass current class instead of the undefined field.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PPTViewer pptViewer = (PPTViewer) findViewById(R.id.pptviewer);
pptViewer.setNext_img(R.drawable.next)
.setPrev_img(R.drawable.prev)
.setSettings_img(R.drawable.settings)
.setZoomin_img(R.drawable.zoomin)
.setZoomout_img(R.drawable.zoomout);
pptViewer.loadPPT(MainActivity.this,"/home/waheed/lab6.pptx");
}

Can we call a method declared in same class in MainActivity not in onCreate or other methods in android studio?

I have created a method in MainActivity class. I know I can call that in onCreate method and other methods in that same class. But can I call that method outside onCreate and other methods but in MainActivity class?
When I try to do that, I get an error.
The error I am getting is "Invalid method declaration" but I have already declared the method below. I am just calling it here.
package com.example.android.kabaddicounter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
//Can we call this method here? Its giving an error
displayForPakistan(25);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void displayForPakistan(int score){
TextView scoreView = (TextView) findViewById(R.id.score_pakistan);
scoreView.setText(String.valueOf(score));
}
public void displayForIndia(int score){
TextView scoreView = (TextView) findViewById(R.id.score_india);
scoreView.setText(String.valueOf(score));
}
}
The answer is no you can't, unlike other codeflows the android codeflow runs only through callback functions called from the devices internal system.
You can for example call a method from other method but if that method will not be call from any of the callbacks , both will never get excited
With that been said, you have the exception of listener which can also call methods but there are just another type of callbacks
Read about activitys lifecycle to learn more

Android Development: Having an AsyncTask in a separate class file

I have been playing around with various examples trying to familiarize myself with AsyncTask. So far all the examples I have seen have had the AsyncTask included into the onCreate method of the main activity. Which I don't like very much, so I was wanting to see how hard it would be to separate it into its own class. So far I have this:
the main activity
package com.example.asynctaskactivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.asynctaskactivity.ShowDialogAsyncTask;
public class AsyncTaskActivity extends Activity {
Button btn_start;
ProgressBar progressBar;
TextView txt_percentage;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_start = (Button) findViewById(R.id.btn_start);
progressBar = (ProgressBar) findViewById(R.id.progress);
txt_percentage= (TextView) findViewById(R.id.txt_percentage);
Log.v("onCreate","Attempt set up button OnClickListener");
btn_start.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
btn_start.setEnabled(false);
new ShowDialogAsyncTask().execute();
}
});
Log.v("onCreate","Success!");
}
}
the new seperate AsyncTask class
package com.example.asynctaskactivity;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class ShowDialogAsyncTask extends AsyncTask<Void, Integer, Void>{
int progress_status;
#Override
protected void onPreExecute() {
// update the UI immediately after the task is executed
Log.v("onPreExecute","1");
super.onPreExecute();
Log.v("onPreExecute","2");
//Toast.makeText(AsyncTaskActivity.this,"Invoke onPreExecute()", Toast.LENGTH_SHORT).show();
progress_status = 0;
Log.v("onPreExecute","3");
txt_percentage.setText("downloading 0%");
Log.v("onPreExecute","4");
}
#Override
protected Void doInBackground(Void... params) {
Log.v("doInBackground","1");
while(progress_status<100){
progress_status += 2;
publishProgress(progress_status);
SystemClock.sleep(300);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
txt_percentage.setText("downloading " +values[0]+"%");
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Toast.makeText(AsyncTaskActivity.this,"Invoke onPostExecute()", Toast.LENGTH_SHORT).show();
txt_percentage.setText("download complete");
btn_start.setEnabled(true);
}
}
Originally this was all in the main activity, hence the mentions to the elements that the asynctask should in theory update. Obviously at present this is causing runtime errors, which then got me thinking. How can I have the file seperate but still update the UI thread.
Sorry if this is a stupid question, quite new to android development and background threads in particular.
How can I have the file seperate but still update the UI thread.
Okey. So at first you know that main advantage of AsyncTask added in Activity as inner class is that you have direct access to all UI elements and it makes possible pretty "lightweight" UI updates.
But if you decided to make AsyncTask separated from Activity(which also have some benefits e.q. code is more clean and app logic is separated from appearance) class you can:
You can pass UI elements via constructor of class
You can create various setters
You can create some interface that will hold callbacks. Look at Android AsyncTask sending Callbacks to UI
This is all what you need i guess.
Add a callback interface, and let your Activity implement it.
public interface MyAsyncTaskCallback{
public void onAsyncTaskComplete();
}
In the postexecute:
myAsyncTaskCallback.onAsyncTaskComplete();
In the constructor of your AsyncTask you could pass the instance of MyAsyncTaskCallback (your Activity).
Your best way of handling this is via a Handler. Instantiate one in the activity and override the method handleMessage(). When you create ShowDialogAsyncTask class just pass in the handler and maintain a reference to it. On postExecute you can construct a message and send it via the handler method sendMessage().
A previous answer mentioned using an interface and a callback paradigm. This will work, however, there is a chance that the activity can be destroyed and won't be present when the postExecute method is executed so you would need to test for this.

Android Development: "Cannot be resolved"

Hoping to get into android app development so I'm doing some basic tutorials just now.
Just trying to get comfortable with the basics at the moment, one of which is using the Typeface class.
package org.me.myandroidstuff;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Typeface;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class HelloWorldActivity extends Activity implements OnClickListener
{
private View mainView;
private TextView tbox1;
private Button exitButton;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainView=(View)findViewById(R.id.mainView);
mainView.setBackgroundColor(getResources().getColor(R.color.silver));
tbox1 = (TextView)findViewById(R.id.textBox1);
tbox1.setTypeface(Typeface.MONOSPACE);
}
}
The line
tbox1 = (TextView)findViewById(R.id.textBox1);
Has a red cross beside it (I'm using eclipse) with the error
tbox1 cannot be resolved
Its been a while since i have used java, but as i aware the following code
create a new TextView object called tbox1
Assigns the tbox1 object the id specified in the xml for the TextView tag in an external main.xml
Then tbox1 executes the setTypeFace() method on itself?
Obviously I'm going wrong somewhere, any ideas? Something really simple no doubt...
You can't inform us about one error and neglect the others. Look at your code.
Besides what user370305 said, you have other problems. Namely, your Activity, according to the contract, implements OnClickListener but does not override the necessary onClick(View v) method. You must add it for the contract to be met.
So your code should look like:
package org.me.myandroidstuff;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class HelloWorldActivity extends Activity implements OnClickListener {
private View mainView;
private TextView tbox1;
private Button exitButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainView=(View)findViewById(R.id.mainView);
mainView.setBackgroundColor(getResources().getColor(R.color.silver));
tbox1 = (TextView)findViewById(R.id.textBox1);
tbox1.setTypeface(Typeface.MONOSPACE);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Remember, you can't talk about errors until you fix every other that might cause other errors to be falsely reported.
First try to set setContentView(R.layout.yourlayoutfilename); in onCreate().
1.) Delete line super.onCreate(savedInstanceState);
2.) Retype super.onCreate(savedInstanceState);
3.) Clean the Project
4.) Build the Project

Categories