Android Studio app crashes - java

I have a problem with my application I am making on Android Studio. I don't know why, but after the splash screen, the application crashes. I want the activity "Accueil" to open after the splash screen. It worked fine last week and now it doesn't anymore. I didn't touch anything. I show you the manifest, and the .java files.
Splashscreen.java:
import android.app.Activity;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class Splashscreen extends Activity {
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
Thread splashTread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen);
StartAnimations();
Thread loading = new Thread() {
public void run() {
try {
sleep(5000);
Intent main = new Intent(Splashscreen.this,Menu.class);
startActivity(main);
finish();
} catch (Exception e) {
e.printStackTrace();
} finally {
finish();
}
}
};
loading.start();
}
private void StartAnimations() {
Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
anim.reset();
LinearLayout l = (LinearLayout) findViewById(R.id.lin_lay);
l.clearAnimation();
l.startAnimation(anim);
anim = AnimationUtils.loadAnimation(this, R.anim.rotate);
anim.reset();
ImageView iv = (ImageView) findViewById(R.id.splash);
iv.clearAnimation();
iv.startAnimation(anim);
splashTread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
while (waited < 3500) {
sleep(100);
waited += 100;
}
Intent intent = new Intent(Splashscreen.this,Menu.class);
startActivity(intent);
finish();
} catch (InterruptedException e) {
}
}
};
}
}
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.thibaudmangeot.erdfapplicationsecurite">
<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=".Accueil"
android:label="#string/title_activity_accueil"/>
</application>
</manifest>
Accueil.java:
package com.example.thibaudmangeot.erdfapplicationsecurite;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.Button;
import android.view.View;
public class Accueil extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accueil);
Button buttonfis = (Button) findViewById(R.id.buttonfis);
buttonfis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goTosignin();
}
});
}
private void goTosignin() {
Intent intent = new Intent(this, Menu.class);
startActivity(intent);
}
}

Do this
Intent main = new Intent(Splashscreen.this, Accueil.class);
startActivity(main);
finish();
Instead of
Intent main = new Intent(Splashscreen.this, Menu.class);
startActivity(main);
finish();
You have not even mentioned Menu activity in your manifest.

This is your error:
Intent main = new Intent(Splashscreen.this,Menu.class);
it should be:
Intent main = new Intent(Splashscreen.this, Accueil.class);

I think your application is crashing maybe because of two reasons
There is no Activity named "Menu"
Menu Activity is not mentioned in manifest file
If you want to open "Accueil" activity then write your intent in following fashion.
Intent openAccueil = new Intent(Splashscreen.this,Menu.class);
startActivity(openAccueil);

Related

NFC Tag Reading Activity not receiving intent

