changing activity on android - android

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 ?

Related

How do I get each textview resource amount and add them all together into a single variable to be converted into a two sliced pie chart?

This is the code I have been working on for a while. The only issue is I cannot seem to be able to get the sum of values input into the editText fields that are dynamically added into the program and then place them into a pie chart. The data is to be transferred from the second activity to the third where the third activity will add up all resource amounts and display them into a pie chart.
SecondActivity.class
package com.example.a4mob;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.InputType;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.drawerlayout.widget.DrawerLayout;
import java.util.ArrayList;
import java.util.List;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
public DrawerLayout drawerLayout;
public ActionBarDrawerToggle actionBarDrawerToggle;
private LinearLayout linearLayout;
private Button add;
//for button add resource
List<String> ColourList = new ArrayList<>();
ArrayList<Results> resultList = new ArrayList<>();
private Button submit;
private Number uinput;
#Override
protected void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.secondactivity);
// drawer layout instance to toggle the menu icon to open
// drawer and back button to close drawer
drawerLayout = findViewById(R.id.my_drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.nav_open, R.string.nav_close);
// pass the Open and Close toggle for the drawer layout listener
// to toggle the button
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
// to make the Navigation drawer icon always appear on the action bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar;
actionBar = getSupportActionBar();
// Define ColorDrawable object and parse color
// using parseColor method
// with color hash code as its parameter
ColorDrawable colorDrawable
= new ColorDrawable(Color.parseColor("grey"));
// Set BackgroundDrawable
actionBar.setBackgroundDrawable(colorDrawable);
//Adds more objects
linearLayout = findViewById(R.id.layout_list);
add = findViewById(R.id.CreateNew);
add.setOnClickListener(this);
ColourList.add("grey");
ColourList.add("green");
ColourList.add("blue");
ColourList.add("yellow");
// Creating submit button click listener
submit = findViewById(R.id.Submit);
submit.setOnClickListener(this);
}
public void onClick(View view){
switch (view.getId()){
case R.id.CreateNew:
addView();
break;
case R.id.Submit:
if(isValid()){
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("list", resultList);
intent.putExtras(bundle);
startActivity(intent);
}
break;
}
}
private boolean isValid() {
resultList.clear();
boolean valid = true;
for(int i = 0; i < linearLayout.getChildCount(); i++){
View resultView = linearLayout.getChildAt(i);
EditText resultName = (EditText) resultView.findViewById(R.id.RName);
EditText resultNumber = (EditText) resultView.findViewById(R.id.RAmount);
AppCompatSpinner COP = (AppCompatSpinner) resultView.findViewById(R.id.ColourOP);
Results results = new Results();
if(!resultName.getText().toString().equals("")){
results.setResName(resultName.getText().toString());
}else{
valid = false;
break;
}
if(!resultNumber.getText().toString().equals("")){
results.setResAmount(Integer.parseInt(resultNumber.getText().toString()));
}else{
valid = false;
break;
}
if(COP.getSelectedItemPosition()!=0){
}else{
valid = false;
break;
}
resultList.add(results);
}
if(resultList.size() == 0){
valid = false;
Toast.makeText(this, "Complete all fields first", Toast.LENGTH_SHORT).show();
} else if(!valid){
Toast.makeText(this, "Enter details correctly", Toast.LENGTH_SHORT).show();
}
return valid;
}
public void addAmount(){
for(int i = 0; i < linearLayout.getChildCount(); i++) {
View resultView = linearLayout.getChildAt(i);
EditText resultNumber = (EditText) resultView.findViewById(R.id.RAmount);
Results results = new Results();
}
}
private void sub(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please input inventory space:");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_NUMBER);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
uinput = input.getInputType();
changeAct();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
private void changeAct(){
Intent intent = new Intent(this, ThirdActivity.class);
startActivity(intent);
}
private void addView(){
View newResource = getLayoutInflater().inflate(R.layout.row_add_data, null, false);
ImageView imageClose = (ImageView)newResource.findViewById(R.id.Remove);
TextView RN = (TextView) newResource.findViewById(R.id.RName);
TextView RA = (TextView) newResource.findViewById(R.id.RAmount);
AppCompatSpinner COP = (AppCompatSpinner) newResource.findViewById(R.id.ColourOP);
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, ColourList);
COP.setAdapter(arrayAdapter);
imageClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeView(newResource);
}
});
linearLayout.addView(newResource);
}
private void removeView(View view){
linearLayout.removeView(view);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
super.onPointerCaptureChanged(hasCapture);
}
}
ThirdActivity.class
package com.example.a4mob;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class ThirdActivity extends AppCompatActivity {
RecyclerView recycle_results;
ArrayList<Results> resultList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thirdactivity);
recycle_results = findViewById(R.id.res_results);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
recycle_results.setLayoutManager(linearLayoutManager);
resultList = (ArrayList<Results>) getIntent().getExtras().getSerializable("list");
recycle_results.setAdapter(new ResultsAdapter(resultList));
}
}
Results.class
package com.example.a4mob;
import java.io.Serializable;
public class Results implements Serializable {
public String resourceName;
public int resourceAmount;
public int totalAmount;
public Results(){
}
public int getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(int totalAmount) {
this.totalAmount = totalAmount;
}
public int getResAmount() {
return resourceAmount;
}
public void setResAmount(int resourceAmount) {
this.resourceAmount = resourceAmount;
}
public Results(String resourceName, int resourceAmount){
this.resourceName = resourceName;
this.resourceAmount = resourceAmount;
}
public String getResName() {
return resourceName;
}
public void setResName(String resourceName) {
this.resourceName = resourceName;
}
}
ResultsAdapter.class
package com.example.a4mob;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ResultsAdapter extends RecyclerView.Adapter<ResultsAdapter.ResultsView> {
ArrayList<Results> resultList = new ArrayList<>();
int total;
public ResultsAdapter(ArrayList<Results> resultList) {
this.resultList = resultList;
}
#NonNull
#Override
public ResultsView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_results,parent,false);
return new ResultsView(view);
}
#Override
public void onBindViewHolder(#NonNull ResultsView holder, int position) {
Results results = resultList.get(position);
holder.resourceName.setText(results.getResName());
holder.resourceAmount.setText(String.valueOf(results.getResAmount()));
}
#Override
public int getItemCount() {
return resultList.size();
}
public class ResultsView extends RecyclerView.ViewHolder{
TextView resourceName, resourceAmount, resourceTotal;
public ResultsView(#NonNull View itemView) {
super(itemView);
resourceName = (TextView) itemView.findViewById(R.id.resNa);
resourceAmount = (TextView) itemView.findViewById(R.id.resAm);
resourceTotal = (TextView) itemView.findViewById(R.id.resTot);
}
}
}
thirdactivity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".ThirdActivity">
<LinearLayout
android:id="#+id/layoutThird"
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/res_results"
android:layout_width="match_parent"
android:layout_height="match_parent"></androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
row_results.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardBackgroundColor="#color/white"
android:layout_margin="5dp"
android:layout_marginBottom="20dp"
app:cardCornerRadius="10dp"
app:cardElevation="10dp">
<LinearLayout
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="1"
android:layout_marginBottom="0dp">
<TextView
android:id="#+id/resNa"
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Resource Name"
android:textSize="18sp"
android:textColor="#color/black"></TextView>
<TextView
android:id="#+id/resAm"
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Resource Amount"
android:textSize="14sp"
android:textColor="#color/black"></TextView>
<TextView
android:id="#+id/resTot"
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Resource Amount"
android:textSize="14sp"
android:textColor="#color/black"></TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>

