Run Time Main Activity not come after Splash Activity and app close - java

Everything in my code looks good in both the .java and .xml files (according to the software) because I have no errors yet every time I click the app icon in the emulator, it brings up the splash screen then the app exits without showing my main activity. Here's my code so far:
SplashActivity.java
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//hide title bar of activity
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
//Making activity full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
int t =3000; //time for spash screen 3000 means 3sec
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(SplashActivity.this, MainActivity.class));
}
},t);
}
}
SplashActivity.xml
<ImageView
android:layout_width="250dp"
android:layout_height="250dp"
android:src="#drawable/icon"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
MainActivity.java:
public class MainActivity extends AppCompatActivity
{
String webAdress ="https://www.google.com/";
WebView webView;
FrameLayout frameLayout;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webView = (WebView) findViewById(R.id.webView);
frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
webView.setWebViewClient(new HelpClient());
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
frameLayout.setVisibility(View.VISIBLE);
progressBar.setProgress(newProgress);
setTitle("Loading..."); //when url is loading set this on actionbar
if (newProgress == 100) {
frameLayout.setVisibility(View.GONE); // Hide progress bar when page is loaded
setTitle(view.getTitle()); //get amd set title of opend page
}
super.onProgressChanged(view, newProgress);
}
});
webView.getSettings().setJavaScriptEnabled(true); //enable javaScript
//check internet connection
if (haveNetworkConnection()) {
webView.loadUrl(webAdress);
} else {
Toast.makeText(this, "No internet Connection", Toast.LENGTH_SHORT).show();
}
progressBar.setProgress(0);
}
private class HelpClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
frameLayout.setVisibility(View.VISIBLE);
return true;
}
}
private boolean haveNetworkConnection(){
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] networkInfos = cm.getAllNetworkInfo();
for(NetworkInfo ni : networkInfos){
if(ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if(ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//check if the event was the back button and if there's history
if ((keyCode==KeyEvent.KEYCODE_BACK) && webView.canGoBack()){
webView.goBack();
return true;
}
//if it was the back or there is no web page history, bubble up to the default system behaviour
return super.onKeyDown(keyCode, event);
}
}
MainActivity.xml:
<!--Progressbar-->
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="3dip"
android:background="#android:color/transparent">
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="match_parent"
style="?android:attr/progressBarStyleHorizontal"
android:layout_height="7dp"
android:layout_gravity="top"
android:layout_marginTop="-3dp"
android:progressDrawable="#drawable/custom_progress"
android:background="#android:color/transparent"
android:progress="20"/>
</FrameLayout>
<!--WebView-->
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
</WebView>
Here's my manifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!--internet permision-->
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".SplashActivity"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity">
</activity>
</application>
Any hints would be greatly appreciated, thank you!

The problem is in onCreate method of MainActivity, you do not provide any UI (xml layout file), as a result, the app cannot find view elements to init, set listeners, etc. I guess you can find an exception in logcat when your app close.
Solution: Provide a layout xml file for MainActivity
public class MainActivity extends AppCompatActivity {
String webAdress ="https://www.google.com/";
WebView webView;
FrameLayout frameLayout;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Add this line
webView = (WebView) findViewById(R.id.webView);
...
}
}

try use
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();

Your code is not so good. If you want to show splashscreen only when app start I recommend using the following code:
AndroidManifest.xml
<activity android:name=".view_layer.activities.SplashScreenActivity"
android:theme="#style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
styles.xml
<style name="SplashTheme" parent="#android:style/Theme.NoTitleBar.Fullscreen">
<item name="android:windowBackground">#drawable/splash</item>
</style>
SplashscreenActivity.java
public class SplashscreenActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startActivity(new Intent(this, MainActivity.class));
finish();
}
}
More: https://android.jlelse.eu/the-complete-android-splash-screen-guide-c7db82bce565

Related

Not sure if EditText or KeyEvent are not listening or is an XML problem