I have an activity to read NFC Type A tags (non-NDEF). I am running Android Studio with Android phone in developer mode.
The project launches the application correctly on the developer Android phone with NFC switched on on the phone. When I tap my NFC contactless card on the phone, the phone detects the NFC card but shows an options list of other NFC reader application installed on the phone instead of passing the intent to the foreground application.
How do I get the foreground project's application to receive the NFC intent instead of having a suggestions list popout ?
Here's my AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="testtag">
<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=".TapTagActivity">
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED" />
</intent-filter>
<meta-data
android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="#xml/nfc_tech_filter" />
</activity>
<activity android:name=".ManageTagActivity"></activity>
<activity android:name=".EnquireTagActivity"></activity>
<activity android:name=".SelectTagActionActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".TestActivity" />
</application>
<uses-permission android:name="android.permission.NFC" />
<uses-sdk android:minSdkVersion="10" />
<uses-feature
android:name="android.hardware.nfc"
android:required="true" />
</manifest>
Here's the Activity Java class:
package testtag;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
public class TapTagActivity extends AppCompatActivity {
private static Class targetActivity = null;
private NfcAdapter nfcAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tap_tag);
System.out.println("Tap Tag window ready ...");
NfcManager nfcManager = (NfcManager) getSystemService(Context.NFC_SERVICE);
// nfcAdapter = nfcManager.getDefaultAdapter();
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcManager != null) {
System.out.println("NFC Manager ready ...");
}
if (nfcAdapter != null) {
System.out.println("NFC Adapter ready ...");
}
}
#Override
protected void onResume() {
super.onResume();
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent nfcPendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
if (nfcAdapter != null) {
nfcAdapter.enableForegroundDispatch(this, nfcPendingIntent, null, null);
}
}
#Override
protected void onPause() {
super.onPause();
if (nfcAdapter != null) {
try {
nfcAdapter.disableForegroundDispatch(this);
} catch (IllegalStateException ex) {
Log.e("ATHTAG","Error disabling NFC foreground dispatch", ex);
}
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
System.out.println("Doing onNewIntent() ...");
// Use NFC to read tag
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (tag != null) {
System.out.println("New tag found !!!");
} else {
System.out.println("No new tag found !!!");
}
}
public static void setTargetRedirectIntent(Class activity) {
targetActivity = activity;
}
}
The console manages to print the:
I/System.out: Tap Tag window ready ...
I/System.out: NFC Manager ready ...
NFC Adapter ready ...
How do I read the NFC card from the foreground without having the suggestions list with installed NFC reader apps appear ?
I figured out that I have to set enableForegroundDispatch() parameters in the onResume() instead of leaving null values.
Working code:
package testtag;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.os.Bundle;
import android.util.Log;
public class TapTagActivity extends AppCompatActivity {
private static Class targetActivity = null;
private NfcAdapter nfcAdapter = null;
private IntentFilter[] intentFiltersArray = null;
private String[][] techListsArray = null;
private PendingIntent pendingIntent = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tap_tag);
System.out.println("Tap Tag window ready ...");
NfcManager nfcManager = (NfcManager) getSystemService(Context.NFC_SERVICE);
// nfcAdapter = nfcManager.getDefaultAdapter();
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcManager != null) {
System.out.println("NFC Manager ready ...");
}
if (nfcAdapter != null) {
System.out.println("NFC Adapter ready ...");
}
pendingIntent = PendingIntent.getActivity(
this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
intentFiltersArray = new IntentFilter[]{new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)};
techListsArray = new String[][]{new String[]{NfcA.class.getName()}, new String[]{NfcB.class.getName()}, new String[]{IsoDep.class.getName()}};
}
#Override
protected void onResume() {
super.onResume();
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent nfcPendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
if (nfcAdapter != null) {
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);
}
}
#Override
protected void onPause() {
super.onPause();
if (nfcAdapter != null) {
try {
nfcAdapter.disableForegroundDispatch(this);
} catch (IllegalStateException ex) {
Log.e("ATHTAG", "Error disabling NFC foreground dispatch", ex);
}
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
System.out.println("Doing onNewIntent() ...");
// Use NFC to read tag
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
if (tag != null) {
System.out.println("New tag found !!!");
} else {
System.out.println("No new tag found !!!");
}
}
public static void setTargetRedirectIntent(Class activity) {
targetActivity = activity;
}
}

Android Studio App crashes when i press the submit button to go to a 2nd activity

