Why my Android application is eating so much RAM? - android

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!

Related

xml layout loads but my activity doesn't respond to button clicks

I'm new at this but I already made a small app that worked the same way.
I can't see what I'm doing wrong because the code looks quiet the same as my previous app.
When I run it or debug my app it shows my layout on my emulator so it does load the page that has to be loaded but that's all it does, it doesn't listen to button clicks. I also gives me no errors.
Here's my XML code for 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">
<TextView
android:text="Eventaris"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="100px"
android:textStyle="bold"
android:id="#+id/lblEventaris"
/>
<LinearLayout
android:layout_width="500px"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:orientation="vertical"
android:id="#+id/login">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Gebruikersnaam"
android:id="#+id/txtGebruikersnaam"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Wachtwoord"
android:inputType="textPassword"
android:layout_below="#id/txtGebruikersnaam"
android:id="#+id/txtWachtwoord"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Inloggen"
android:id="#+id/btnInloggen"
android:layout_below="#id/txtWachtwoord"/>
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:layout_below="#id/login">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="nog geen account?"
android:gravity="center"
android:id="#+id/lblRegistratie"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Registeren"
android:id="#+id/btnRegistreren"
android:layout_below="#id/lblRegistratie"/>
</RelativeLayout>
</RelativeLayout>
Here's my fragmennt activity MainFragment.Java
package com.example.arno.eventaris;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import java.sql.SQLException;
/**
* Created by Arno on 28/04/2015.
*/
public class MainFragment extends Fragment {
private OnMainFragmentInteractionListener mListener;
private View view;
public MainFragment()
{
//required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view=inflater.inflate(R.layout.fragment_main, container, false);
Button btnInloggen = (Button) view.findViewById(R.id.btnInloggen);
btnInloggen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
inloggen();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
Button btnRegistreren = (Button) view.findViewById(R.id.btnRegistreren);
btnRegistreren.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
navigeerRegistratie();
}
});
return view;
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try{
mListener = (OnMainFragmentInteractionListener) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException(activity.toString() + "must implement OnFragmentInteractionListener");
}
}
public void inloggen() throws SQLException {
EditText gebr=(EditText) view.findViewById(R.id.txtGebruikersnaam);
EditText wachtw=(EditText) view.findViewById(R.id.txtWachtwoord);
String gebruiker = gebr.getText().toString();
String wachtwoord = wachtw.getText().toString();
mListener.login(gebruiker, wachtwoord);
}
public void navigeerRegistratie()
{
mListener.navigeerRegistratie();
}
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
public interface OnMainFragmentInteractionListener {
//Todo: Update argument type and name
public void login(String gebruiker, String wachtwoord) throws SQLException;
public void navigeerRegistratie();
}
}
Here is my Main Activity MainActivity.java
package com.example.arno.eventaris;
import android.app.DialogFragment;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.example.arno.eventaris.Database.DBAdapter;
import java.sql.SQLException;
public class MainActivity extends ActionBarActivity implements MainFragment.OnMainFragmentInteractionListener,RegistratieFragment.OnRegistratieFragmentInteractionListener{
private Cursor gebruikerCursor;
#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();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void login(String gebruiker, String wachtwoord) throws SQLException {
DBAdapter db = new DBAdapter(this);
db.open();
gebruikerCursor = db.getGebruiker(gebruiker);
if(gebruikerCursor.moveToFirst()) {
gebruikerCursor.moveToFirst();
String wwControle = gebruikerCursor.getString(gebruikerCursor.getColumnIndex("wachtwoord"));
if (wachtwoord.equals(wwControle)) {
HomeFragment fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putString("gebruikersnaam", gebruiker);
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
} else {
DialogFragment errorlogin = new ErrorLogin();
errorlogin.show(getFragmentManager(), "Wachtwoord incorrect!");
}
}
else
{
DialogFragment errorlogin = new ErrorLogin();
errorlogin.show(getFragmentManager(), "Gebruikersnaam incorrect!");
}
db.close();
}
#Override
public void navigeerRegistratie() {
getFragmentManager().beginTransaction().replace(R.id.container, new RegistratieFragment()).commit();
}
#Override
public void registreren(String gebruiker, String voornaam, String naam, String email, String wachtwoord, String herhaalWachtwoord) {
if(wachtwoord.equals(herhaalWachtwoord)) {
DBAdapter db = new DBAdapter(this);
db.open();
long id = db.insertGebruiker(gebruiker, voornaam, naam, email, wachtwoord);
getFragmentManager().beginTransaction().replace(R.id.container, new MainFragment()).commit();
}
else
{
DialogFragment errorregistratie = new ErrorRegistratie();
errorregistratie.show(getFragmentManager(), "Wachtwoorden komen niet overeen!");
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
And as last here is my activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/container"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity" tools:ignore="MergeRootFrame" />
Thanks in advance!
Fixed it by making a new project with the same code, had to be a problem way deeper than my code.

Android EditText not editable

I have a 2 activities with edittexts on them the first activity work fine but the second activity's EditText is focused but I can't edit it nor can I click the button on it.
Also everything works in the emulator but not when I install it on the device. (The keyboard popup also does not come up in the second activity where as it does in the first activity)
Below is the code for the1st and second activity
First Activity Class
package com.rohan.rohan_pc.sportappnew;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends ActionBarActivity {
EditText edtEmail, edtPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Initialize components
edtEmail = (EditText) findViewById(R.id.edtEmail);
edtPassword = (EditText) findViewById(R.id.edtPassword);
Button btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (edtEmail.getText().toString().length() > 0 && edtPassword.getText().toString().length() > 0) {
new GetAllCustomerTask().execute(new ConnecterClass());
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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);
}
// Connect to the DB
private class GetAllCustomerTask extends AsyncTask<ConnecterClass, Long, JSONArray>
{
#Override
protected JSONArray doInBackground(ConnecterClass... params) {
// Execute in background
return params[0].usrLogin(edtEmail.getText().toString(), edtPassword.getText().toString());
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
if (jsonArray != null) {
JSONObject json = null;
try {
json = jsonArray.getJSONObject(0);
if (edtEmail.getText().toString().equals(json.getString("email"))) {
if (edtPassword.getText().toString().equals(json.getString("pass"))) {
Toast toast = Toast.makeText(getApplicationContext(), "login successful", Toast.LENGTH_SHORT);
toast.show();
Intent intent = new Intent(LoginActivity.this, SearchActivity.class);
//Pass the school_id
intent.putExtra("SCHOOL_ID", json.getInt("school_id"));
startActivity(intent);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "password incorrect", Toast.LENGTH_SHORT);
toast.show();
}
} else {
Toast toast = Toast.makeText(getApplicationContext(), "failed to login ...", Toast.LENGTH_SHORT);
toast.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
//login(edtEmail.getText().toString(),""
/*
//Got to second screen if login is successful
Intent intent = new Intent(LoginActivity.this, AfterLogin.class);
//Pass the table name through
intent.putExtra("CLIENT_DB", clientDB);
startActivity(intent);
*/
}
}
}
}
Second Activity Class
> package com.rohan.rohan_pc.sportappnew;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SearchActivity extends ActionBarActivity {
EditText edtFName, edtLName, edtIDNum;
ListView listViewSearch;
String sFName, sLName, sIDNum;
int school_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
edtFName = (EditText) findViewById(R.id.edtFirstName);
edtLName = (EditText) findViewById(R.id.edtLastName);
edtIDNum = (EditText) findViewById(R.id.edtIDNum);
Button btnSearch = (Button) findViewById(R.id.btnSearch);
listViewSearch = (ListView) this.findViewById(R.id.listViewSearch);
//Initialize the default values for the search criteria variables
sFName = "";
sLName = "";
sIDNum = "";
//Load school_id
school_id = getIntent().getExtras().getInt("SCHOOL_ID");
if(edtFName.requestFocus()) { getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); }
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(edtFName.getText().toString().length() > 0)
{
sFName = edtFName.getText().toString().trim();
}
if(edtLName.getText().toString().length() > 0)
{
sLName = edtLName.getText().toString().trim();
}
if(edtIDNum.getText().toString().length() > 0)
{
sIDNum = edtIDNum.getText().toString().trim();
}
new SearchAllCustomers().execute(new ConnecterClass());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search, 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);
}
//Search in the background
public void setListViewArray(final JSONArray jsonArray)
{
this.listViewSearch.setAdapter(new Search_ListView_Adapter(jsonArray, this));
//Setup what happens when a user clicks on a searched item
this.listViewSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try{
JSONObject clickedItem = jsonArray.getJSONObject(position);
Intent askActivity = new Intent(getApplicationContext(), AskActivity.class);
askActivity.putExtra("IDNUM", clickedItem.getString("idnum"));
askActivity.putExtra("SCHOOL_ID", clickedItem.getInt("school_id"));
startActivity(askActivity);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
// Connect to the DB
private class SearchAllCustomers extends AsyncTask<ConnecterClass, Long, JSONArray>
{
#Override
protected JSONArray doInBackground(ConnecterClass... params) {
// Execute in background
return params[0].searchPlayers(school_id, sFName, sLName, sIDNum);
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
if (jsonArray != null) {
setListViewArray(jsonArray);
//login(edtEmail.getText().toString(),""
/*
//Got to second screen if login is successful
Intent intent = new Intent(LoginActivity.this, AfterLogin.class);
//Pass the table name through
intent.putExtra("CLIENT_DB", clientDB);
startActivity(intent);
*/
}
}
}
}
The XML - First Activity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".LoginAcivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/edtEmail"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp"
android:hint="email ..."
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/edtPassword"
android:layout_below="#+id/edtEmail"
android:layout_centerHorizontal="true"
android:layout_marginTop="44dp"
android:hint="password ..."
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/btnLogin"
android:layout_below="#+id/edtPassword"
android:layout_centerHorizontal="true"
android:layout_marginTop="49dp" />
</RelativeLayout>
The XML - Second Activity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.rohan.rohan_pc.sportsappv001.SearchActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Search"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Name"
android:ems="10"
android:id="#+id/edtFirstName"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Surname"
android:ems="10"
android:id="#+id/edtLastName"
android:layout_below="#+id/edtFirstName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/edtIDNum"
android:hint="ID Number"
android:layout_below="#+id/edtLastName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="#+id/edtLastName"
android:layout_alignEnd="#+id/edtLastName" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:id="#+id/btnSearch"
android:layout_below="#+id/edtIDNum"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="64dp"
android:layout_marginTop="42dp" />
<ListView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:id="#+id/listViewSearch"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#+id/edtIDNum"
android:layout_alignTop="#+id/edtFirstName"
android:clickable="true"
/>
I just figured to re-create the app. I dont think it is a wise decision to copy the raw files to another directory and use that.

How to pass value from a method to another method

import android.support.v4.app.Fragment;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import android.widget.NumberPicker.OnValueChangeListener;
public class MainActivity extends Activity implements OnValueChangeListener {
EditText push_ups, sit_ups;
NumberPicker np;
Button calculate;
final Context context = this;
CheckBox checkbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calculate = (Button)findViewById(R.id.calculate);
push_ups = (EditText)findViewById(R.id.pushups);
sit_ups = (EditText)findViewById(R.id.situps);
np = (NumberPicker)findViewById(R.id.np1);
checkbox = (CheckBox)findViewById(R.id.checkbox);
String[] values = {"some array"};
np.setMaxValue(values.length-1);
np.setMinValue(0);
np.setDisplayedValues(values);
np.setWrapSelectorWheel(false);
//calculateButton runs when I click the "calculate" Button
calculateButton();
LinearLayout layout = (LinearLayout)findViewById(R.id.linearLayout1);
layout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
hideKeyboard();
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
}
private void hideKeyboard() {
InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(push_ups.getWindowToken(), 0);
}
public int calculatePushups() {
int pushupScore = 0;
int ageGroup = Integer.parseInt(null, np.getValue());
int pushupReps = Integer.parseInt(push_ups.getText().toString());
final int [][] pushupTable = {"some 2D array"};
if (pushupReps<= 60) {
pushupScore = pushupTable[pushupReps][ageGroup];
} else {
pushupScore = 60;
}
return pushupScore;
}
public int calculateSitups() {
final int [][] situpTable = {"some 2D array"};
return 0;
}
private void normalRun() {
}
private void specialRun() {
}
private void calculateRun() {
if (checkbox.isChecked()) {
specialRun();
}
else {
normalRun();
}
}
private void calculateScore() {
calculatePushups();
calculateSitups();
calculateRun();
}
public void calculateButton() {
final TextView pus = (TextView)findViewById(R.id.pushup_score);
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_custom);
dialog.setTitle("Score");
I am trying to set the TextView to display the pushupScore here but it seems I am trying to pass a result from another method to this. I have no idea how to get it around still new with android,
//pus.setText(pushupScore);
pus.setText(String.valueOf(calculatePushups()));
Button dialogButton = (Button) dialog.findViewById(R.id.dialog_ok);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
}
Here's my dialog XML code:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:text="Push-ups: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/pushup_score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4.97"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:text="Sit-ups: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:text="2.4km Run: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:text="Award: "
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/dialog_ok"
style="#style/AppTheme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:lineSpacingExtra="5dp"
android:text="Ok" />
</LinearLayout>
you are returning the pushupScore in calculatePushups so just write:
pus.setText(String.valueOf(calculatePushups()));
And btw this is not a android mechanism, this is simple java return usage:
http://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html
You left out quite a bit of your code so I'm not sure where your problem is, but if you could follow these steps and let me know if you're getting any errors etc? Anyway, here is what you need to have:
Make sure your Activity implements OnClickListener:
public class MainActivity extends Activity implements OnClickListener, OnValueChangeListener {
//...
}
Within the activity's overridden onCreate() method, register the activity as the handler:
calculate = (Button)v.findViewById(R.id.dialog_ok);
calculate.setOnClickListener(this);
Within MainActivity, have the handler like so:
public void onClick(View v){
switch(v.getId(){
case R.id.dialog_ok:
push_ups.setText("" + calculatePushups());
break;
}
// ...
}
Perhaps you should change your EditText into a TextView, the EditText isn't necessary and might be causing problems?
Is this what you were after?

Problems with the event treatment of a Button

Something very weird is happening in my program. I try to use the button with the first program below (using an emulator) and the program did not even open. So I changed to the second version, using the android:OnClick, and it did not work either (the program opened, but in the click it crashed). Then I tried the third program, using android:onCLick and the instanciation of the EditText in the treatment function, and the program worked.
Can someone explain to me why the first two programs did not worked?
Edit: I noticed now that LogCat is pointing to the following error: error opening trace file: No such file oor directory (2), what is that? Can it have any relation to this error?
And if I comment the definition of the onClickListener to b1 the program do not crash anymore.
First code:
package app.projetnf33;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends Activity implements OnClickListener{
String[] names;
EditText status;
EditText par1;
EditText par2;
EditText par3;
Button b1;
Button b2;
Button b3;
Button b4;
Spinner spin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (EditText) findViewById(R.id.text);
b1 = (Button) findViewById(R.id.b1);
b1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
status.setText("Connect");
}
});
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Second code
package app.projetnf33;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends Activity implements OnClickListener{
String[] names;
EditText status;
EditText par1;
EditText par2;
EditText par3;
Button b1;
Button b2;
Button b3;
Button b4;
Spinner spin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (EditText) findViewById(R.id.text);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void treatment_connect(View v){
status.setText("Connect");
}
public void treatment_persons(View v){
status.setText("Persons");
}
public void treatment_lecture(View v){
status.setText("Lecture");
}
public void treatment_execute(View v){
status.setText("Execute");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Third code (which worked):
package app.projetnf33;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class MainActivity extends Activity implements OnClickListener{
String[] names;
EditText status;
EditText par1;
EditText par2;
EditText par3;
Button b1;
Button b2;
Button b3;
Button b4;
Spinner spin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void treatment_connect(View v){
status = (EditText) findViewById(R.id.text);
status.setText("Connect");
}
public void treatment_persons(View v){
status.setText("Persons");
}
public void treatment_lecture(View v){
status.setText("Lecture");
}
public void treatment_execute(View v){
status.setText("Execute");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Fragment_layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tex_status" />
<EditText
android:id="#+id/text"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<Spinner
android:id="#+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/par1" />
<EditText
android:id="#+id/par1"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/par2" />
<EditText
android:id="#+id/par2"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/par3" />
<EditText
android:id="#+id/par3"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_action_usb"
android:gravity="center_vertical"
android:text="#string/connect"
android:onClick="treatment_connect" />
<Button
android:id="#+id/b2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_action_computer"
android:gravity="center_vertical"
android:text="#string/read"
android:onClick="treatment_lecture" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/b3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_action_accept"
android:gravity="center_vertical"
android:text="#string/execution"
android:onClick="treatment_execution" />
<Button
android:id="#+id/b4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_action_warning"
android:gravity="center_vertical"
android:text="#string/disconnect"
android:onClick="treatment_disconnect" />
</LinearLayout>
</LinearLayout>
In the first and seconds layout you tried to call
status = (EditText) findViewById(R.id.text);
b1 = (Button) findViewById(R.id.b1);
before
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
So you tried to reference a Button and EditText contained in the PlaceholderFragment layout before you created the fragment.
The views are in the fragment layout. It only becomes a part of the activity view hierarchy after the fragment transaction has been run. Your pending fragment transaction is executed in activity super.onStart() which comes only after onCreate(). In essence, you're calling findViewById() too early in the first two versions. The third version works because the findViewById() is in the click handler and gets invoked when the fragment is attached to the activity.
Usually you'd call findViewById() to set up listeners and so on at the earliest possibility in fragment onCreateView(), just after the fragment layout is inflated.

Android app stop when is being to run

I'm new to android and java. this is my first app. an example of a book. I did all steps according the book. the app is going to increase the number by click on + button
this is my Java file :
package com.example.myprayercounter;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.os.Build;
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();
}
}
#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 {
int counter;
TextView tView;
Button btn;
public PlaceholderFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
counter = 0;
tView = (TextView)getActivity().findViewById(R.id.txt_textTwo);
btn = (Button)getActivity().findViewById(R.id.btn_buttonOne);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
tView.setText(" " + counter);
}
});
return rootView;
}
}
}
xml file :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fbfbdd"
android:gravity="center_horizontal"
android:orientation="vertical"
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.myprayercounter.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/txt_textOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="تعداد ذکرهای من"
android:textColor="#763f05"
android:textSize="20dp" />
<TextView
android:id="#+id/txt_textTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textColor="#763f05"
android:textSize="40dp" />
<Button
android:id="#+id/btn_buttonOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#763f05"
android:text="+"
android:textColor="#fbfbdd"
android:textSize="40dp" />
</LinearLayout>
I got this error at first run of the app :
What is my mistakes? and how i can fix them?
Thanks in advance
change:
tView = (TextView)getActivity().findViewById(R.id.txt_textTwo);
btn = (Button)getActivity().findViewById(R.id.btn_buttonOne);
to ( getActivity() --> rootView)
tView = (TextView)rootView.findViewById(R.id.txt_textTwo);
btn = (Button)rootView.findViewById(R.id.btn_buttonOne);
in PlaceholderFragment, your View is rootView and you need find your view from that

Categories

Resources