I'm trying to make a game but I need the user to fill in the username before jumping from Main Activity to Activity 2.
If the username is empty, itdoesn't do anything.
If the username has at least one letter, it launches second activity.
In my case it never works and I don't know what I'm doing wrong.
This is my code.
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText et1;
TextView tv1;
String usuario;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = findViewById(R.id.et1);
tv1 = findViewById(R.id.tv1);
/*Button next = findViewById(R.id.boton);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), MainActivity2.class);
startActivity(myIntent);
}
});*/
et1.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
usuario = et1.getText().toString();
if(et1.getText().toString().trim().length() > 0) {
if((event.getAction() == KeyEvent.ACTION_DOWN) && (event.getAction() == KeyEvent.KEYCODE_ENTER)) {
startActivity2();
}
}
return false;
}
});
}
public boolean startActivity2(){
Intent myIntent = new Intent(this, MainActivity2.class);
startActivity(myIntent);
return false;
}
And the activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/texto"
android:layout_centerVertical="true"
android:layout_marginRight="50dp"
android:layout_marginLeft="50dp"
android:background="#ff8200"
android:layout_marginEnd="50dp"
android:layout_marginStart="50dp" />
<Button
android:id="#+id/boton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="jump"
android:layout_below="#+id/tv1"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/et1"
android:ems="7"
android:inputType="text"
android:maxLines="1"
android:maxLength="11"
android:layout_toRightOf="#+id/tv1"
android:layout_centerInParent="true"/>
</RelativeLayout>
I tried for the ifs !isEmpty(), trim(), !equals and absolutely nothing.
Here is the manifest, if necesarry.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.juegocartas3">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.JuegoCartas3">
<activity
android:name=".MainActivity3"
android:exported="false" />
<activity
android:name=".MainActivity2"
android:exported="false" />
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Try this-
public class MainActivity extends AppCompatActivity {
EditText et1;
TextView tv1;
String usuario;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = findViewById(R.id.et1);
tv1 = findViewById(R.id.tv1);
et1.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((actionId & EditorInfo.IME_MASK_ACTION) == EditorInfo.IME_ACTION_DONE) {
usuario = et1.getText().toString();
if (usuario.trim().length() > 0) {
startActivity2();
} else {
Toast.makeText(getApplicationContext(), " Please add User name", Toast.LENGTH_LONG).show();
}
return true;
}
return false;
}
});
public void startActivity2() {
Intent myIntent = new Intent(this, MainActivity2.class);
startActivity(myIntent);
}}

Open specific links in browser, instead of webview by regex

I'm using parts of code form some tutorial to create webview app. Goals is - to open links, that not contain appdev365 in browser, not in webview. I am completly noob at android development, so all that i've searched - didn't match to my(from tutorial) code.
MainActivity.java
package com.example.ynt;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.content.Intent;
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://yatln.com/appdev365/index.php");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ynt">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="Y&T База талантов"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ynt.MainActivity">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible" />
</RelativeLayout>
SOLUTION (by Varma Lanke):
https://gist.github.com/codedamage/8f98e2ed13d1d1fa05e5d43e67ea3e6c
private WebView htmlWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
htmlWebView = (WebView)findViewById(R.id.webview);
htmlWebView.setWebViewClient(new CustomWebViewClient());
WebSettings webSetting = htmlWebView.getSettings();
webSetting.setJavaScriptEnabled(true);
webSetting.setDisplayZoomControls(true);
htmlWebView.loadUrl("https://yatln.com/appdev365/index.php");
}
private class CustomWebViewClient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.contains("appdev365"))
view.loadUrl(url);
else{
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
}
// view.loadUrl(url);
return true;
}
}
For you should use shouldOverrideUrlLoading method, once try the below one
private WebView htmlWebView;
String url = "https://yatln.com/appdev365/index.php";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainpage);
htmlWebView = (WebView)findViewById(R.id.webView);
if(url.contains("appdev365"))
htmlWebView.setWebViewClient(new CustomWebViewClient());
WebSettings webSetting = htmlWebView.getSettings();
webSetting.setJavaScriptEnabled(true);
webSetting.setDisplayZoomControls(true);
htmlWebView.loadUrl(url);
}
private class CustomWebViewClient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.equalsIgnoreCase("appdev365"))
view.loadUrl(url);
return true;
}
}
This code opens browser and specified link (ex. google.com):
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);

Button displays toast and starts service