Firstly, I am pretty new to Android programming and I am trying to develop a simple app that shows a message, and when you press the button that's under the message, it sends you to a 2nd activity, which is a form. The app isn't linked to any database, I was just trying to develop a validation algorithm within the app, so the data that's written in the EditText's it's correct. Like the Name only with letters, etc. I created both activities, it worked to jump from the 1st one to the 2nd one after pressing the button, but that was before I added the validation algorithm. Now, with that implemented, whenever I press on the "Start!" button(1st activity-submit one), the apps just crashes.
The manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.myapplication">
<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"
tools:ignore="GoogleAppIndexingWarning">
<activity
android:name=".Inregistrare"
android:exported="true"
android:theme="#style/AppTheme1" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The 1st app MainActivity.java:
package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button submitButton = findViewById(R.id.submitButton);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Inregistrare();
}
});
}
public void Inregistrare(){
Intent intent = new Intent(this,Inregistrare.class);
startActivity(intent);
}
}
The 2nd activity Inregistrare.java:
package com.example.myapplication;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class Inregistrare extends AppCompatActivity {
EditText nume, prenume, email, telefon;
TextView rezultat;
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inregistrare);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{ final String Nume = nume.getText().toString();
final String Prenume=prenume.getText().toString();
final String Email=email.getText().toString();
final String Telefon=telefon.getText().toString();
if(Nume.length()==0)
{
nume.requestFocus();
nume.setError("Campul nu poate fi lasat liber");
}
else if(!Nume.matches("[a-zA-Z ]+"))
{
nume.requestFocus();
nume.setError("Campul poate fi completat doar cu litere");
}
else if(Prenume.length()==0)
{
prenume.requestFocus();
prenume.setError("Campul nu poate fi lasat liber");
}
else if(!Prenume.matches("[a-zA-Z ]+")) {
prenume.requestFocus();
prenume.setError("Campul poate fi completat doar cu litere");
}
else if(Email.length()==0)
{
email.requestFocus();
email.setError("Campul nu poate fi lasat liber");
}
else if(!Email.matches("^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,6}$"))
{
email.requestFocus();
email.setError("Campul poate fi completat doar cu litere");
}
else if(Telefon.length()==0 || Telefon.length()<10)
{
telefon.requestFocus();
telefon.setError("Campul nu poate fi lasat liber si trebuie sa aiba minim 10 cifre");
}
else if(!Telefon.matches("[0-9]+"))
{
telefon.requestFocus();
telefon.setError("Campul poate fi completat doar cu cifre");
}
else{
rezultat = findViewById(R.id.rezultat);
String date="Date corecte!";
rezultat.setText(date);
}
}
})
;}
}
I tried using another activity to check the switch and it works. The problem is somewhere in inregistrare.java (2nd activity) but i cant seem to find it. I didnt add the .xml's because i dont this that there's any problem. As i said i am pretty new to this, so please be kind and dont yell at me if i did a big mistake.
Thanks in advance!

avoid of send null from destroyed activity to restarted service

I want to programing app for data track in background , so I use service .
I want to write a program that monitors all data sent and received by the device, and when the total volume of received or received messages reaches a specified value, the Internet device is turned off.
So I used the following code to monitor the data:
 