Why my Android application is eating so much RAM?

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!

Button Display Android Eclipse

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.

Using DialogFragments. Are there bugs in the official example?

I have just copied the official example, and my dialog is very narrow. Why?
My code.
The dialog.
package com.redplanet;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class EditNameDialog extends DialogFragment implements OnEditorActionListener {
public interface EditNameDialogListener {
void onFinishEditDialog(String inputText);
}
private EditText mEditText;
public EditNameDialog() {
// Empty constructor required for DialogFragment
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_edit_name, container);
mEditText = (EditText) view.findViewById(R.id.txt_your_name);
getDialog().setTitle("Hello");
// Show soft keyboard automatically
mEditText.requestFocus();
getDialog().getWindow().setSoftInputMode(
LayoutParams.SOFT_INPUT_STATE_VISIBLE);
mEditText.setOnEditorActionListener(this);
return view;
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (EditorInfo.IME_ACTION_DONE == actionId) {
// Return input text to activity
EditNameDialogListener activity = (EditNameDialogListener) getActivity();
activity.onFinishEditDialog(mEditText.getText().toString());
this.dismiss();
return true;
}
return false;
}
}
The activity.
package com.redplanet;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.Menu;
import android.widget.Toast;
import com.redplanet.EditNameDialog.EditNameDialogListener;
public class FragmentDialogDemo extends FragmentActivity implements EditNameDialogListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showEditDialog();
}
private void showEditDialog() {
FragmentManager fm = getSupportFragmentManager();
EditNameDialog editNameDialog = new EditNameDialog();
editNameDialog.show(fm, "fragment_edit_name");
}
#Override
public void onFinishEditDialog(String inputText) {
Toast.makeText(this, "Hi, " + inputText, Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return super.onCreateOptionsMenu(menu);
}
}
Activity layout file.
<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" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="#dimen/padding_medium"
android:text="#string/hello_world"
tools:context=".FragmentDialogDemo" />
</RelativeLayout>
Dialog layout file.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/edit_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/lbl_your_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your name" />
<EditText
android:id="#+id/txt_your_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"
android:inputType="text" />
</LinearLayout>
In order not to puzzle over workarounds, I'd prefer an AlertDialog to a DialogFragment. The issue I asked about was on Android 2.3.6 and wasn't on Android 4.1.2.