I have two buttons (start/stop) that when clicked need to have a Toast pop up saying what has happened to the Service. Start = popup of "service has started" and the service actually starts. The service isn't finished and will be grabbing some GPS info later on.
Anyway, none of my Toasts show up and I'm hoping I'm not missing something obvious.
Main (Activity)
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startBtn = (Button) findViewById(R.id.startButton);
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), ParseService.class));
}
});
Button stopBtn = (Button) findViewById(R.id.startButton);
stopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), ParseService.class));
}
});
}
}
ParseService
public class ParseService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent e, int flags, int startId){
Toast.makeText(this, "Service has Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy(){
super.onDestroy();
Toast.makeText(this, "Service has Stopped", Toast.LENGTH_LONG).show();
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAlignment="center"
tools:context="${packageName}.${activityClass}" >
<Button
android:id="#+id/startButton"
android:layout_width="150dp"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="92dp"
android:text="Start" />
<Button
android:id="#+id/stopButton"
android:layout_width="150dp"
android:layout_height="60dp"
android:layout_alignLeft="#+id/startButton"
android:layout_below="#+id/startButton"
android:layout_marginTop="74dp"
android:text="Stop" />
</RelativeLayout>
You are supposed to use the Application's Context from a Service and not the Service's Context.
From your Service:
Toast.makeText(getApplicationContext(), // application Context not 'this'
"Service has Started",
Toast.LENGTH_LONG).show();
Alternatively, you could display them from your Activity before you invoke the Service if you wish but I think where you have the calls currently positioned makes more sense and would reduce repetition later on as long as you always want the Toast displayed.
EDIT:
Ok, after making a quick test app I think I found what might be going wrong for you.
Do you have the Service declared in your AndroidManifest.xml??
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.indivisible.testapp">
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name=".toasts.ToastActivity"
android:label="#string/title_activity_toast">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Define your Service as below.
In my case the path is:
.../TestApp/app/src/main/java/com/indivisible/testapp/toasts/ToastService.java
Android Studio has a nice auto-complete when you press '.'
-->
<service
android:name=".toasts.ToastService"
android:label="ToastService">
</service>
</application>
</manifest>
It seems like your service is not getting started, make sure the service is declared in the manifest and enabled as below:
<service
android:name=".ParseService"
android:enabled="true" />
Hope this helps

Music don't start on button click

When I go to install the app on the device, I click the button but nothing happen.
I want to make device play tosse.acc from res/raw when I click the button...
Ok resolved the problem :) thanks for answers guys :D ( i have changed the name of the song from tosse to toxxe)
public void tosse1(View v) {
Button one = (Button)this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.toxxe);
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Resume the music player
mp.start();
}
});
}
Here my code:
public void tosse1(View v) {
Button one = (Button)this.findViewById(R.id.button1);
final MediaPlayer mp = new MediaPlayer();
mp.create(this, R.raw.tosse);
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Resume the music player
mp.start();
}
});
}
activity_main:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.tosseapp.app.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button1"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="tosse1" />
</RelativeLayout>
AndroidManifest:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<activity
android:name="com.example.tosseapp.app.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Declare your mp as private variable in your class:
public class PlayaudioActivity extends Activity {
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.tosse);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
Try getting a Mediaplayer Instance like this:
final MediaPlayer mp = MediaPlayer.create(this, R.raw.tosse);
should solve your problem, because it also prepares the MediaPlayer, see documentation:
public static MediaPlayer create (Context context, int resid) Added in API level 1
Convenience method to create a MediaPlayer for a given
resource id. On success, prepare() will already have been called and
must not be called again.
When done with the MediaPlayer, you should call release(), to free the
resources. If not released, too many MediaPlayer instances will result
in an exception.

set the tabbar bottom on android all activities