mStartRX = TrafficStats.getTotalRxBytes ();
mStartTX = TrafficStats.getTotalTxBytes ();
And I used the services to work on the background in the background.
To specify the download or upload limit from the user with edittext, I requested this limit in mainactivity and send this value to the service.
The problem is when: When I destroy the program, I will restart the service and get the NULL value and the program crashes.
My application code:
Main Activity :
package ir.alexandre9009.service;
import android.app.AlertDialog;
import android.content.Context;
import android.net.TrafficStats;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public static Handler mHandler = new Handler();
public static long UPP;
public static long DLL;
Button startService,stopService;
public Context context=this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (FirstService.mStartRX == TrafficStats.UNSUPPORTED || FirstService.mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}
startService=(Button)findViewById(R.id.startService);
stopService=(Button)findViewById(R.id.stopService);
startService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText UP = (EditText) findViewById(R.id.UP);
String UPPP = UP.getText().toString();
UPP=Long.parseLong(UPPP);
EditText DL = (EditText) findViewById(R.id.DL);
String DLLL = DL.getText().toString();
DLL=Long.parseLong(DLLL);
Intent intent = new Intent(getApplicationContext(), FirstService.class);
String myString = DLLL;
intent.putExtra("StringName", myString);
startService(intent);
}
});
stopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(),FirstService.class));
}
});
}
public final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
RX.setText(Long.toString(FirstService.rxBytes));
TX.setText(Long.toString(FirstService.txBytes));
mHandler.postDelayed(mRunnable, 1000);
}
};
}
Service :
package ir.alexandre9009.service;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.TrafficStats;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.IBinder;
import android.widget.TextView;
import android.widget.Toast;
public class FirstService extends Service{
public static long mStartRX ;
public static long mStartTX ;
public static long rxBytes ;
public static long txBytes ;
public long dl=MainActivity.DLL;
Context context=this;
private final Runnable mRunnable = new Runnable() {
public void run() {
rxBytes = (TrafficStats.getTotalRxBytes()- mStartRX)/1048576;
txBytes = (TrafficStats.getTotalTxBytes()- mStartTX)/1048576;
if (rxBytes==2) {
stopService(new Intent(getBaseContext(),FirstService.class));
Intent i = new Intent(context,MainActivity.class);
context.startActivity(i);
// WifiManager wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
// wifiManager.setWifiEnabled(false);
//معرفی توست برای نمایش یک پیام کوتاه به کاربر در هنگام خاموش کردن وای فای
Toast.makeText(FirstService.this, "هشدار", Toast.LENGTH_LONG).show();
}
mHandler.postDelayed(mRunnable, 1000);
}
};
private Handler mHandler = new Handler();
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this,"staart",Toast.LENGTH_LONG).show();
mStartTX=0;
mStartRX=0;
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
mHandler.postDelayed(mRunnable, 1000);
return Service.START_STICKY;
}
#Override
public void onDestroy() {
TrafficStats.clearThreadStatsTag();
Toast.makeText(this,"FirstService Stoped",Toast.LENGTH_LONG).show();
mStartTX=0;
mStartRX=0;
super.onDestroy();
}
}
AndroidManifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ir.alexandre9009.service">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<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>
<service android:name=".FirstService"
>
</service>
</application>
</manifest>
please help me ...
The problem is with this line
public long dl=MainActivity.DLL;
You're referring to a variable in the Activity, surly when the Activity is destroyed, this variable is no longer in scope, thus you get Null Exception.
You must get this value using the intent.
The other problem is that you can't prevent any service from being killed by the system except foreground services which need to show a notification to the user. But this is not suitable for your situation.
Therefore, the best approach for you is to check whether intent is null or not. If it is not null, you get the value and save it into Preferences or Database or somewhere, if it is null, you retrieve the value from where you stored it before.

My android app stops responding after the Splash Screen

I'm programming a new app which contains a splash screen.
I've finished it and it was all good. After I've opened android studio again to work on the navigation bar I've tried to run the app to see the result but the application stopped and crashed after the display of the splash screen.
this is Main class
package com.example.computer.bsinfoshop;
public class Main extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
and this is the class od splash screen
package com.example.computer.bsinfoshop;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Screen extends AppCompatActivity {
TextView tv;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen);
tv = (TextView)findViewById(R.id.textView);
img = (ImageView)findViewById(R.id.imageView);
Typeface font = Typeface.createFromAsset(getAssets(),"fonts/Satisfy-Regular.ttf");
tv.setTypeface(font);
img.setImageResource(R.drawable.rsz_2rsz_img);
Thread timerThread = new Thread(){
public void run(){
try
{
sleep(3700);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
finally {
Intent intent = new Intent(Screen.this , Main.class);
startActivity(intent);
}
}
};
timerThread.start();
}
#Override
protected void onPause() {
super.onPause();
finish();
}
}
and here where i think is the problem
the manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.computer.bsinfoshop">
<application
android:allowBackup="true"
android:icon="#drawable/logo"
android:label="#string/app_name">
<activity
android:name=".Screen"
android:theme="#style/App">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Information"
android:label="Information"
android:theme="#style/AppTheme">
</activity>
<activity
android:name="com.example.computer.bsinfoshop.Main"
android:theme="#style/AppTheme">
</activity>
</application>
</manifest>
I just want to know what is the problem in my code and how can I fix it. thank you ^^
Change Thread to something like this:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
finish();
startActivity(new Intent(Screen.this, Main.class));
}
}, 1500);
To be honest, I think this is not the correct way of creating a Splash Screen. That way you force the user to wait for 3 seconds which causes a bad user-experience.
Have a look at that tutorial and your users will thank you! https://www.bignerdranch.com/blog/splash-screens-the-right-way/

