I have a search bar, a search button (as i just converted to using onKeyPress and haven't removed it yet), and a TextView.
It works well, except that each key press issues a new call to Search(), and the old call doesn't stop running. If i type too quickly or for too long, the app crashes. How do I better manage my threads or quit prior Search() executions when onKeyPress() fires?
Thanks!
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="corp.dtc.tel" >
<application
android:allowBackup="true"
android:icon="#mipmap/tel_ico"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".TEL_Main_Activity"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat.Light.DarkActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<EditText
android:id="#+id/search_box"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:hint="Enter Here"
android:inputType="text"
android:textSize="12sp"
android:layout_marginLeft="5dp"
android:layout_weight="1" />
<Button
android:id="#+id/search_button"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Search..."
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:onClick="Search"/>
</LinearLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:hint="List of Numbers will be here"
android:id="#+id/list_view"
android:maxLines="50"
android:scrollbars="vertical"
android:freezesText="true" />
</LinearLayout>
MainActivity.java
package corp.dtc.tel;
import android.content.Intent;
import android.graphics.Typeface;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.IOException;
public class TEL_Main_Activity extends ActionBarActivity {
TextView textView;
EditText editText;
Button button;
Employee[] list;
Employee[] employees;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getSupportActionBar();
actionBar.setLogo(R.mipmap.tel_ico);
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
LoadArray la = new LoadArray();
try {
employees = la.LoadArray(this, R.raw.droid);
} catch (IOException e) {}
setContentView(R.layout.activity_tel_main);
textView = (TextView) findViewById(R.id.list_view);
textView.setHorizontallyScrolling(true);
textView.setMovementMethod(new ScrollingMovementMethod());
textView.setTypeface(Typeface.MONOSPACE);
button = (Button) findViewById(R.id.search_button);
editText = (EditText) findViewById(R.id.search_box);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Search(findViewById(R.id.layout));
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onResume() {
super.onResume();
try {
//check if any view exists on current view
Button style = ((Button) findViewById(R.id.search_button));
} catch (Exception e) {
Intent i = new Intent();
i.setClass(getApplicationContext(), TEL_Main_Activity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}
#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_tel_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);
}
public void UpdateTextView () {
textView.setText(String.format("%-20s %10s %10s", list[0].name, list[0].number, list[0].support));
for (int x = 1 ; x < list.length & list[x] != null ; x++) {
textView.append("\n" +
(String.format("%-20s %12s %10s", list[x].name, list[x].number, list[x].support)));
}
}
public void Search(View view) {
textView.setText(null);
EditText line = (EditText) findViewById(R.id.search_box);
String[] tokens = line.getText().toString().split(" ");
if (tokens.length == 0)
{
//There was nothing in the search box.
}
else {
list = new Employee[50];
int listCtr = 0; //Keeps ctr for list[]
for (int dbCtr = 0 ; dbCtr < 5000 ; dbCtr++) {
System.out.println(dbCtr);
if (listCtr == 50)
break;
if (employees[dbCtr] == null)
{
//Should have less than 50 listed items and finished searching.
//Now it is okay to update the list view.
UpdateTextView();
break;
}
if (employees[dbCtr].contains(tokens))
{
list[listCtr] = employees[dbCtr];
listCtr++;
}
}
}
}
}
The App purpose: search through company employee listing, display results.(Must have less than 51 results to display)
I don't think that "the other search doesn't stop running" is really a good description of what's going wrong here. I don't see any "threads." I think that the problem is that you're attempting to do the search "on keyPress," therefore "with every keyPress."
A much better way to think of what you're trying to do here would be: "I want to automatically 'push the button' as soon as the user stops typing."
So, basically, when the user starts pressing keys, you'll start a timer (if such a timer isn't already running) set to go off in, say, 1/2-second. Then, in any case, you'll set a flag to true which indicates that "the user has recently pressed a key."
When the timer goes off, it checks to see if this flag is true. If so, it sets the flag to false and reschedules the timer to go-off again in another 1/2-second. Otherwise, it does what "pressing the button" used to do, then it will reset the (separate) flag that indicates that the timer is running.
As long as the user is pressing at least one key every 1/2 second, the timer will continue to reschedule itself (and, no one else will attempt to start the timer since they can see that the timer's running). Eventually, though, the timer will see that the key-has-been-pressed flag has remained false for half-a-second. That's when it "presses the button," causing the search to take place.
For a thorough solution, the timer-routine, after performing the search, would check the "key-has-been-pressed" flag once again. If it's still false, then the user really has stopped typing and it's time to present those search-results. Otherwise, the timer-routine should start rescheduling itself again.
Eventually, the user will stop typing. The timer will run the search, and, having done so, will see that the user still hasn't typed anything more. Results will then be displayed (for the first time).
Related
I'm new to programming. I've only learned the basics. Right now, I'm trying Android development out with Android Studio. My program simply has a title, and 2 buttons that are supposed to open a URL. There doesn't seem to be anything wrong with my code since nothing is underlined in red, so I don't understand why the layout model isn't showing up in the emulator.
What are some things that affects the emulator from running properly? I tried it on a windows computer and the emulator came after a minute or so. But nothing for the Mac. Anyway to speed up the process?
My code has no errors. Only problem I'm facing is the emulator not running in a timely manner. The app is supposed to open a URL for each of the 2 buttons in the browser.
Running on a Macbook Pro Mid 2010 13" with 8 GB RAM
**************************************Activity Code**********************************************
package com.first.bharg.firstapp;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
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;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonOnClick();
}
public void buttonOnClick(){
Button b = (Button) findViewById(R.id.button);
Button b1 = (Button) findViewById(R.id.button2);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i1 =
new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.yahoo.com"));
startActivity(i1);
}
});
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i2 =
new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(i2);
}
});
}
#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);
}
}
************************************************Layout******************************************
<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"
android:id="#+id/activity_main"
android:clickable="true"
android:background="#ffffa157"
android:focusable="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yahoo"
android:id="#+id/button"
android:layout_marginTop="107dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="51dp"
android:layout_marginStart="51dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Google"
android:id="#+id/button2"
android:layout_alignBottom="#+id/button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="42dp"
android:layout_marginEnd="42dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="First App"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
As far as windows concerns, I am afraid there's nothing you can do but wait for the emulator to load everything up. It always takes a lot of time, unless you use your own device (i.e connect your mobile phone to your laptop via USB).
For Mac it's a bit tricky. It's obviously not the only way, but I do suggest you to try another emulator if the one you actually have it's not working properly on it. It's gonna be faster than trying to solve whatever that's going on.
Apparently your code is ok. However if you are new to android I suggest you first get familiar with android activities life cycle before using intents. Here you may find some information related.
I've personally used eclipse's android SDK and it works fine on both OS.
I can't find a way how to make it work. So here it goes:
Application starts and I press Option menu and it offers me "Settings" option, and when I click it, it goes to layout called "help.xml" which shows me some text ...And in that layout I created a button which must return me to my activity ( the window which is shown when app starts)
I tried making a back button works but I failed cause I need for user to wait 30 seconds until the next image switch , and by making back button works hw would exploit it..
Sorry for my English, it is not my native language ;)
//** Povratak= return **//
MainActivity
package com.example.ams;
import java.util.Random;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
final Random rnd = new Random();
ImageView img = null;
Button btnRandom = null;
#Override
protected void onCreate(
final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.imgRandom);
btnRandom = (Button) findViewById(R.id.btnRandom);
}
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
public void clickHandler(final View v)
{
switch(v.getId())
{
case R.id.btnRandom:
{
if (!btnRandom.isEnabled())
{
return;
}
// I have 3 images named img_0 to img_2, so...
final String str = "img_" + rnd.nextInt(45);
img.setImageDrawable
(
getResources().getDrawable(getResourceID(str, "drawable",
getApplicationContext()))
);
btnRandom.setEnabled(false);
new CountDownTimer(30000, 1000) // Wait 30 secs, tick every 1 sec
{
#Override
public final void onTick(final long millisUntilFinished)
{
btnRandom.setText("Pričekaj do sljedeće kartice: " + (millisUntilFinished / 1000));
}
#Override
public final void onFinish()
{
btnRandom.setText("PROMIJENI KARTICU !");
btnRandom.setEnabled(true);
}
}.start();
break;
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
setContentView(R.layout.help);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
public void goBack(View v){
startActivity(new Intent(this, MainActivity.class));
}
#Override
public void onBackPressed() {
}
}
activity_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=".MainActivity"
android:background="#drawable/bgi"
>
<ImageView
android:id="#+id/imgRandom"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
/>
<Button
android:id="#+id/btnRandom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/imgRandom"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/imgRandom"
android:onClick="clickHandler"
android:text=" Promijeni karticu !"
android:textColor="#ffffff"
android:textSize="25dp" />
help.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="fill_parent"
android:orientation="vertical" >
<ScrollView
android:id="#+id/SCROLLER_ID"
android:layout_width="fill_parent"
android:layout_height="450dp"
android:fillViewport="true"
android:scrollbars="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:enabled="true"
android:freezesText="false"
android:overScrollMode="always"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbarStyle="insideOverlay"
android:scrollbars="vertical"
android:text="UVOD:Uz svaki scenario organizator moze odrediti da se koristi "AMS sustav" zbog realnijeg pristupa igri i viseg stupnja MILSIM-a. Organizator bira medice (ili kako se vec odredi) i oni moraju imati prilikom pocetka igre 46 kartica. />
</ScrollView>
<Button
android:id="#+id/button1"
android:layout_width="320dp"
android:layout_height="wrap_content"
android:text="Povratak" />
So I want to "Povratak" button works, it needs to send user to lets called it "main menu" (go back)..
EDITED AND FIXED:
have another question, is there any way to activity remebers the counting, because when you enter the app you click button which random generates a image from drawable and it doesn't let user to press that button for 30 secs.. the problem now is that when you are waiting for counter go to 0 you can easily press option menu, click settings and click "povratak" ,which starts activity all over again and the counter losses its point because user can now again press button that generates image (and I dont want that):/
In your help.xml for your Povratak button, use:
android:onClick="goBack"
Then in your Help.java, use:
public void goBack(View v){
setContentView(R.layout.activity_main);
}
there is two way to fix that problem ,the first one is that you need to call the finish methode in your call back methode of the button like this :
in your help.xml file :
in your class Help.java implement your methode as follow :
public void Povratak(View v)
{
finish();
}
if that does not fix your problem you can start an intent to go to your main activity, you have to change the implimentation of your call back methode :
public void Povratak(View v){
Intent intent=new Intent(this,MainActivity.class);
startactivity(intent);
finish();
}
hope this help ,for more information about activity and intent you can see this tutoriel
click here
Iam doing an android application. In that i want to create dynamic controls(edittext) like android core contacts application. After entering data in the ediitext i want to save the data to sqlite database by clicking a button named save. As Iam new to android i dont have any idea to create dynamic controls and storing its row values. Please help me if anybody knows.
My code:
package com.xiaochaoyang.dynamicviews;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
// Parent view for all rows and the add button.
private LinearLayout mContainerView;
// The "Add new" button
private Button mAddButton;
// There always should be only one empty row, other empty rows will
// be removed.
private View mExclusiveEmptyView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row_container);
mContainerView = (LinearLayout) findViewById(R.id.parentView);
mAddButton = (Button) findViewById(R.id.btnAddNewItem);
// Add some examples
inflateEditRow("Xiaochao");
inflateEditRow("Yang");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// TODO: Handle screen rotation:
// encapsulate information in a parcelable object, and save it
// into the state bundle.
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// TODO: Handle screen rotation:
// restore the saved items and inflate each one with inflateEditRow;
}
// onClick handler for the "Add new" button;
public void onAddNewClicked(View v) {
// Inflate a new row and hide the button self.
inflateEditRow(null);
//v.setVisibility(View.GONE);
}
// onClick handler for the "X" button of each row
public void onDeleteClicked(View v) {
// remove the row by calling the getParent on button
mContainerView.removeView((View) v.getParent());
}
// Helper for inflating a row
private void inflateEditRow(String name) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.row, null);
final ImageButton deleteButton = (ImageButton) rowView
.findViewById(R.id.buttonDelete);
final EditText editText = (EditText) rowView
.findViewById(R.id.editText);
if (name != null && !name.isEmpty()) {
editText.setText(name);
} else {
mExclusiveEmptyView = rowView;
//deleteButton.setVisibility(View.INVISIBLE);
}
// A TextWatcher to control the visibility of the "Add new" button and
// handle the exclusive empty view.
editText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
if (s.toString().isEmpty()) {
//mAddButton.setVisibility(View.GONE);
//deleteButton.setVisibility(View.INVISIBLE);
if (mExclusiveEmptyView != null
&& mExclusiveEmptyView != rowView) {
mContainerView.removeView(mExclusiveEmptyView);
}
mExclusiveEmptyView = rowView;
} else {
if (mExclusiveEmptyView == rowView) {
mExclusiveEmptyView = null;
}
mAddButton.setVisibility(View.VISIBLE);
deleteButton.setVisibility(View.VISIBLE);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
// Inflate at the end of all rows but before the "Add new" button
mContainerView.addView(rowView, mContainerView.getChildCount() );
}
}
My layouts:
Row Cointainer.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parentView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:orientation="vertical" >
<ScrollView
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/btnAddNewItem"
android:layout_width="21dp"
android:layout_height="wrap_content"
android:background="#drawable/transparent_background"
android:gravity="center_vertical"
android:onClick="onAddNewClicked"
android:layout_gravity="right"
android:paddingLeft="5dp"
android:text="+"
android:textColor="#android:color/black" />
</ScrollView>
</LinearLayout>
Row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal" >
<EditText
android:id="#+id/editText"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:singleLine="true"
android:ems="10"
android:hint="" >
<requestFocus />
</EditText>
<Spinner
android:id="#+id/spinnerCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.15"
android:entries="#array/categories"
android:gravity="right" />
<ImageButton
android:id="#+id/buttonDelete"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/content_remove"
android:background="#drawable/transparent_background"
android:contentDescription="#string/button_delete_row_description"
android:onClick="onDeleteClicked"/>
</LinearLayout>
First of all, while posting your question in SO, please show what have you tried so far, post your logcat if your app is getting force closed.
To work with controls, please refer to http://developer.android.com/reference/packages.html
There you find the methods available to work with controls.
Check this link: http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
It helps to learn and perform CRUD operations on SQLite Database.
At last, what you left with is, get data (or input) from controls, and insert into database.
Also, please go for googling.
An area which will present a predefined question
A button which will cause the answer to the question to be shown while leaving the question on the screen
An area which will present the answer
A button which will cause a transition to a screen that is formatted the same as this one, with the next question shown on it
A button which will cause the app to end (a transition to (3))
Only trying to get the transition from screen 1 to screen 2 to work with a different question/answer pair in its place with a button click. If there is anyway to do this other than switching the screens and activities which is the error, please let me know.
package com.example.androidassignment2;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
public class AndroidAssignment2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_assignment2_1);
Button next = (Button) findViewById(R.id.QButton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.android_assignment2_1, menu);
return true;
}
}
layout file
<LinearLayout 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:orientation="vertical" >
<TextView android:id="#+id/Questions"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:text="#string/Q2" />
<Button android:id="#+id/QButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_question" />
<Button android:id="#+id/AButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send" />
<TextView android:id="#+id/Answers"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:hint="#string/A2" />
<Button android:id="#+id/QuitButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_quit" />
</LinearLayout>
activity 1 file (incase needed)
package com.example.androidassignment2;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button next = (Button) findViewById(R.id.QButton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), AndroidAssignment2_1.class);
startActivityForResult(myIntent, 0);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Intent myIntent = new Intent(view.getContext(), AndroidAssignment2_1.class);
startActivityForResult(myIntent, 0);
You are starting a new activity, the most likely cause is that this is has not been declared in the Manifest.
In your AndroidManifest.xml`, you will need to add something like this:
<activity
android:name="your.package.name.AndroidAssignment2_1" />
This will reside inside of the <application> tag.
You are using startActivityForResult() but you don't override the onActivityForResult() method in your first Activity. You could change that to just use startActivity() and remove setResult() from your second Activity.
Button next = (Button) findViewById(R.id.QButton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), AndroidAssignment2_1.class);
startActivity(myIntent);
}
});
If this isn't your problem then please post logcat (always when you have a crash) and make sure the Activity is decalred.
As far as your other inquiry
If there is anyway to do this other than switching the screens and activities which is the error, please let me know.
If you are simply changing the text then you can stay in the same Activity and change the text of your TextViews. You could store questions and answers in something like Arrays or in a DB if you wish and keep a counter to where you are and change the text with each click.
Another option, which may go along with the first if you want, is to use a ViewPager
I am new to the Android development world and I've built a simple "Hello World" app. First, activity requests a text. When the "Go" button is clicked, the app launches the second activity displaying the input text.
If I click the HOME button and then click the application icon, the app launches the first activity again but if I press-hold the home button and click the icon from the "Recent apps" bar, it resumes the app where I left.
How do I avoid this?
I need my app to resume even if the launcher icon is clicked.
MainActivity.java,
package com.example.myfirstandroidapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view){
// Do something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.txtName);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
DisplayActivity.java,
package com.example.myfirstandroidapp;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class DisplayMessageActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_message, menu);
return true;
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_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=".MainActivity" >
<EditText
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/btnGo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/txtName"
android:layout_alignParentRight="true"
android:onClick="sendMessage"
android:text="Go!" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtName"
android:layout_alignParentTop="true"
android:layout_marginTop="18dp"
android:text="Please input your name:"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
activity_display_message.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=".DisplayMessageActivity" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
AndroidManifest.xml,
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstandroidapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="10" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.myfirstandroidapp.MainActivity"
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="com.example.myfirstandroidapp.DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.example.myfirstandroidapp.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstandroidapp.MainActivity" />
</activity>
</application>
</manifest>
Problem:
I'm not qualified to say this a bug, but there is a behaviour with release builds when starting the application from the launcher. It seems that instead of resuming the previous Activity, it adds a new Activity on top. There is a related bug report on this topic here.
Solution:
I'm working around this this by closing the Launcher Activity if it's not the root of the task, as a result the previous Activity in that task will be resumed.
if (!isTaskRoot()) {
finish();
return;
}
Issue for me was whenever app in installed by an apk with the click on 'Open' option it used to relaunch every time when we minimize it.
resolved it by
SplashActivity.java:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!isTaskRoot
&& intent.hasCategory(Intent.CATEGORY_LAUNCHER)
&& intent.action != null
&& intent.action.equals(Intent.ACTION_MAIN)) {
finish()
return
}
}