i have develop one android application.
Here i have to set the tabbar bottom on all android activities.how can i do.please give me solution for these.
i have totally 10 activities means the tabbar is show on botton on all 10 activities.how can i do in android.please help me.
These is my 1st activity:
setContentView(R.layout.tabbar);
TabHost tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;
TabSpec dbspec = tabHost.newTabSpec("Home");
dbspec.setIndicator("Home", getResources().getDrawable(R.drawable.home));
Intent dbIntent = new Intent(this, MainActivity.class);
dbspec.setContent(dbIntent);
tabHost.addTab(dbspec);
TabSpec orderspec = tabHost.newTabSpec("Cart");
orderspec.setIndicator("Cart", getResources().getDrawable(R.drawable.cart));
Intent orderIntent = new Intent(this, ViewCartActivity.class);
orderspec.setContent(orderIntent);
tabHost.addTab(orderspec);
TabSpec settingspec = tabHost.newTabSpec("My Account");
settingspec.setIndicator("My Account", getResources().getDrawable(R.drawable.myaccount));
Intent settingIntent = new Intent(this, CustomerLogin.class);
settingspec.setContent(settingIntent);
tabHost.addTab(settingspec);
tabbar.xml:
<?xml version="1.0" encoding="utf-8"?>
<TabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="match_parent"
android:id="#+id/linearLayout1"
android:layout_height="match_parent">
<TabWidget
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#android:id/tabs"
android:layout_alignParentBottom="true">
</TabWidget>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#android:id/tabcontent">
</FrameLayout>
</RelativeLayout>
</TabHost>
In first tab have to perform MainActivity(GridView) activity.it is woked well.in Main activity i have to clik any item means it is go to SubCate(listview) activity.Here also i have to display tabbar on bottom.how can i set.
In subcate.xml file have included below code:
<include
android:id="#+id/footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
layout="#layout/tabbar" />
but the tabbar is not display.whats wrong here.please help me.
Please write below code instead of your code for add multiple activities in one TabActivity, it will solve your problem.
ActivityStack.java
public class ActivityStack extends ActivityGroup {
private Stack<String> stack;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (stack == null)
stack = new Stack<String>();
// start default activity
push("FirstStackActivity", new Intent(this, Tab_SampleActivity.class));
}
#Override
public void finishFromChild(Activity child) {
pop();
}
#Override
public void onBackPressed() {
pop();
}
public void push(String id, Intent intent) {
Window window = getLocalActivityManager().startActivity(id, intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
stack.push(id);
setContentView(window.getDecorView());
}
}
public void pop() {
if (stack.size() == 1)
finish();
LocalActivityManager manager = getLocalActivityManager();
manager.destroyActivity(stack.pop(), true);
if (stack.size() > 0) {
Intent lastIntent = manager.getActivity(stack.peek()).getIntent();
Window newWindow = manager.startActivity(stack.peek(), lastIntent);
setContentView(newWindow.getDecorView());
}
}
}
TabActivity.java
public class TabActivity extends TabActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_screen);
TabHost tabHost = getTabHost();
Intent intent = new Intent().setClass(this, ActivityStack.class);
TabHost.TabSpec spec = tabHost.newTabSpec("tabId").setIndicator("Temp", getResources().getDrawable(R.drawable.home));
spec.setContent(intent);
tabHost.addTab(spec);
Intent intent1 = new Intent().setClass(this, ActivityStack.class);
TabHost.TabSpec spec1 = tabHost.newTabSpec("tabId").setIndicator("Temp", getResources().getDrawable(R.drawable.invoice));
spec1.setContent(intent1);
tabHost.addTab(spec1);
tabHost.setCurrentTab(0);
}
}
FirstActivity.java
public class FirstActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setText("Tab Sample Activity ");
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getParent(), SecondActivity.class);
ActivityStack activityStack = (ActivityStack) getParent();
activityStack.push("SecondActivity", intent);
}
});
setContentView(textView);
}
}
SecondActivity.java
public class SecondActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setText("First Stack Activity ");
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getParent(), ThirdActivity.class);
ActivityStack activityStack = (ActivityStack) getParent();
activityStack.push("ThirdActivity", intent);
}
});
setContentView(textView);
}
}
ThirdActivity.java
public class ThirdActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Add Below XML files into your res/layout folder.
1) tab_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="3dp" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#android:id/tabs"
android:layout_weight="1" />
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
</RelativeLayout>
</TabHost>
2) main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
</LinearLayout>
AndroidManifest.xml:-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.tabsample"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".FirstActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".TabActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ActivityStack"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".SecondActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".ThirdActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
And see below link for more information on add multiple activities under one TabActivity with complete example.
Android - Multiple Android Activities under one TabActivity
You can use this class for implementing the functionality you have specified.
import java.util.ArrayList;
import android.app.Activity;
import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
public class TabActivityGroup extends ActivityGroup {
private ArrayList<String> mIdList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mIdList == null)
mIdList = new ArrayList<String>();
}
/**
* This is called when a child activity of this one calls its finish method.
* This implementation calls {#link LocalActivityManager#destroyActivity} on
* the child activity and starts the previous activity. If the last child
* activity just called finish(),this activity (the parent), calls finish to
* finish the entire group.
*/
#Override
public void finishFromChild(Activity child) {
LocalActivityManager manager = getLocalActivityManager();
int index = mIdList.size() - 1;
if (index < 1) {
finish();
return;
}
manager.destroyActivity(mIdList.get(index), true);
mIdList.remove(index);
index--;
String lastId = mIdList.get(index);
Intent lastIntent = manager.getActivity(lastId).getIntent();
Window newWindow = manager.startActivity(lastId, lastIntent);
setContentView(newWindow.getDecorView());
}
/**
* Starts an Activity as a child Activity to this.
*
* #param Id
* Unique identifier of the activity to be started.
* #param intent
* The Intent describing the activity to be started.
* #throws android.content.ActivityNotFoundException.
*/
public void startChildActivity(String Id, Intent intent) {
Window window = getLocalActivityManager().startActivity(Id,
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
mIdList.add(Id);
setContentView(window.getDecorView());
}
}
/**
* The primary purpose is to prevent systems before
* android.os.Build.VERSION_CODES.ECLAIR from calling their default
* KeyEvent.KEYCODE_BACK during onKeyDown.
*/
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// preventing default implementation previous to
// android.os.Build.VERSION_CODES.ECLAIR
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Overrides the default implementation for KeyEvent.KEYCODE_BACK so that
* all systems call onBackPressed().
*/
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
return true;
}
return super.onKeyUp(keyCode, event);
}
/**
* If a Child Activity handles KeyEvent.KEYCODE_BACK. Simply override and
* add this method.
*/
#Override
public void onBackPressed() {
int length = mIdList.size();
if (length > 1) {
Activity current = getLocalActivityManager().getActivity(
mIdList.get(length - 1));
current.finish();
}
}
}
Create an intermediate activity as below by extending TabActivitygroup
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class InterMediateActivity extends TabActivityGroup{
String TabID;
String TabName;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
TabID=getIntent().getStringExtra("TabID");
TabName=getIntent().getStringExtra("TabName");
Log.i("Tab from intermediate",""+TabID+" "+TabName);
filterTabs(TabID);
}
private void filterTabs(String TabID)
{
if(TabID.trim().equals("Home"))
{
startChildActivity("Options", new Intent(this,HomePage.class));
//TabsUtil.setTabIndicator(specTab,"Wall", null, tabView);
}
if(TabID.trim().equals("Menu"))
{
startChildActivity("Options", new Intent(this,MenuPage.class));
//TabsUtil.setTabIndicator(specTab,"Wall", null, tabView);
}
if(TabID.trim().equals("Gallery"))
{
Log.i("GALLERY check", "gallery check");
startChildActivity("Options", new Intent(this,GalleryPage.class));
}
if(TabID.trim().equals("Aboutus"))
{
startChildActivity("Options", new Intent(this,AboutUsPage.class));
}
if(TabID.trim().equals("Location"))
{
startChildActivity("Options", new Intent(this,LocationList.class));
}
if(TabID.trim().equals("Events"))
{
startChildActivity("Options", new Intent(this,EventsPage.class));
}
if(TabID.trim().equals("TipCalculator"))
{
startChildActivity("Options", new Intent(this,TipCalculatorPage.class));
}
if(TabID.trim().equals("Special"))
{
startChildActivity("Options", new Intent(this,SpecialPage.class));
}
if(TabID.trim().equals("NowRunning"))
{
startChildActivity("Options", new Intent(this,NowRunningPage.class));
}
if(TabID.trim().equals("ShowTimes"))
{
startChildActivity("Options", new Intent(this,ShowTimePage.class));
}
if(TabID.trim().equals("GpsCoupon"))
{
startChildActivity("Options", new Intent(this,GPSCouponPage.class));
}
if(TabID.trim().equals("UpcomingMovieNames"))
{
startChildActivity("Options", new Intent(this,UpcomingPage.class));
}
if(TabID.trim().equals("PriceListOfServices"))
{
startChildActivity("Options", new Intent(this,ServicesPage.class));
}
if(TabID.trim().trim().equals("NewsLetter"))
{
Log.i("newsletter check", "newsletter check");
startChildActivity("Options", new Intent(this,NewsLetter.class));
}
if(TabID.trim().trim().equals("Website"))
{
startChildActivity("Options", new Intent(this,WebSitePage.class));
}
}
}
And instead of setting the tabs from tabactivity directly you can set them inside the intermediate activity. Then call the Intermediate activity from the tabactivity.
Intent intent = new Intent(this, InterMediateActivity.class);
intent.putExtra("TabID", item.elementAt(0));
intent.putExtra("TabName", item.elementAt(1));

Categories