Android Could execute method of the activity

I'm building a simple paint app and encountering this error given by the logcat:
I'm using the following code:
This SaveDrawing.java serves as the main activity
package com.example.SaveDrawing;
import com.example.SaveDrawing.drawings.DrawingActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class SaveDrawing extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View view){
switch (view.getId()){
case R.id.drawBtn:
//Intent drawIntent = new Intent(this, DrawingActivity.class);
//startActivity( drawIntent);
//Toast.makeText(getBaseContext(), "This is the Toast message", Toast.LENGTH_SHORT).show();
Intent nextActivity = new Intent(SaveDrawing.this, DrawingActivity.class);
startActivity(nextActivity);
break;
}
}
}
Then the next activity after clicking the button is DrawingActivity.java
package com.example.SaveDrawing.drawings;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.io.FileOutputStream;
import com.example.SaveDrawing.R;
import com.example.SaveDrawing.R.id;
import com.example.SaveDrawing.R.layout;
public class DrawingActivity extends Activity implements View.OnTouchListener{
private DrawingSurface drawingSurface;
private DrawingPath currentDrawingPath;
private Paint currentPaint;
private Button redoBtn;
private Button undoBtn;
private static File APP_FILE_PATH = new File("/sdcard/TutorialForAndroidDrawings");
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawing_activity);
setCurrentPaint();
drawingSurface = (DrawingSurface) findViewById(R.id.drawingSurface);
drawingSurface.setOnTouchListener(this);
redoBtn = (Button) findViewById(R.id.redoBtn);
undoBtn = (Button) findViewById(R.id.undoBtn);
redoBtn.setEnabled(false);
undoBtn.setEnabled(false);
}
private void setCurrentPaint(){
currentPaint = new Paint();
currentPaint.setDither(true);
currentPaint.setColor(0xFFFFFF00);
currentPaint.setStyle(Paint.Style.STROKE);
currentPaint.setStrokeJoin(Paint.Join.ROUND);
currentPaint.setStrokeCap(Paint.Cap.ROUND);
currentPaint.setStrokeWidth(3);
}
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
currentDrawingPath = new DrawingPath();
currentDrawingPath.paint = currentPaint;
currentDrawingPath.path = new Path();
currentDrawingPath.path.moveTo(motionEvent.getX(), motionEvent.getY());
currentDrawingPath.path.lineTo(motionEvent.getX(), motionEvent.getY());
}else if(motionEvent.getAction() == MotionEvent.ACTION_MOVE){
currentDrawingPath.path.lineTo(motionEvent.getX(), motionEvent.getY());
}else if(motionEvent.getAction() == MotionEvent.ACTION_UP){
currentDrawingPath.path.lineTo(motionEvent.getX(), motionEvent.getY());
drawingSurface.addDrawingPath(currentDrawingPath);
undoBtn.setEnabled(true);
redoBtn.setEnabled(false);
}
return true;
}
public void onClick(View view){
switch (view.getId()){
case R.id.colorRedBtn:
currentPaint = new Paint();
currentPaint.setDither(true);
currentPaint.setColor(0xFFFF0000);
currentPaint.setStyle(Paint.Style.STROKE);
currentPaint.setStrokeJoin(Paint.Join.ROUND);
currentPaint.setStrokeCap(Paint.Cap.ROUND);
currentPaint.setStrokeWidth(3);
break;
case R.id.colorBlueBtn:
currentPaint = new Paint();
currentPaint.setDither(true);
currentPaint.setColor(0xFF00FF00);
currentPaint.setStyle(Paint.Style.STROKE);
currentPaint.setStrokeJoin(Paint.Join.ROUND);
currentPaint.setStrokeCap(Paint.Cap.ROUND);
currentPaint.setStrokeWidth(3);
break;
case R.id.colorGreenBtn:
currentPaint = new Paint();
currentPaint.setDither(true);
currentPaint.setColor(0xFF0000FF);
currentPaint.setStyle(Paint.Style.STROKE);
currentPaint.setStrokeJoin(Paint.Join.ROUND);
currentPaint.setStrokeCap(Paint.Cap.ROUND);
currentPaint.setStrokeWidth(3);
break;
case R.id.undoBtn:
drawingSurface.undo();
if( drawingSurface.hasMoreUndo() == false ){
undoBtn.setEnabled( false );
}
redoBtn.setEnabled( true );
break;
case R.id.redoBtn:
drawingSurface.redo();
if( drawingSurface.hasMoreRedo() == false ){
redoBtn.setEnabled( false );
}
undoBtn.setEnabled( true );
break;
case R.id.saveBtn:
final Activity currentActivity = this;
Handler saveHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
final AlertDialog alertDialog = new AlertDialog.Builder(currentActivity).create();
alertDialog.setTitle("Saved 1");
alertDialog.setMessage("Your drawing had been saved :)");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
} ;
new ExportBitmapToFile(this,saveHandler, drawingSurface.getBitmap()).execute();
break;
}
}
private class ExportBitmapToFile extends AsyncTask<Intent,Void,Boolean> {
private Context mContext;
private Handler mHandler;
private Bitmap nBitmap;
public ExportBitmapToFile(Context context,Handler handler,Bitmap bitmap) {
mContext = context;
nBitmap = bitmap;
mHandler = handler;
}
#Override
protected Boolean doInBackground(Intent... arg0) {
try {
if (!APP_FILE_PATH.exists()) {
APP_FILE_PATH.mkdirs();
}
final FileOutputStream out = new FileOutputStream(new File(APP_FILE_PATH + "/myAwesomeDrawing.png"));
nBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
return true;
}catch (Exception e) {
e.printStackTrace();
}
//mHandler.post(completeRunnable);
return false;
}
#Override
protected void onPostExecute(Boolean bool) {
super.onPostExecute(bool);
if ( bool ){
mHandler.sendEmptyMessage(1);
}
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.SaveDrawing"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-sdk android:minSdkVersion="8" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".SaveDrawing"
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=".DrawingActivity" android:screenOrientation="landscape" ></activity>
<activity android:name=".drawings.DrawingActivity"/>
</application>
</manifest>
I have the following in my explorer. I'm not so sure if I got a wrong file structure.
Anyone can help me? I'm kinda new to java and android programming. Many thanks!!! :)
remove <activity android:name=".DrawingActivity" android:screenOrientation="landscape" ></activity> from your manifest as there is no such activity. there is only DrawingActivity in your project structure. Then clean build Run.
Also another possible problem could having an Activity Class name SaveDrawing in the package. You should try to rename the package, update relevant changes to the manifest and try running the app again..
You probably forgot to declare DrawingActivity in your manifest.xml
This is because you attempt to launch com.example.SaveDrawing.drawings/com.example.SaveDrawing.drawings.DrawingActivity,
but actual activity you launch in code is com.example.SaveDrawing/com.example.SaveDrawing.drawings.DrawingActivity
Please change
Intent nextActivity = new Intent(SaveDrawing.this, DrawingActivity.class);
to
Intent nextActivity = new Intent();
nextActivity.setClassName ("com.example.SaveDrawing.drawings", "com.example.SaveDrawing.drawings.DrawingActivity");
It might work.

Categories