getApplicationContext() method getting error - java

I am a Android beginner, making a simple Service example.
but in a single code getApplicationContext() method behaves differently, Please check comment of MainActivity.
MainActivity.java
package com.avisingh.servicetest;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button alertButton = (Button)findViewById(R.id.alert_btn);
alertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); //If i placing here getApplicationContext() method then getting error;
builder.setTitle("Warning");
builder.setMessage("Are you sure to open media played in this app?");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(getApplicationContext(),PlayerActivity.class)); // here getApplicationContext() and MainActivity.this both working
}
});
builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show(); //getting error here.
}
});
}
}
PlayerActivity.java
package com.avisingh.servicetest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class PlayerActivity extends AppCompatActivity{
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_activity);
final Button startBtn = (Button)findViewById(R.id.start_btn);
final Button stopBtn = (Button)findViewById(R.id.stop_btn);
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getApplicationContext(),MyServices.class));
}
});
stopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getApplicationContext(),MyServices.class));
}
});
}
}
MyServices.java
package com.avisingh.servicetest;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
public class MyServices extends Service {
MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
//return null;
throw new UnsupportedOperationException("Not implemented");
}
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.one_man);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer.start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
}
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.avisingh.servicetest">
<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=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".PlayerActivity"/>
<service android:name=".MyServices"/>
</application>
activity_main
<?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.avisingh.servicetest.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/alert_btn"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:id="#+id/alert_btn"/>
</RelativeLayout>
player_activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/start_btn"
android:id="#+id/start_btn"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="#string/stop_btn"
android:id="#+id/stop_btn"/>
</RelativeLayout>
Error:
08-14 14:17:58.916 6874-6874/com.avisingh.servicetest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.avisingh.servicetest, PID: 6874
java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
at android.support.v7.app.AppCompatDialog.setContentView(AppCompatDialog.java:83)
at android.support.v7.app.AlertController.installContent(AlertController.java:225)
at android.support.v7.app.AlertDialog.onCreate(AlertDialog.java:257)
at android.app.Dialog.dispatchOnCreate(Dialog.java:373)
at android.app.Dialog.show(Dialog.java:274)
at com.avisingh.servicetest.MainActivity$1.onClick(MainActivity.java:42)
at android.view.View.performClick(View.java:4759)
at android.view.View$PerformClick.run(View.java:19770)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5247)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)

//If i placing here getApplicationContext() method then getting error
Correct. That is because the Application object does not know anything about themes, and your dialog needs a theme based on Theme.AppCompat. Always use your Activity context for creating dialogs.
You may wish to read Dave Smith's awesome blog post on the uses of different types of Context object for more on this.

Related

A Button which does not work