Android Handler Message and ListView

Here's my error:
*** Uncaught remote exception! (Exceptions are not yet supported across processes.)
android.util.AndroidRuntimeException: { what=1008 when=368280372 } This message is already in use.
at android.os.MessageQueue.enqueueMessage(MessageQueue.java:171)
at android.os.Handler.sendMessageAtTime(Handler.java:457)
at android.os.Handler.sendMessageDelayed(Handler.java:430)
at android.os.Handler.sendMessage(Handler.java:367)
at android.view.ViewRoot.dispatchAppVisibility(ViewRoot.java:2748)
What I'm attempting is to have a listview, that is populated by custom list items, each list item has multiple views and each view has an onclick listener attached. When this onClickListener is pressed it sends a Message to a Handler with a what and arg1 arguments.
Clicking one of my elements fires an intent to start a new activity.
Clicking the other shows a toast.
When these are pressed in a combination I get the error above. Namely clicking the text to fire the intent, (then press back) then clicking the image to show the toast, then when you click the text to fire the intent again I get the FC.
And here is the code below, I tried to remove as much cruft as I could to get to the bones of the error:
If you want to skip to whats important look at the onClickListener's in ConversationAdapter.class and how they interact with StartPage.class
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.handler.test"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".StartPage"
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=".DetailsPage"
android:label="DetailsPage"
>
</activity>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
StartPage.class:
package com.handler.test;
import java.util.ArrayList;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
public class StartPage extends ListActivity {
private ArrayList<Conversation> mConversations = null;
private ConversationAdapter mAdapter;
private Context mContext;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = this;
mConversations = new ArrayList<Conversation>();
this.mAdapter = new ConversationAdapter(mContext, R.layout.inbox_row, mConversations, mHandler);
setListAdapter(this.mAdapter);
new Thread(new Runnable() {
#Override
public void run() {
getConversations();
}
}).start();
mProgressDialog = ProgressDialog.show(StartPage.this, "Please wait...", "Retrieving data ...", true);
}
private void getConversations() {
try {
mConversations = new ArrayList<Conversation>();
Conversation o1 = new Conversation();
o1.setStatus("SF services");
o1.setMessage("Pending");
mConversations.add(o1);
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(mConversations != null && mConversations.size() > 0){
mAdapter.notifyDataSetChanged();
for(int i=0;i<mConversations.size();i++)
mAdapter.add(mConversations.get(i));
}
mProgressDialog.dismiss();
mAdapter.notifyDataSetChanged();
}
};
private Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
int convIndex = msg.arg1;
int viewTouched = msg.what;
switch(viewTouched){
case ConversationAdapter.PROF_ICON:
showNumber(convIndex);
break;
case ConversationAdapter.MESSAGE:
showMessageDetails(convIndex);
break;
}
super.handleMessage(msg);
}
};
private void showNumber(int convIndex) {
Toast.makeText(mContext, "Pressed: "+convIndex, Toast.LENGTH_LONG).show();
}
private void showMessageDetails(int convIndex) {
final Conversation conv = mConversations.get(convIndex);
Intent i = new Intent(mContext, DetailsPage.class);
i.putExtra("someExtra", conv);
startActivity(i);
}
}
DetailsPage.class
package com.handler.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class DetailsPage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i("Test", "Details Page");
}
}
Conversation.class:
package com.handler.test;
import java.io.Serializable;
public class Conversation implements Serializable {
private static final long serialVersionUID = -437261671361122258L;
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
ConversationAdapter.class:
package com.handler.test;
import java.util.ArrayList;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class ConversationAdapter extends ArrayAdapter<Conversation> {
public static final int PROF_ICON = 0;
public static final int MESSAGE = 1;
private Context mContext;
private Handler mHandler;
private ArrayList<Conversation> mItems;
private int mXmlId;
private LinearLayout detailsOfConv;
private ImageView iconImage;
public ConversationAdapter(Context context, int textViewResourceId, ArrayList<Conversation> items, Handler handler) {
super(context, textViewResourceId, items);
this.mContext = context;
this.mItems = items;
this.mXmlId = textViewResourceId;
this.mHandler = handler;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(mXmlId, null);
}
final Message m = new Message();
m.arg1 = position;
Conversation c = mItems.get(position);
if (c != null) {
iconImage = (ImageView) v.findViewById(R.id.icon);
if (iconImage != null) {
iconImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
m.what = PROF_ICON;
mHandler.sendMessage(m);
}
});
}
detailsOfConv = (LinearLayout) v.findViewById(R.id.details);
if(detailsOfConv != null){
detailsOfConv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
m.what = MESSAGE;
mHandler.sendMessage(m);
}
});
}
}
return v;
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
>
<ListView
android:id="#+id/android:list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:cacheColorHint="#00000000"
/>
</LinearLayout>
inbox_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip">
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="6dip"
android:src="#drawable/icon" />
<LinearLayout
android:id="#+id/details"
android:orientation="vertical"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="fill_parent">
<TextView
android:id="#+id/toptext"
android:textColor="#99FF66"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:singleLine="true"
android:text="123456789"
/>
</LinearLayout>
</LinearLayout>
My guess would be that you are sending twice the same message. Indeed in the code there is one new Message() and two mHandler.sendMessage(m) which are possibly both executed.
Try making a new message for every time you send a message.
Edited:
Message.obtain() is preferable to Message m = new Message() (because it recycles used messages under the hood)
In your case you could use new.copyFrom(old) if you need a copy of existing message.

Categories

Resources