set the tabbar bottom on android all activities - java

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));

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);
}}

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

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

resume button not working to go last activity

have 4 activity : Main Activity,p1,p2,p3
my resume button not working . i want when i click in resume button app open my last activity .
for example : when in p2 click go to main , then in main when click resume , p2 open . here is my code :
Main Activity :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
Button resume = (Button) findViewById(R.id.resume);
Button next = (Button) findViewById(R.id.next);
Button exit = (Button) findViewById(R.id.exit);
resume.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences myPref = getSharedPreferences("APP_SHARED_PREF", Context.MODE_PRIVATE);
String lastActivity= myPref.getString("lastactivity","");
try {
Intent fooActivity = new Intent(MainActivity.this,Class.forName(lastActivity));
startActivity(fooActivity);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, p1.class);
startActivity(intent);
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
});
}
}
XML layout :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="resume"
android:layout_width="wrap_content"
android:id="#+id/resume"
android:layout_height="wrap_content" />
<Button
android:text="next"
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="exit"/>
</LinearLayout>
p1 :
public class p1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.p1);
Button next = (Button) findViewById(R.id.next);
Button home=(Button)findViewById(R.id.home);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(p1.this, p2.class);
startActivity(intent);
}
});
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(p1.this, MainActivity.class);
startActivity(intent);
}
});
}
private void storeCurrentActivity(){
SharedPreferences myPref =getSharedPreferences("APP_SHARED_PREF", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = myPref.edit();
editor.putString("lastactivity", this.getClass().getSimpleName());
editor.commit();
}
#Override
public void onResume(){
super.onResume();
storeCurrentActivity();
}
}
XML :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/next"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="page 1"/>
<Button
android:text="go in main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/home"/>
</LinearLayout>
and p2,p3 like p1
and this my manifast :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.er.myapplication">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".p1"
android:label="#string/title_activity_main2"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".p2"
android:label="#string/title_activity_p2"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".p3"
android:label="#string/title_activity_p3"
android:theme="#style/AppTheme.NoActionBar"/>
</application>
</manifest>
you have to do below things to achieve what you want
whenever you open activity you have to save previous activity name in prefrance.
when you press resume button get activity name from prefrance and open activity using below code
Intent intent = new Intent();
intent.setClassName("com.android.browser","com.android.BrowserActivity");
context.startActivity(intent);
// clear previous activity before start
when you app relaunch app then do step 2 again in main Activity
in this type of approch you have to maintain flow of application using singletone or clear stack before launch activity. because you have to handle backbutton

Using QR and NFC technology together in an Android app

I am developing an Android app consisting of two activites so far. The first activity (MainActivity) is started when the app is launched or when a QR code is scanned. The MainActivity starts the second activity (NFCActivity) when the user presses a button. The NFCActivity waits for the user to tap a NFC token, reads out data from the token, and returns the read data to the MainActivity.
This works fine if the app is started manually. If the app is started by scanning a QR code, taping the NFC tag does not invoke the NFCActivity's onNewIntent() method as exepcted, but instead creates a new instance of the NFCActivity on top of the already displayed one.
The enableForegroundDispatch() method is called and FLAG_ACTIVITY_SINGLE_TOP should be set. Relevant source code of a minimal example is provided below. Any help would be highly appreciated!
MainActivity:
public class MainActivity extends Activity {
private EditText dataRead;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
dataRead = (EditText) findViewById(R.id.data);
final Button readKeyButton = (Button) findViewById(R.id.readNFC);
readKeyButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent keyIntent = new Intent(MainActivity.this,
NFCActivity.class);
keyIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivityForResult(keyIntent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == 1) {
String result = intent.getExtras().getString("resultData");
this.dataRead.setText(result);
}
}
}
Main Activity's GUI:
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/readNFC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="127dp"
android:text="Read NFC Tag" />
<EditText
android:id="#+id/data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/readNFC"
android:layout_centerHorizontal="true"
android:layout_marginBottom="85dp"
android:ems="10" >
<requestFocus />
</EditText>
</RelativeLayout>
NFCActivity:
public class NFCActivity extends Activity {
private NfcAdapter mAdapter;
private PendingIntent pendingIntent;
private IntentFilter[] mFilters;
private String[][] mTechLists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read_nfc);
mAdapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
// // Setup an intent filter for all MIME based dispatches
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType("*/*");
} catch (MalformedMimeTypeException e) {
throw new RuntimeException("fail", e);
}
IntentFilter td = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
mFilters = new IntentFilter[] { ndef, td };
//
// // Setup a tech list for all NfcF tags
mTechLists = new String[][] { new String[] { NfcV.class.getName(),
NfcF.class.getName(), NfcA.class.getName(),
NfcB.class.getName() } };
}
#Override
public void onResume() {
super.onResume();
if (mAdapter != null)
mAdapter.enableForegroundDispatch(this, pendingIntent, mFilters,
mTechLists);
}
#Override
public void onPause() {
super.onPause();
if (mAdapter != null)
mAdapter.disableForegroundDispatch(this);
}
#Override
public void onNewIntent(Intent intent) {
Log.d("TEST", "onNewIntent() called.");
// READ THE NFC TAG HERE [SKIPPED FOR MINIMAL EXAMPLE]
// Return dummy data for test
Intent result = new Intent();
result.putExtra("resultData", "DUMMY DATA");
setResult(1, result);
finish();
}
}
NFCActivity's GUI:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#303030"
android:paddingLeft="30dp"
android:paddingRight="30dp" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Tap your NFC tag.."
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FF8811"
android:textSize="30sp"
android:textStyle="bold" />
</RelativeLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.nfcqrtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.NFC" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="test.nfcqrtest.MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" android:host="test.org" android:pathPrefix="/testapp" />
</intent-filter>
</activity>
<activity
android:name=".NFCActivity"
android:windowSoftInputMode="stateHidden" android:screenOrientation="portrait" android:launchMode="singleTop">
</activity>
</application>
</manifest>
In case somebody is facing a similar problem: I was finally able to overcome the issue described above by setting the android:launchMode property for the MainActivity to singleInstance.

