I have few activity files that contains almost same code as shown below. Well i have not included onDestroy and finish() method in all of my activity files, before moving forward i want to be sure of the code posted below.
public class Three extends AppCompatActivity {
Button forwardB,backwardB,homeB;
TextView textView2,textView4,textView5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.one);
//Place advertisement here
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
adView.loadAd(adRequest);
//
//find widget by Id
forwardB = (Button) findViewById(R.id.forwardB);
backwardB = (Button) findViewById(R.id.backwardB);
homeB = (Button) findViewById(R.id.homeB);
textView2= (TextView) findViewById(R.id.textView2);
textView4 = (TextView) findViewById(R.id.textView4);
textView5 = (TextView) findViewById(R.id.textView5);
textView5.setText("3/50");
//set text inside textView3 and textView4
textView2.setText("Apfel");textView4.setText("apple");
//set on click listener for forward,backward and home button
forwardB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Two.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
});
homeB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
});
backwardB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Four.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
After running the application i found a serious issue with data,it looks like android keeps data in background. How can i avoid this?
Everytime i run app and check the data it seems to be increasing.
Well this is my MainActivity.java:
public class MainActivity extends Activity {
Button btnflashcards;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//create widget ids that are usable forw rest of the code
btnflashcards = (Button) findViewById(R.id.btnflashcards);
}
//on flash card button click
public void findFlashCards(View v){
Intent i = new Intent(this, FlashCardSelection.class);
startActivity(i);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
You will need to explicitly clear the application's user data every time you exit the aplication or at any point of time you want to during the use of your app.
Use this: ActivityManager's clearApplicationUserData() method
As per documentation this will:
Permits an application to erase its own data from disk. This is
equivalent to the user choosing to clear the app's data from within
the device settings UI. It erases all dynamic data associated with the
app -- its private data and data in its private area on external
storage -- but does not remove the installed application itself, nor
any OBB files.
Give something like this a shot
import java.io.File;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle *) {
super.onCreate(*);
setContentView(R.layout.main);
}
#Override
protected void onStop(){
super.onStop();
}
//Fires after the OnStop() state
#Override
protected void onDestroy() {
super.onDestroy();
try {
trimCache(this);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
}
Related
Main Activity
i want to check the amount is greater than 100 , after clicking button
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
buyItemButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (amount_checker >= 100){
Intent intent = new Intent(CartActivity.this,AddressActivity.class);
intent.putExtra("itemList", (Serializable) itemsList);
startActivity(intent);
}else {
Toast.makeText(getApplicationContext(), ""+amount_checker, Toast.LENGTH_SHORT).show();
}
}
});
}
i want to get the amount checker value to go to oncreate function
private void calculateAmount() {
amount_checker = 1223.00023223;
}
I want to get the amount checker value to go to onCreate function
Since you need the amount_checker value inside a click listener of a button (and not when the onCreate method is called) you can make amount_checker a field of your CartActivity class.
Then you are just referencing amount_checker as this.amount_checker instead anywhere you need to read or assign the value (maybe in some scopes you might have to access it with CartActivity.this.amount_checker).
class CartActivity {
// this stores the latest amount_checker value
private double amount_checker = 0;
private void calculateAmount() {
this.amount_checker = 1223.00023223;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
buyItemButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (this.amount_checker >= 100){
Intent intent = new Intent(CartActivity.this,AddressActivity.class);
intent.putExtra("itemList", (Serializable) itemsList);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), ""+this.amount_checker, Toast.LENGTH_SHORT).show();
}
}
});
}
where is error? how can I fix it? layout is true error in 24th line that
kaleciKayit.setOnClickListener(new View.OnClickListener() {
here is my all codes
public class oyuncuAdlariActivity extends AppCompatActivity {
Button kaleciKayit;
Button oyuncuKayit;
EditText isimGiris;
String isimGirisString;
int kaleciSayisi = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_oyuncu_adlari);
kaleciKayit = (Button) findViewById(R.id.kaleciButton);
oyuncuKayit = (Button) findViewById(R.id.oyuncuButton);
isimGiris = (EditText) findViewById(R.id.isimGir);
kaleciKayit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
kaleciSayisi++;
isimGirisString = isimGiris.getText().toString();
if (isimGirisString.isEmpty()){
Toast toast1 = Toast.makeText(getApplicationContext(),getApplicationContext().getString(R.string.isimBos), Toast.LENGTH_SHORT);
toast1.show();
}
else if (kaleciSayisi >2)
kaleciKayit.setEnabled(false);
}
});
}
}
First of all, I will recommend setting the objects in a class to private. I think the problem is that maybe you are assigning the id of the wrong widget? check the FindViewByID again.
The other 3 possibilities that I can think about are-
The problem is in the first activity(In this case I ask you to post here the content of the first activity)
The setContentView method points at a wrong XML file.
Your AVD ran out of memory and you need to add more to it in the AVD Manager tool.
Change MainActivity to this,
public class MainActivity extends AppCompatActivity {
Button devamButton;
EditText takim1, takim2;
String takimTextA;
String takimTextB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
devamButton = findViewById(R.id.devamButton);
takim1 = findViewById(R.id.takimB);
takim2 = findViewById(R.id.takimA);
devamButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takimTextA = takim1.getText().toString();
takimTextB = takim2.getText().toString();
if (takimTextA.equals(takimTextB)) {
Toast toast1 = Toast.makeText(getApplicationContext(),getApplicationContext().getString(takimAyniOlmaz), Toast.LENGTH_SHORT);
toast1.show();
} else if (takimTextA.isEmpty() || takimTextB.isEmpty()) {
Toast toast2 = Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.takimBosBirakma), Toast.LENGTH_SHORT);
toast2.show();
} else {
activityGecis1(v);
}
}
});
}
private void activityGecis1(View v) {
Intent gecis1 = new Intent(v.getContext(), oyuncuAdlariActivity.class);
startActivity(gecis1);
}
Since you are calling inside onclicklistener maybe this in intent may point to that functions class.
I asked a question earlier play video in new activity
What I want is when (Button) findViewById(R.id.pickVid); is clicked it calls PICK_VIDEO_REQUEST, then when the video is selected the new activity should open and play the video.
The guy that helped me said that I should use this.mPlayer.setDataSource(mStringFilePath); instead of FileInputStream
PROBLEM:
I am getting a error saying setDataSource failed.: status=0x80000000 with a black screen.
MainActivity
public class MainActivity extends AppCompatActivity {
Uri mMediaUri;
String vidFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button pickVid = (Button) findViewById(R.id.pickVid);
//choose the video
pickVid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chooseVideo = new Intent(Intent.ACTION_GET_CONTENT);
chooseVideo.setType("video/*");
startActivityForResult(chooseVideo, PICK_VIDEO_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_VIDEO_REQUEST) {
if (resultCode == RESULT_OK) {
mMediaUri = data.getData();
vidFile = mMediaUri.toString();
Intent playVid = new Intent(MainActivity.this, PlayVideoAct.class);
playVid.putExtra("vidFile", vidFile);
startActivity(playVid);
}
}
}
PlayVideoAct
String mStringFilePath;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playvideo);
mStringFilePath = getIntent().getStringExtra("vidFile");
}
public void surfaceCreated(SurfaceHolder holder) {
if (this.mPlayer == null) {
this.mPlayer = new MediaPlayer();
} else {
this.mPlayer.reset();
mPlayer.start();
}
try {
this.mMediaPlayer.setDataSource(mStringFilePath);
this.mPlayer.setDisplay(this.mSurfaceHolder);
this.mPlayer.prepare();
this.mPlayer.start();
this.mPlayer.pause();
Play();
} catch (Exception e) {
LogUtil.e(e, "Error in PlayVideoAct.surfaceCreate(SurfaceHolder)");
}
}
private void Play() {
mMediaPlayer.start();
if (this.mMediaPlayer.isPlaying()) {
this.mMediaPlayer.pause();
return;
}
if (this.isStop) {
this.mMediaPlayer.seekTo(this.leftPosition);
}
this.mImageViewButtonControls.setImageResource(R.drawable.pause);
}
Check video path, if it's correct then check if you have all necessary permissions like:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
If yes, then depending on your Android version you may need to go to Settings -> Apps -> Your application -> Permissions and toggle those permissions manually.
I want to add a button in my application that turns off the music but I don't know how to approach it, I have an idea but I'm sure it's far from best so I want to consult with you. The situation is as follows:
public class MainActivity extends Activity implements OnClickListener {
MediaPlayer easysong;
MediaPlayer normalsong;
MediaPlayer hardsong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.land_main);
mContext = this;
restartButton = (Button)findViewById(R.id.restartButton);
restartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
easysong = MediaPlayer.create(MainActivity.this, R.raw.arideniro);
normalsong = MediaPlayer.create(MainActivity.this, R.raw.junior);
hardsong = MediaPlayer.create(MainActivity.this, R.raw.ketsathis);
counter = 101;
i = 500 - dif;
new Thread(new Runnable() {
public void run() {
if(i==500){
easysong.start();}
else if(i==375){
normalsong.start();
}else if(i==250){
hardsong.start();
}
while (counter > 0) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter--;
runOnUiThread(new Runnable() {
#Override
public void run() {
scoreText.setText(Integer.toString(counter));
}
});
if(i>150){
i/=1.01;}
else if(i>90-(dif/10)){
i-=1;
}
}if (counter==0) {
mChronometer.stop();
if(easysong.isPlaying()) {
easysong.stop();
easysong.release();
easysong = null;
}else if(normalsong.isPlaying()){
normalsong.stop();
normalsong.release();
normalsong = null;
}else if(hardsong.isPlaying()){
hardsong.stop();
hardsong.release();
hardsong = null;
}
This is the main class of my app where the mediaplayer is used, now I deleted much of the code because it was irrelevant to the mediaplayer and the question, so don't look for the missing brackets and such. And this here is the main menu class where the Switch that will turn on and off the music will be located:
public class MainMenu extends Activity{
private Button easy;
private Button normal;
private Button hard;
private Button scores;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
easy = (Button) findViewById(R.id.btn_easy);
scores = (Button) findViewById(R.id.btn_highscores);
easy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dif = 0;
startGame();
}
});
}
public void startGame() {
Intent intent = new Intent(MainMenu.this, MainActivity.class);
startActivity(intent);
}
So my idea is simnple, to add a variable in MainActivity like "int p;" and from the MainMenu class to change it's state between 0 and 1, then I will add around each line that starts music an if(p==1) but is this a good approach ? Also I would like the value of the int to be saved when the app is closed
I am trying to create a messaging app with several different xml views/classes:
one for the main menu (MainActivity);
one for the sending message screen (SendMsg);
one for storing sent messages (Logs).
In SendMsg, I want to store my message into an object called msgLog, which I had created in MainActivity. Just for testing, I have set SendMsg to display the Logs class upon pressing the SEND button, and the sent message does indeed appear there.
However, it is not storing it into the msgLog variable that I created, so that I can't access again from MainActivity.
How do I store it into a variable, so that it will always be there when I access it? Any help would be much appreciated.
=========================================================
public class MainActivity extends AppCompatActivity {
Logs msgLog = new Logs();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendOnClick (View view){
Intent intent = new Intent("com.example.android.attone.SendMsg");
startActivity(intent);
}
public void logsOnClick (View view){
Intent intent = new Intent(this, Logs.class);
startActivity(intent);
}
}
=========================================================
public class SendMsg extends AppCompatActivity {
EditText txtPhoneNo;
EditText txtMessage;
Button btnSend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_msg);
txtPhoneNo = (EditText) this.findViewById(R.id.txtPhoneNo);
txtMessage = (EditText) this.findViewById(R.id.txtMessage);
btnSend = (Button) this.findViewById(R.id.btnSend);
btnSend.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// Get phone number and message sms
String phoneNo = txtPhoneNo.getText().toString();
String message = txtMessage.getText().toString();
Intent writeLog = new Intent(getApplicationContext(), Logs.class);
writeLog.putExtra("link", message);
startActivity(writeLog);
// If phone number and message is not empty
if (phoneNo.length() > 0 && message.length() > 0)
{
sendMessage(phoneNo, message);
}
else
{
Toast.makeText(getBaseContext(), "Please enter both number and message", Toast.LENGTH_LONG).show();
}
}
});
}
// Function send message sms
private void sendMessage(String phoneNo, String message)
{
try
{
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent", Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "SMS failed. Please try again!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
=========================================================
public class Logs extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logs);
String logging = getIntent().getStringExtra("link");
TextView textView = (TextView) findViewById(R.id.txtLog);
textView.setText(logging);
Button log2menu = (Button)findViewById(R.id.logToMenu);
log2menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
}
}
You can use SharedPreferences to store such data.
One more thing you can try if you don't want to save the data after the app closes is storing the data in a static variable of a separate class.