I am trying to make a quiz app in Android Studio 1.5 and my title screen "Begin" Button does not work.
It is supposed to lead from the MainActivity to the second Activity named questionone.
Here is the Button from the layout:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Begin"
android:id="#+id/begin"
android:layout_marginTop="45dp"
android:layout_below="#+id/textView"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView"
android:clickable="true"
android:background="#ffffff"
android:onClick="toDo" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit"
android:id="#+id/exit"
android:layout_marginTop="27dp"
android:layout_below="#+id/begin"
android:layout_alignLeft="#+id/begin"
android:layout_alignStart="#+id/begin"
android:clickable="true"
android:onClick="toDo"
android:background="#ffffff" />
Here is the code from my MainActivity Java file:
package com.example.noot_a_normal_pc.kmtomiles;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import static android.widget.Toast.makeText;
public class MainActivity extends AppCompatActivity {
Button buttonBegin, buttonExit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonBegin = (Button) findViewById(R.id.begin);
buttonExit = (Button) findViewById(R.id.exit);
}
public void buttonBegin (View view){
Intent intent = new Intent (this, question.class);
startActivity(intent);
}
public void toDo(View v) {
if (v.equals(buttonExit)) {
Toast.makeText(getApplicationContext(), "Why would you want to exit such a great app?", Toast.LENGTH_LONG).show();
}
}
}
Here is also my Android Manifest file:
<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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".questionone">
</activity>
</application>
</manifest>
Your problem is that you have put android:onClick="toDo" twice, and so buttonBegin is never used.
As an alternative, I would recommend this after you remove any android:onClick from the XML
public class MainActivity extends AppCompatActivity
implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.begin).setOnClickListener(this);
findViewById(R.id.exit).setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.begin:
// handle begin
break;
case R.id.exit:
// handle exit
break;
}
}
}
Also, based on the Activity name "questionone", I would strongly suggest you avoid the thought that you need one new Activity per question.
You only need one generic Activity to display any question.
In your MainActivity, I would recommend implementing an OnClickListener...
package com.example.noot_a_normal_pc.kmtomiles;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import static android.widget.Toast.makeText;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button buttonBegin, buttonExit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonBegin = (Button) findViewById(R.id.begin);
buttonBegin.setOnClickListener(this);
buttonExit = (Button) findViewById(R.id.exit);
buttonExit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.equals(buttonExit)) {
Toast.makeText(getApplicationContext(), "Why would you want to exit such a great app?", Toast.LENGTH_LONG).show();
}
else if (v.equals(buttonBegin)) {
//run your app!
}
}
}
your Button xml is wrong, change it like below:(onClick field is changed from toDo to buttonBegin)
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Begin"
android:id="#+id/begin"
android:layout_marginTop="45dp"
android:layout_below="#+id/textView"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView"
android:clickable="true"
android:background="#ffffff"
android:onClick="buttonBegin" />
Your button will newer call "buttonBegin(View v)" because in his XML you set "toDo(View v)" in onClick attribute.
So you should make it look like this:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Begin"
android:id="#+id/begin"
android:layout_marginTop="45dp"
android:layout_below="#+id/textView"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView"
android:clickable="true"
android:background="#ffffff"
android:onClick="buttonBegin" />
But better and cleaner idea to accomplish what you want is setting onClickListener on your button. Something like this:
buttonBegin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent (this, question.class);
startActivity(intent);
}
});
If user clicks on you button then code inside onClick(View v){ //code } will run.

Android: WebView app crashes after 3 seconds of showing Splash screen

so I've decided to make an android application for my website (not many people read it, however I think it'll look good on my Ucas!
My problem is that after the splash screen is displayed on my phone the app crashes, I'm quite new to android app development so I'm unsure about what I'm doing wrong.
I've uploaded my sourcecode on to Github so that you can have a better look at it!
Heres some of my code:
MainActivity.java
package com.alffiw.alffisblog;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
private WebView mWebView;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.coderefer.com");
mWebView.setWebViewClient(new HelloWebViewClient());
}
private class HelloWebViewClient extends WebViewClient{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url)
{
webView.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(view.GONE);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{ //if back key is pressed
if((keyCode == KeyEvent.KEYCODE_BACK)&& mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set title
alertDialogBuilder.setTitle("Exit");
// set dialog message
alertDialogBuilder
.setMessage("Do you really want to exit?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
MainActivity.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
SplashScreen.java
package com.alffiw.alffisblog;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class SplashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread timerThread = new Thread(){
public void run(){
try{
sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent intent = new Intent(SplashScreen.this,MainActivity.class);
startActivity(intent);
}
}
};
timerThread.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
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" 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=".MainActivity">
<ProgressBar
android:layout_centerHorizontal="true"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:id="#+id/progressBar1"/>
<TextView
android:layout_below="#+id/progressBar1"
android:layout_height="wrap_content"
android:id="#+id/LoadingText"
android:layout_width="fill_parent"
android:text="Loading, Please Wait.."
android:textSize="20sp"
android:gravity="center_horizontal">
</TextView>
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.alffiw.alffisblog.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="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:layout_height="match_parent"
android:background="#drawable/splash_image"
android:orientation="vertical">
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.alffiw.alffisblog">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".SplashScreen"
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=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.coderefer.androidsplashscreenexample.MAINACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Thank you for any help in advance!
Instead of calling from thread use Handler
protected void onCreate(Bundle savedInstanceState) {
//your stuff.....
new android.os.Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (!isFinishing()) {//just to make sure user didn,t press back button
Intent mainIntent = new Intent(Splashscreen.this, MainActivity.class);
startActivity(mainIntent);
finish();
}
}
}, 3000);//waiting time
}
You can't call startActivity(intent) form inside the thread you've created. Firstly because startActivity(...) is a Context method and secondly, you need to execute this statement on the UI thread.
Try this:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
final Context activity = this;
Thread timerThread = new Thread(new Runnable(
public void run(){
try{
sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
activity.runOnUiThread(new Runnable() {
public void run(){
Intent intent = new Intent(SplashScreen.this,MainActivity.class);
activity.startActivity(intent);
}
});
}
}
));
timerThread.start();

Splash screen in Android glitch

I have developed a splash screen in Android which comes for 2 seconds and go to the main activity. The problem is that when I start the application the main activity comes for few milliseconds and then goes to the splash screen activity. Can I know the solution for this?
splashscreen.java
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;
import android.view.WindowManager;
public class splashscreen extends Activity {
private static int splashInterval = 2000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
etWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splashscreen);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent i = new Intent(splashscreen.this, MainActivity.class);
startActivity(i);
this.finish();
}
private void finish() {
// TODO Auto-generated method stub
}
},
splashInterval);
};
}
splashscreen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" >
<ImageView android:src="#drawable/splash" android:layout_width="fill_parent" android:layout_height="fill_parent" android:scaleType="fitXY"/>
<ProgressBar android:id="#+id/progressBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="58dp" />
</RelativeLayout>
Android Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="asdf.splashtest1" >
<application android:allowBackup="true" android:icon="#drawable/ic_launcher" android:label="#string/app_name" android:theme="#style/AppTheme" >
<!-- Splash screen -->
<activity android:name=".splashscreen" android:label="#string/app_name" android:screenOrientation="portrait" android:noHistory="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Main activity -->
<activity android:name=".MainActivity" android:label="#string/app_name" ></activity>
</application>
</manifest>
//MainActivity.java
package asdf.splashtest1;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
This is my Splash Code Maybe This will helps,
Thread Background = new Thread() {
public void run() {
try {
sleep(2000);
Intent intent = new Intent(splashscreen.this, MainActivity.class);
startActivity(intent);
finish();
} catch (Exception e) {
}
};
Background.start();
}
At sleep(2000), enter your desired time in milliseconds.
Edit
private class SplashTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
finish();
Intent intent = new Intent(SplashActivity.this,
MainActivity.class);
startActivity(intent);
}
}
Call This Async with in onCreate Method new SplashTask().execute();