Android Splash Screen

this is what i have in my package explorer so lets start from the top
and work our way around to the problem where i think it is located..
MainActivity.java -
package com.drg.idoser;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
now SplashActivity.java
package com.drg.idoser;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
public class SplashActivity extends Activity {
private static String TAG = SplashActivity.class.getName();
private static long SLEEP_TIME = 5; // Sleep for some time
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); // Removes title bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Removes notification bar
setContentView(R.layout.splash);
// Start timer and launch main activity
IntentLauncher launcher = new IntentLauncher();
launcher.start();
}
private class IntentLauncher extends Thread {
#Override
/**
* Sleep for some time and than start new activity.
*/
public void run() {
try {
// Sleeping
Thread.sleep(SLEEP_TIME*1000);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
// Start main activity
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
SplashActivity.this.startActivity(intent);
SplashActivity.this.finish();
}
}
}
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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
splash.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#drawable/splash_bg"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
AndroidManafest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.drg.idoser"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.drg.idoser.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>
now i think my problem is in AndroidManafest.xml i dont think i have the splach screen set up right in the AndroidManafest.xml when i launch my application from my phone it jumps to activity_main.xml and not splash.xml im new to android applications so i cant seem to find my problem but i need my splash screen to show for 5 seconds if anyone has TeamViwer and would like to help me ill post my session info if it will be faster.
Change your <application> tag to the following. You didn't have SplashActivity declared, and had your MainActivity setup as the launcher Activity.
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.drg.idoser.SplashActivity"
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="com.drg.idoser.MainActivity"
android:label="#string/app_name" />
</application>
The Best way implement a splash screen, to be displayed every time your application is launched will be to create a new activity.
public class SplashScreen extends Activity {
private Handler mHandler;
private Runnable myRunnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Just create simple XML layout with i.e a single ImageView or a custom layout
setContentView(R.layout.splash_screen_layout);
mHandler = new Handler();
myRunnable = new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
finish();
}
};
}
#Override
public void onBackPressed() {
// Remove callback on back press
if (mHandler != null && myRunnable != null) {
mHandler.removeCallbacks(myRunnable);
}
super.onBackPressed();
}
#Override
protected void onPause() {
// Remove callback on pause
if (mHandler != null && myRunnable != null) {
mHandler.removeCallbacks(myRunnable);
}
super.onPause();
}
#Override
protected void onResume() {
// Attach and start callback with delay on resume
if (mHandler != null && myRunnable != null) {
mHandler.postDelayed(myRunnable, ConstantValues.SPLASH_TIME_OUT);
}
super.onResume();
}
}
You can easily access splash screen like this. such as
public class MainActivity extends Activity {
private ImageView splashImageView;
private boolean splashloading = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
splashImageView = new ImageView(this);
splashImageView.setScaleType(ScaleType.FIT_XY);
splashImageView.setImageResource(R.drawable.ic_launcher);
setContentView(splashImageView);
splashloading = true;
Handler h = new Handler();
h.postDelayed(new Runnable() {
public void run() {
splashloading = false;
// set your layout file in below
setContentView(R.layout.activity_main);
}
}, 3000);
}
}
it will be works 100%.
Here is a simple one!
~Lunox
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
splashscreen.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class splashscreen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
//Splash Screen duration
int secondsDelayed = 1;
new Handler().postDelayed(new Runnable() {
public void run() {
startActivity(new Intent(splashscreen.this, MainActivity.class));
finish();
}
}, secondsDelayed * 3000);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
splashscreen.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/splashlogo"
/>
splashlogo.png
splashlogo.png
GitHub
SplashScreen
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread th = new Thread(new Runnable() { /*create a new thread */
#Override
public void run() { /*
* The purpose of this thread is to
* navigate from one class to another
* after some time
*/
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
/*
* We are creating this new thread because we don’t
* want our main thread to stop working for that
* time as our android stop working and some time
* application will crashes
*/
e.printStackTrace();
}
finally {
Intent i = new Intent(MainActivity.this,
Splash_Class.class);
startActivity(i);
finish();
}
}
});
th.start(); // start the thread
}
http://www.codehubb.com/android_splash_screen

Categories