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

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

Related

getApplicationContext() method getting error

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.

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

Run android App Error (FATAL EXCEPTION: main Process: PID: 14099)

I have below code and have below Error when run App PLZ Help me
Main Activity
package com.comp.easybuy.easybuy;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import static android.net.Uri.parse;
public class MainActivity extends Activity {
private ImageButton callusphone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
callusphone=(ImageButton)findViewById(R.id.callus);
callusphone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL, parse("tel:+962796880853"));
startActivity(callIntent);
}
});
}
public void flick(View view){
Intent bowsprit =new Intent(Intent.ACTION_VIEW, parse("http://www.facebook.com/ebuy2015/"));
startActivity(bowsprit);
}
public void incline(View view){
Intent browbeaten =new Intent(Intent.ACTION_VIEW, parse("http://www.instagram.com/easy_buy_1/"));
startActivity(browbeaten);
}
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] {
R.drawable.offer4,
R.drawable.offer5,
R.drawable.offer6,
};
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = MainActivity.this;
ImageView imageView = new ImageView(context);
int padding =context.getResources().
getDimensionPixelSize(R.dimen.abc_switch_padding);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(mImages[position]);
container.addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((ImageView) object);
}
}
#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);
}
}
Splash screen
package com.comp.easybuy.easybuy;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class Splash 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(Splash.this,MainActivity.class);
startActivity(intent);
}
}
};
timerThread.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.comp.easybuy.easybuy">
<uses-permission android:name="ANDROID.PERMISSION.CALL_PHONE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Splash"
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"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
main Activity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
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">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageButton"
android:onClick="flick"
android:src="#drawable/fbook"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="false"
android:scaleType="center"
android:contentDescription="facebook Image Button"
android:layout_alignParentStart="false"
android:theme="#style/Widget.AppCompat.RatingBar"
android:visibility="visible" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/insta"
android:onClick="incline"
android:src="#drawable/inst"
android:layout_alignParentBottom="true"
android:layout_alignTop="#+id/imageButton"
android:layout_alignParentEnd="false"
android:layout_alignParentStart="false"
android:scaleType="center"
android:theme="#style/Widget.AppCompat.RatingBar"
android:visibility="visible" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/callus"
android:onClick="callusphone"
android:src="#drawable/callus"
android:layout_alignParentBottom="false"
android:layout_centerHorizontal="true"
android:layout_marginLeft="145dp"
android:layout_marginRight="145dp"
android:layout_below="#+id/view_pager"
android:layout_alignParentEnd="false"
android:layout_alignParentStart="false"
android:scaleType="center"
android:theme="#style/Widget.AppCompat.RatingBar"
android:visibility="visible" />
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignWithParentIfMissing="false"
android:layout_gravity="right|left"
android:visibility="visible"
android:background="#ffffff"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_above="#+id/imageButton" />
</RelativeLayout>
and have Error
08-19 09:30:36.123 14099-14099/com.comp.easybuy.easybuy E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.comp.easybuy.easybuy, PID: 14099
java.lang.IllegalArgumentException: Expected receiver of type com.comp.easybuy.easybuy.MainActivity, but got android.view.ContextThemeWrapper
at java.lang.reflect.Method.invoke(Native Method)
at android.view.View$DeclaredOnClickListener.onClick(View.java:4448)
at android.view.View.performClick(View.java:5199)
at android.view.View$PerformClick.run(View.java:21155)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5415)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:725)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:615)
First declare Your Image Buttons as below
imageFb=(ImageButton)findViewById(R.id.imageButton);
imageInsta=(ImageButton)findViewById(R.id.insta);
and use OnClickListener
imageFb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flick(v);
}
});
imageInsta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
incline(v);
}
});
check now it should work!! You have defined your onClick in xml but havent used it and passed the view to method so it was crashing your code!
final MainActivity should look like this!
package com.comp.easybuy.easybuy;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import static android.net.Uri.parse;
public class MainActivity extends Activity {
private ImageButton callusphone;
private ImageButton imageFb;
private ImageButton imageInsta;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
callusphone=(ImageButton)findViewById(R.id.callus);
imageFb=(ImageButton)findViewById(R.id.imageButton);
imageInsta=(ImageButton)findViewById(R.id.insta);
callusphone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL, parse("tel:+962796880853"));
startActivity(callIntent);
}
});
imageFb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flick(v);
}
});
imageInsta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
incline(v);
}
});
}
public void flick(View view){
Intent bowsprit =new Intent(Intent.ACTION_VIEW, parse("http://www.facebook.com/ebuy2015/"));
startActivity(bowsprit);
}
public void incline(View view){
Intent browbeaten =new Intent(Intent.ACTION_VIEW, parse("http://www.instagram.com/easy_buy_1/"));
startActivity(browbeaten);
}
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] {
R.drawable.offer4,
R.drawable.offer5,
R.drawable.offer6,
};
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = MainActivity.this;
ImageView imageView = new ImageView(context);
int padding =context.getResources().
getDimensionPixelSize(R.dimen.abc_switch_padding);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(mImages[position]);
container.addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((ImageView) object);
}
}
#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);
}
}

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
}

Android Emulator crash "Unfortunately _app name_ has stopped"

I have seen a few answers to questions on this topic but I see that those answers change depending on the coding of the app.
I am new to android apps and the tutorial Im following uses one button to increment and another one to reduce a counter. I get this "Unfortunately AddSubb has stoped" error on my emulator.
MainActivity.java
package com.example.addingsubstracting;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
int counter;
Button add, sub;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
add = (Button) findViewById(R.id.bAdd);
sub = (Button) findViewById(R.id.bSub);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Your total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText("Your total is " + counter);
}
});
}
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
fragment_main.xml
<LinearLayout 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:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Yout total is 0"
android:textSize="20dp"
android:id="#+id/tvDisplay" />
<Button
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="Add one"
android:layout_gravity="center"
android:textSize="30dp"
android:id="#+id/bAdd" />
<Button
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="Substract one"
android:layout_gravity="center"
android:textSize="30dp"
android:id="#+id/bSub" />
</LinearLayout>
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.addingsubstracting"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.addingsubstracting.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>
This is because findViewById() searches in the activity_main layout, while the button is located in the fragment's layout fragment_main.
Move that piece of code in the onCreateView() method of the fragment:
eg:
//...
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button add = (Button)rootView.findViewById(R.id.R.id.bAdd);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Your total is " + counter);
}
});
Notice that now you access it through rootView view:
eg:
Button buttonClick = (Button)rootView.findViewById(R.id.button);
otherwise you would get again NullPointerException.

Categories

Resources