I have added a toggleButton, but it is not showing up and I cannot figure out why. I have completed the Android tutorial, and have looked back at the code, as well as many other sources. The objective is to have the program pause when the button is ON. At the moment, the button will not even show up on the user interface. Any suggestions?
<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=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:onClick="pauseCounter" />
</RelativeLayout>
package com.evorlor.counter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent counter = new Intent(MainActivity.this, Counter.class);
startActivity(counter);
}
public void pauseCounter(View view) {
Intent pause = new Intent(this, Pause.class);
startActivity(pause);
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.activity_main, menu);
// return true;
// }
}
package com.evorlor.counter;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Pause extends Activity{
public void onCreate(Bundle instPause) {
super.onCreate(instPause);
TextView tv = new TextView(this);
tv.setTextSize(250);
tv.setText("PAUSE");
setContentView(tv);
}
}
Here is my Counter class. It is messy. Sorry. This is as close as I have come so far. Help would be very appreciated! I have spent a lot of time on this measly button! Thanks!
package com.evorlor.counter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.widget.TextView;
import android.widget.ToggleButton;
public class Counter extends Activity {
private int count = 0;
private int hiCount = 0;
private boolean capCount = false;
public void onCreate(Bundle instCounter) {
super.onCreate(instCounter);
TextView tv = new TextView(this);
tv.setTextSize(250);
if (count < 10000 && capCount == false) {
tv.setText(Integer.toString(count));
} else {
capCount = true;
if (count >= 10000) {
hiCount += 10;
count -= 10000;
}
if (hiCount < 100) {
tv.setText(hiCount + "k+" + count);
} else {
tv.setText("Over\n100k");
}
}
tv.setGravity(Gravity.CENTER);
setContentView(tv);
ToggleButton butPause = new ToggleButton(this);
if (butPause == null) {
Intent pause = new Intent(this, Pause.class);
startActivity(pause);
}
}
// public void pauseCounter(View view) {
// Intent pause = new Intent(this, Pause.class);
// startActivity(pause);
// }
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent counter = new Intent(MainActivity.this, Counter.class);
startActivity(counter);
}
You are starting a new activity right away. thats not a good idea.
You are going to see what is in your Counter activity, not what is in your main activity, reason you don't see your toggle button. Comment out startActivity() just to check.
Related
I have a button in Activity A, which changes the text in it when clicked. There is an Activity B in which I need the TextView to become visible and its text to be the same as the text in the button on the Activity A. Please help.
Activity A
package com.example.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.annotation.Nullable;
public class SmActivity extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sm);
Button btn_apple = (Button) findViewById(R.id.button_apple);
Button btn_cherry = (Button) findViewById(R.id.button_cherry);
Button btn_orange = (Button) findViewById(R.id.button_orange);
Button btn_waterLemon = (Button) findViewById(R.id.button_waterlemon);
View.OnClickListener appleListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_apple.setText("1");
}
else {
int i = Integer.parseInt(btn_apple.getText().toString());
btn_apple.setText(String.valueOf(i + 1));
i = i;
}
}
};
View.OnClickListener cherryListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_cherry.setText("1");
}
else {
int j = Integer.parseInt(btn_cherry.getText().toString());
btn_cherry.setText(String.valueOf(j + 1));
j = j;
}
}
};
View.OnClickListener orangeListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_orange.setText("1");
}
else {
int k = Integer.parseInt(btn_orange.getText().toString());
btn_orange.setText(String.valueOf(k + 1));
k = k;
}
}
};
View.OnClickListener waterListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_waterLemon.setText("1");
} else {
int q = Integer.parseInt(btn_waterLemon.getText().toString());
btn_waterLemon.setText(String.valueOf(q + 1));
q = q;
}
}
};
btn_apple.setOnClickListener(appleListener);
btn_cherry.setOnClickListener(cherryListener);
btn_orange.setOnClickListener(orangeListener);
btn_waterLemon.setOnClickListener(waterListener);
}
public void OnClickBsk(View view){
Intent intent = new Intent(SmActivity.this, BasketActivity.class);
startActivity(intent);
}
public void OnClickProfile(View view){
Intent intent = new Intent(SmActivity.this, ProfileActivity.class);
startActivity(intent);
}
}
Do this In Activity A when you click button to go to next Activity B
btn.setOnClickListener(v -> {
Intent i = new Intent(AActivity.this,BActivity.class);
// This below line sends Key- btnText and Value- Apple
i.putExtra("btnText","Apple");
startActivity(i);
});
In BActivity do this to button
// Here you receives data from activity a with the help of Key- btnText
btn.setText(getIntent().getStringExtra("btnText"));
This is a simple way to do this.
I Have Solved the answer for you,
Minor Explanations is in the comments in code.
Use this code as a concept and apply changes to yours based on your requirement.
XML of Activity A:
<?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"
tools:context=".ActivityA">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text Before Button Click"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:id="#+id/text_to_change"
android:textSize="20sp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_to_change"
android:id="#+id/change_text_btn"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="20dp"
android:text="Change Text and Start Activity B"
/>
</RelativeLayout>
Java of Activity A
package com.example.text_to_speech;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity);
TextView textView;
Button button;
textView=findViewById(R.id.text_to_change);
button=findViewById(R.id.change_text_btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newtext="New Text From Activity A";
textView.setText(newtext);
Intent intent=new Intent(ActivityA.this,ActivityB.class);
intent.putExtra("Change", newtext);//this string will be
//accessed by activityB
startActivity(intent);
}
});
}
}
XML of Activity B:
<?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"
tools:context=".ActivityB">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Waiting for New Text"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:id="#+id/new_textview"
android:textSize="20sp"
android:visibility="gone"
/>
</RelativeLayout>
Java of Activity B:
package com.example.text_to_speech;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class ActivityB extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
TextView textView;
textView=findViewById(R.id.new_textview);
// Below if block is looking for an intent, if it gets it and
// there is content in the extras with key "Change",
// it will make the textview in xml visible and update its string
// based on value set by Activity A
if(savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if (extras == null) {
Toast.makeText(ActivityB.this, "Can't Get the Intent", Toast.LENGTH_LONG).show();
} else {
String get_String = extras.getString("Change");
textView.setVisibility(View.VISIBLE);// be default i have set the visibility to gone in xml
//here it will get visible and then filled with the string sent by the intent in activity A
textView.setText(get_String);
}
}
}
}
My initial plan was to have a UI preference so the user can pick a bg color from the main activity whenever he/she wants - I got that to work BUT it isn't showing up the right color it's specified to. i.e. When Red button is pressed in Main Activity, it shows up Blue in the next activity instead.
Here is a snippet of the code with only two buttons using multiple intents for demo purposes...
My Main layout:
<Button
android:id="#+id/buttonRed"
android:onClick="passBG"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RED"
android:layout_marginLeft="18dp"
android:layout_marginStart="18dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/buttonBlue"
android:onClick="passBG"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BLUE"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/button"
android:layout_alignStart="#+id/button" />
Main Activity is working:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
public class MainActivity extends AppCompatActivity {
View view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view=this.getWindow().getDecorView();
view.setBackgroundResource(R.color.gray);
public void passBG(View v) {
Intent intent = new Intent(this, AudioActivity.class);
intent.putExtra("Red", R.color.red);
intent.putExtra("Blue", R.color.blue);
startActivity(intent);
}
}
But something's not right with the second Activity:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
public class AudioActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio);
int redBG = getIntent().getIntExtra("Red", -1);
int blueBG = getIntent().getIntExtra("Blue", -1);
RelativeLayout rootView = (RelativeLayout) findViewById(R.id.activity_audio);
rootView.setBackgroundResource(redBG);
rootView.setBackgroundResource(blueBG);
}
}
I figured out that whichever color in "..."BG is implemented first in
rootView.setBackgroundResource("..."BG)
will determine the one that will only pop out. It's something to do with the sequence I figured - AT FIRST ATTEMPT, I tried using the intents on separate methods i.e.
public void goRED(View v)
{
view.setBackgroundResource(R.color.red);
Intent intent = new Intent(this, AudioActivity.class);
intent.putExtra("Red", R.color.red);
startActivity(intent);
}
public void goBLUE(View v)
{
view.setBackgroundResource(R.color.blue);
Intent intent = new Intent(this, AudioActivity.class);
intent.putExtra("Blue", R.color.blue);
startActivity(intent);
}
BUT THAT WILL ONLY END UP IN ERROR so I called the buttons on the same method to prevent that problem. So now I'm stuck with a new problem - how do I correctly implement multiple intents to show up the right color BG on the next activity? should I use some if-else statement into it? Any help would be appreciated. Thanks!
Well try this:
Main Activity is working:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
public class MainActivity extends AppCompatActivity {
View view;
private Button redBtn;
private Button blueBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view=this.getWindow().getDecorView();
view.setBackgroundResource(R.color.gray); //This can be achieved by using the `android:background` attribute to your main element on your activity layout
redBtn = (Button) findViewById(R.id.buttonRed); //also, attributes ids on xml layouts shouldnt use uppercase letters, separete words using '_'
blueBtn = (Button) findViewById(R.id.buttonBlue);
redBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onButtonClick(R.color.red);
}
});
blueBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onButtonClick(R.color.blue);
}
});
}
private void onButtonClick(int color){
Intent intent = new Intent(this, AudioActivity.class);
intent.putIntExtra("background",color);
startActivity(intent);
}
}
then, on your second activity:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
public class AudioActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio);
int color = getIntent().getIntExtra("background", -1);
if(color != -1){
RelativeLayout rootView = (RelativeLayout) findViewById(R.id.activity_audio);
rootView.setBackgroundResource(color);
}
}
}
I've difficult with changing activity on android.
I started my app(display main.xml) and clicked Start button(display listening.xml).
When I had pressed back button, background disappeared on my app.
[display main.xml]
[display listening.xml]
detecting display.. (A image not attached because I have less reputation :( )
[display main.xml (Problem)]
Following is my source code.
(Some code are omitted.)
package com.musicg.demo.android;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnSignalsDetectedListener {
static MainActivity mainApp;
public static final int DETECT_NONE = 0;
public static final int DETECT_WHISTLE = 1;
public static int selectedDetection = DETECT_NONE;
// detection parameters
private DetectorThread detectorThread;
private RecorderThread recorderThread;
private int numWhistleDetected = 0;
// views
private View mainView, listeningView, helpView ;
private Button whistleButton , whistleButton02;
// alarmVoice()에서 사용하는 변수들 - am, mp, LOG
private AudioManager am;
private MediaPlayer mp;
private String LOG = "My_Tag";
ImageView imageView01;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainApp = this;
// set views
LayoutInflater inflater = LayoutInflater.from(this);
mainView = inflater.inflate(R.layout.main, null);
listeningView = inflater.inflate(R.layout.listening, null);
setContentView(mainView);
whistleButton = (Button) this.findViewById(R.id.whistleButton); // Start Button
whistleButton.setOnClickListener(new ClickEvent());
whistleButton02 = (Button) this.findViewById(R.id.whistleButton02); // ReadMe Button
whistleButton02.setOnClickListener(new ClickEvent());
}
private void goHomeView() {
setContentView(mainView);
if (recorderThread != null) {
recorderThread.stopRecording();
recorderThread = null;
}
if (detectorThread != null) {
detectorThread.stopDetection();
detectorThread = null;
}
selectedDetection = DETECT_NONE;
}
private void goListeningView() {
setContentView(listeningView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "종료");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
goHomeView();
return true;
}
return super.onKeyDown(keyCode, event);
}
class ClickEvent implements OnClickListener {
public void onClick(View view) {
if (view == whistleButton) { // Start Button
selectedDetection = DETECT_WHISTLE;
recorderThread = new RecorderThread();
recorderThread.start();
detectorThread = new DetectorThread(recorderThread);
detectorThread.setOnSignalsDetectedListener(MainActivity.mainApp);
detectorThread.start();
goListeningView();
}
if(view == whistleButton02) // ReadMe Button
{
Intent intent = new Intent(MainActivity.this, help.class );
startActivity(intent);
}
}
}
// omitted..
}
Please give me some advice.
Sorry for my bad english.
Thanks in advance.
Following are added context.
I tried to change inflater to setContentView().
But, It's not worked.
I clicked start button and touched back key on my phone.
My phone said "Unfortunately, (MY_APP_NAME) has stopped."
I reupload my source code.
[MainActivity.java]
package com.musicg.demo.android;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnSignalsDetectedListener {
static MainActivity mainApp;
public static final int DETECT_NONE = 0;
public static final int DETECT_WHISTLE = 1;
public static int selectedDetection = DETECT_NONE;
// detection parameters
private DetectorThread detectorThread;
private RecorderThread recorderThread;
private int numWhistleDetected = 0;
// views
private View mainView, listeningView, helpView ;
private Button whistleButton , whistleButton02;
// alarmVoice()에서 사용하는 변수들 - am, mp, LOG
private AudioManager am;
private MediaPlayer mp;
private String LOG = "My_Tag";
ImageView imageView01;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainApp = this;
// set views
// LayoutInflater inflater = LayoutInflater.from(this); // disable inflater
setContentView(R.layout.main);
// mainView = inflater.inflate(R.layout.main, null); // disable inflater
// listeningView = inflater.inflate(R.layout.listening, null); // disable inflater
// setContentView(mainView); // disable inflater
whistleButton = (Button) this.findViewById(R.id.whistleButton); // Start button
whistleButton.setOnClickListener(new ClickEvent());
whistleButton02 = (Button) this.findViewById(R.id.whistleButton02); // ReadMe button
whistleButton02.setOnClickListener(new ClickEvent());
}
private void goHomeView() {
setContentView(mainView);
if (recorderThread != null) {
recorderThread.stopRecording();
recorderThread = null;
}
if (detectorThread != null) {
detectorThread.stopDetection();
detectorThread = null;
}
selectedDetection = DETECT_NONE;
}
private void goListeningView() {
//setContentView(listeningView);
setContentView(R.layout.listening);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "Exit");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
NotificationManager notiMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notiMgr.cancel(999); // Notification의 고유 id가 999인 것을 찾아서 notification을 종료한다.
finish();
break;
default:
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
goHomeView();
return true;
}
return super.onKeyDown(keyCode, event);
}
class ClickEvent implements OnClickListener {
public void onClick(View view) {
if (view == whistleButton) {
selectedDetection = DETECT_WHISTLE;
recorderThread = new RecorderThread();
recorderThread.start();
detectorThread = new DetectorThread(recorderThread);
detectorThread.setOnSignalsDetectedListener(MainActivity.mainApp);
detectorThread.start();
goListeningView();
}
if(view == whistleButton02)
{
Intent intent = new Intent(MainActivity.this, help.class );
startActivity(intent);
}
}
}
private void Threadsleep(DetectorThread detectorThread){
try
{
detectorThread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onWhistleDetected() {
runOnUiThread(new Runnable() {
public void run() {
TextView textView = (TextView)
MainActivity.mainApp.findViewById(R.id.detectedNumberText);
textView.setText(String.valueOf(numWhistleDetected++));
if (numWhistleDetected > 1) {
setEvent();
}
}
});
Threadsleep(detectorThread);
}
}
[main.xml]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/car">
<Button
android:id="#+id/whistleButton"
android:layout_width="150dp"
android:layout_height="40dp"
android:gravity="center"
android:text="Start"
android:textSize="20dp"
android:background="#FFFFFFFF"
android:textColor="#FF000000"
android:padding="5dp"
android:layout_centerInParent = "true"
/>
<Button
android:id="#+id/whistleButton02"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_below="#id/whistleButton"
android:gravity="center"
android:text="ReadMe"
android:background="#FFFFFFFF"
android:textColor="#FF000000"
android:textSize="20dp"
android:layout_marginTop="15dp"
android:padding="5dp"
android:layout_centerInParent = "true"
/>
</RelativeLayout>
[listening.xml]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background ="#drawable/worker"
>
<TextView
android:id="#+id/listening"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerVertical="true"
android:layout_centerInParent="true"
android:textSize="30dp"
android:text="Detecting.." />
<TextView
android:id="#+id/detectedText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/listening"
android:layout_centerInParent="true"
android:textSize="20dp" />
<TextView
android:id="#+id/detectedNumberText"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/listening"
android:textSize="5dp"
android:layout_toRightOf="#+id/detectedText"
/>
</RelativeLayout>
[help.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"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="112dp"
android:layout_marginTop="20dp"
android:text="Read Me...." />
</RelativeLayout>
[AndroidManifest.xml]
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.musicg.demo.android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application
android:icon="#drawable/ear"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".listening"></activity>
<activity android:name="help"></activity>
</application>
</manifest>
First of all Use setContentView(R.layout.main) in onCreate() in your oncreate as Akhil mentioned instead of inflating.
Also to set background image to your activity use android:background="#drawable/image_name" to your root container in main.xml.
If you are trying to dynamically switch the image in your lisenter.
Try and let us know if it worked.
Also to get more understanding can to show contents of your main.xml ?
I have an Android application with a very simple main activity. It only has two buttons, one textview and one edittext field. I launch the main activity (I don't do anything, just launch it from app drawer), then I press home button to get to my home screen, go to settings > appmanager > running > cached background processes and there I see that my app is eating more RAM than other cached background processes, around 8 MB of RAM. Is it normal? Why is it eating more than other apps? This is my code:
MainActivity:
package com.example.myapp;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass();
long maxMemory = Runtime.getRuntime().maxMemory();
long totalMemory = Runtime.getRuntime().totalMemory();
Log.i("ilog", "memoryClass: " + memoryClass);
Log.i("ilog", "maxMemory: " + maxMemory);
Log.i("ilog", "totalMemory: " + totalMemory);
}
#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 {
private Button button1;
private Button button2;
private TextView textView1;
private EditText editText1;
private ComponentName cn;
private String disable = "Disable app";
private String enable = "Enable app";
private int enabledState;
private PackageManager pm;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
button1 = (Button) rootView.findViewById(R.id.button1);
editText1 = (EditText) rootView.findViewById(R.id.editText1);
textView1 = (TextView) rootView.findViewById(R.id.textView1);
button2 = (Button) rootView.findViewById(R.id.button2);
cn = new ComponentName(getActivity(), CallReceiver.class);
pm = getActivity().getPackageManager();
enabledState = pm.getComponentEnabledSetting(cn);
if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
button1.setText(disable);
} else {
button1.setText(enable);
}
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
enabledState = pm.getComponentEnabledSetting(cn);
if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
pm.setComponentEnabledSetting(cn,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
button1.setText(enable);
} else {
pm.setComponentEnabledSetting(cn,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
button1.setText(disable);
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editText1.getText().toString().length() > 0) {
Intent callImitateIntent = new Intent(getActivity(), CallReceiver.class);
callImitateIntent.putExtra(TelephonyManager.EXTRA_STATE, TelephonyManager.EXTRA_STATE_RINGING);
callImitateIntent.putExtra(TelephonyManager.EXTRA_INCOMING_NUMBER, editText1.getText().toString());
getActivity().sendBroadcast(callImitateIntent);
} else textView1.setText("Invalid incoming number");
}
});
return rootView;
}
}
#Override
public void onDestroy() {
super.onDestroy();
Intent serviceStopIntent = new Intent(this, WindowService.class);
stopService(serviceStopIntent);
}
}
fragment_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.myapp.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="#string/welcome" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:maxLength="12"
android:hint="#string/edittext1" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="#string/button2" />
</RelativeLayout>
So can anyone tell me why is it eating so much RAM? Thanks in advance!
calculated.java: (this has to command to show the calculated.xml layout)
public class Calculated extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculated);
}
}
older:
main class:
package com.barth.appie;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.EditText;
public class MainActivity extends Activity {
Button button1;
String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public void addListenerOnButton() {
button1 = (Button) findViewById(R.id.buttoncalculate);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText editText = (EditText)findViewById(R.id.editText1);
String text = editText.getText().toString();
Intent myIntent = new Intent(view.getContext(), Calculated.class);
startActivityForResult(myIntent, 0);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
calculated.xml: (this is what it has to show after the button press)
<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=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp"
android:text="#string/text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Furthermore I have <string name="text">Value</string> at strings.xml, and in the other class called calculated.class, I have it so that it outputs the calculated.xml ( which works fine)
What I want: I want to display text in calculated.xml, which is a string made in main.class, and i want the string to be the text filled in textfield called "editText1"
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.EditText;
public class MainActivity extends Activity {
Button button1;
String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public void addListenerOnButton() {
button1 = (Button) findViewById(R.id.buttoncalculate);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText editText = (EditText)findViewById(R.id.editText1);
String text = editText.getText().toString();
Intent myIntent = new Intent(view.getContext(),Calculated.class);
myIntent.putExtra("mytext",text);
startActivity(myIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Calculated.java
public class Calculated extends Activity {
TextView mTextview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculated);
mTextview = (TextView)findViewById(R.id.textView1);
mTextview.setText(getIntent().getStringExtra("mytext"));
}
calculated.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
To send the data from one activity to another activity
MainActivity.java is first activity from where you want to send data to another activity.
Intent myIntent = new Intent(view.getContext(), Calculated.class);
myIntent.putExtra("text", text);
startActivity(myIntent);
Calculated.java is second activity which receive the intent data whatever you pass from MainActivity.java
String text = myIntent.getStringExtra("text");
TextView textView = (TextView)findViewById(R.id.textView1);
textView.setText(text);