Calling Textview values using Android app

I am doing a Android app where I want to show the travels contact numbers. Here is the code:
App2Activity.java
package com.example.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
public class App2Activity extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
}
}
AppActivity.java
package com.example.android;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class AppActivity extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, App2Activity.class);
Intent intent = new Intent(Intent.ACTION_CALL);
startActivity(intent);
}
});
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Travels and Holidays" />
</LinearLayout>
main2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/travels"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Travels and Holidays Details</string>
<string name="travels">\n
Nirmala travels - 0824-2497051 \n
RR Tours and Travels - 0824-4280999 \n
Surabhii Travels - 0824-2212111 \n
</string>
</resources>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".AppActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:label="#string/app_name"
android:name=".App2Activity" >
</activity>
</application>
</manifest>
When clicked on "Travels and Holidays" button, it shows the 3 travels names with their contact number.
I want to call that travels through the app. So if I click on particular travels, it should redirect to the call of that number.
Where am I going wrong? Please help. Thanks in advance.
AppActivity.java
public class AppActivity extends Activity {
Button button;
Context context = this;
private final CharSequence[] TRAVELS ="Nirmala travels","RR Tours and Travels","Surabhii Travels"};
String numbertodial;
String phonenumberNT ="08242497051";
String phonenumberRR ="08244280999";
String phonenumberST ="08242212111";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Dialog dialog = null;
AlertDialog.Builder builder = null;
builder = new AlertDialog.Builder(context);
String travels = getString(R.string.app_name);
builder.setTitle(travels);
builder.setSingleChoiceItems(TRAVELS, 3,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
CharSequence s = (TRAVELS[item]);
//THIS CAN BE IMPROVED. I DONT HAVE THE TIME BUT IT SHOULD STILL WORK.
if (s.equals("Nirmala travels")){numbertodial =phonenumberNT; }
if (s.equals("RR Tours and Travels")){numbertodial=phonenumberRR; }
if (s.equals("Surabhii Travels")){numbertodial=phonenumberST ;}
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:"+numbertodial ));
startActivity(callIntent);
dialog.dismiss();
}});
dialog = builder.create();
dialog.show();
return;
}
});
//REMOVE addListenerOnButton(); and it's method
}

Button's don't work when clicked on, Code is correct

I tried test files like HelloWorld and Count Down timer. Neither of the buttons on my app seem to work. These segments of code are ones I downloaded from the internet, and they have been reported to work. I don't know what the issue could be. I am also very new eclipse and android app programming.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:textColor="#FF0000"
android:background="#000000"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FF0000"
android:text="CountDown Timer Demo"
/>
<Button
android:text="Seizure Detected"
android:id="#+id/start"
android:textColor="#FF0000"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button
android:text="Override"
android:id="#+id/stop"
android:textColor="#FF0000"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button
android:text="click me"
android:id="#+id/Button01"
android:textColor="#FF0000"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<TextView
android:id="#+id/tv"
android:textColor="#FF0000"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="sexy"/>
</LinearLayout>
CountDownTest.java >In the src folder
package com.example.epilepsytestapp;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class CountDownTest extends Activity {
Button start, stop;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button)this.findViewById(R.id.start);
stop = (Button)this.findViewById(R.id.stop);
tv = (TextView)this.findViewById(R.id.tv);
tv.setText("10"); // startting from 10.
final MyCounter timer = new MyCounter(10000,1000);
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
timer.start();
}
});
stop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
timer.cancel();
}
});
}
public class MyCounter extends CountDownTimer{
public MyCounter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
System.out.println("Timer Completed.");
tv.setText("Timer Completed.");
}
#Override
public void onTick(long millisUntilFinished) {
tv.setText((millisUntilFinished/1000)+"");
System.out.println("Timer : " + (millisUntilFinished/1000));
}
}
}
Here is Helloworld.java
package com.example.epilepsytestapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) this.findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View v) {
Toast.makeText(HelloWorld.this, "Hello World", Toast.LENGTH_SHORT).show();
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.epilepsytestapp"
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=".CountDownTest"/>
<activity
android:name="com.example.epilepsytestapp.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN"
android:name=".CountDownTest"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
try this.Your hello world code
package com.example.epilepsytestapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(this, "Hello World", Toast.LENGTH_SHORT).show();
}
});
}
}

Categories

Resources