Android button returning to activity from layout - android

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

Related

OnClick Button action in Custom ListView

Actually, I was trying to implement a shopping cart using Android Studio. There is a custom list view in the main page included an "Add to Cart" button. So, whenever I click on the button the item must be added in the cart. But, I have no idea. Please guys, help me out. I'm a newbie.
Here is the Product Adapter
package com.example.raswap.octomatic;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by aurora on 22/03/16.
*/
public class Pro_Adapter extends ArrayAdapter {
List list = new ArrayList();
public Pro_Adapter(Context context, int resource) {
super(context, resource);
}
static class DataHandler{
ImageView img;
TextView p_name;
TextView b_name;
TextView price;
Button b_atc;
}
#Override
public void add(Object object) {
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
DataHandler handler;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.e_layout, parent, false);
handler = new DataHandler();
handler.img = (ImageView)row.findViewById(R.id.pro_image);
handler.p_name = (TextView)row.findViewById(R.id.pro_name);
handler.b_name = (TextView)row.findViewById(R.id.brand);
handler.price = (TextView)row.findViewById(R.id.pricing);
handler.b_atc = (Button)row.findViewById(R.id.atc);
row.setTag(handler);
}else{
handler = (DataHandler)row.getTag();
}
Product_data_provider dataProvider;
dataProvider = (Product_data_provider)this.getItem(position);
handler.img.setImageResource(dataProvider.getPro_img_resource());
handler.p_name.setText(dataProvider.getPro_name());
handler.b_name.setText(dataProvider.getBr_name());
handler.price.setText(dataProvider.getPricing());
return row;
}
}
Here is the Main Activity class:
package com.example.raswap.octomatic;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class E_shop extends Activity {
ListView listView;
int[] emage = {R.drawable.gb32, R.drawable.tb1, R.drawable.dvd};
String[] pro_name;
String[] br_name;
String[] price;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_e_shop);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_titlebar);
View z = findViewById(R.id.oct_logo);
z.setClickable(true);
z.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(E_shop.this, MainActivity.class));
}
});
View x = findViewById(R.id.for_user_info);
x.setClickable(true);
x.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(E_shop.this, UserInformation.class));
}
});
Pro_Adapter adapter = new Pro_Adapter(getApplicationContext(),R.layout.e_layout);
ListView listView = (ListView)findViewById(R.id.e_list);
listView.setAdapter(adapter);
pro_name = getResources().getStringArray(R.array.nameOfProduct);
br_name = getResources().getStringArray(R.array.branding);
price = getResources().getStringArray(R.array.pricing);
int i = 0;
for(String pro: pro_name){
Product_data_provider dataProvider = new Product_data_provider(emage[i],pro, br_name[i], price[i]);
adapter.add(dataProvider);
i++;
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:
Intent newActivity = new Intent(E_shop.this, Product_Desc.class);
newActivity.putExtra("pro_emage",R.drawable.gb32);
newActivity.putExtra("title","Kingston 32Gigs Pen Drive");
newActivity.putExtra("desc", "Store a huge collection of data in a generous 32GB space of this Kingston pen drive and carry it along. It has a sleek design with a smooth finish, and a pretty-looking charm bearing the Kingston logo dangles from this pen drive. Featured in a size of 3 x 1.2 x 0.5 cm, this Kingston 32GB pen drive weighs only 5g. You can easily tuck it away in the pocket of your laptop bag, purse or your shirt pocket with its compact and light weight.");
startActivity(newActivity);
break;
case 1:
Intent Activity1 = new Intent(E_shop.this, Product_Desc.class);
Activity1.putExtra("pro_emage",R.drawable.tb1);
Activity1.putExtra("title","Samsung 1TB Portable Hard Disk");
Activity1.putExtra("desc", "From college to school students, all deal with transferring files, software and applications from various systems that are large in size. With the advancements in media technology on the rise, we require a large amount of space to store our data. Even most of the growing companies require a secure means of storing data for analyses. All of this embarks on the need for a reliable hard disk. The top quality brand of Samsung brings you this sleek and portable hard drive ideally designed for continuous usage. Now you can store 2TB of diverse data easily. This, sleek hard disk comes with 36 months warranty. The body of this drive has a smart construction. The Samsung external hard disk comes in a sturdy design.");
startActivity(Activity1);
break;
case 2:
Intent Activity2 = new Intent(E_shop.this, Product_Desc.class);
Activity2.putExtra("pro_emage", R.drawable.dvd);
Activity2.putExtra("title", "A pack of 50 DVD's");
Activity2.putExtra("desc", "Create and store digital video, audio and multimedia files, Stores up to 4.7GB or more than 2 hours of MPEG2 video, Has 7 times the storage capacity of a CDR, Sony branded 16X DVD-R in a 100 pack Spindle, AccuCORE Technology");
startActivity(Activity2);
break;
}
}
#SuppressWarnings("unused")
public void onClick(View v){
}
});
}
}
Here is the Product Data Provider Class:
package com.example.raswap.octomatic;
/**
* Created by aurora on 22/03/16.
*/
public class Product_data_provider {
private int pro_img_resource;
private String pro_name;
private String br_name;
private String pricing;
public int getPro_img_resource() {
return pro_img_resource;
}
public Product_data_provider(int pro_img_resource, String pro_name, String br_name, String pricing){
this.setPro_img_resource(pro_img_resource);
this.setPro_name(pro_name);
this.setBr_name(br_name);
this.setPricing(pricing);
}
public void setPro_img_resource(int pro_img_resource) {
this.pro_img_resource = pro_img_resource;
}
public String getPro_name() {
return pro_name;
}
public void setPro_name(String pro_name) {
this.pro_name = pro_name;
}
public String getBr_name() {
return br_name;
}
public void setBr_name(String br_name) {
this.br_name = br_name;
}
public String getPricing() {
return pricing;
}
public void setPricing(String pricing) {
this.pricing = pricing;
}
}
Now, Custom ListView XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/oneL"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/pro_image"
android:src="#drawable/gb32"
android:layout_width="160dp"
android:layout_height="match_parent" />
<LinearLayout
android:background="#afeeee"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Product Name"
android:id="#+id/pro_name"
android:textColor="#000"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Branding"
android:id="#+id/brand"
android:textColor="#000"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Price"
android:textColor="#000"
android:id="#+id/pricing"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to Cart"
android:id="#+id/atc" />
</LinearLayout>
</LinearLayout>
<View
android:layout_below="#+id/oneL"
android:layout_width="match_parent"
android:layout_height="5dp"
android:background="#000"/>
</RelativeLayout>
</RelativeLayout>
and finally the main layout XML file:
<?xml version="1.0" encoding="utf-8"?>
<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.raswap.octomatic.E_shop">
<ListView
android:id="#+id/e_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
Add your button's OnClick event in the Pro_Adapter's getView() methond as you do normally in your activities' onCreate() method.
Implement OnClickListener in your adapter class and get the Button click first and do the other task when you get the event. If you need the call back to your main activity class implement your own listener.follow the link enter link description here
Add the onClickListener to your Button in getView() of your ListAdapter.
If you want handle event click button in row, i'm think you should answer set button onclick event for every row of listview
you can try this.
Change in custom Listview xml file.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to Cart"
android:onClick="AddCart"
android:id="#+id/atc" />
In MainActivity
public void AddCart(View v)
{
LinearLayout vwParentRow = (LinearLayout)v.getParent();
TextView child = (TextView)vwParentRow.getChildAt(0);
child.setText("I've been clicked!");
vwParentRow.refreshDrawableState();
}

Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference

Basically this app is supposed to ask for your name, with an option to save, which when click, an alert dialog pops up and asks 'are you sure?', when yes is clicked, it should say 'welcome + whatever name put'. my problem is that the app keeps shutting down before it says welcome. I declared the string as userName and ran it without any function to the string, and it just said 'welcome, null'.
but when i did
userName=editText.getText().toString();
the app shut down immediately. Please HELP I'm out of ideas.
the page which calls the welcome page works fine, but the welcome.java is the file with the issue.
public class Welcome extends Activity {
String userName;
final EditText editText=(EditText)findViewById(R.id.editText);
final TextView textView=(TextView)findViewById(R.id.textView);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
final TextView textView=(TextView)findViewById(R.id.textView);
final EditText editText=(EditText)findViewById(R.id.editText);
userName=editText.getText().toString();
textView.setText(String.format("Welcome, %s.", userName));
}
}
The logcat is basically the title, giving an error to the following line:
userName=editText.getText().toString();
PS I've moved that line of code before and after onCreate and it still gave errors
My MainActivity.java is
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.View;
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] menu={"User Preferences","Animation","Browser","Media","Take Picture"};
setListAdapter(new ArrayAdapter<String>(this,R.layout.activity_main,R.id.options, menu));
}
protected void onListItemClick(ListView l, View v, int position, long id){
switch(position){
case 0:
startActivity(new Intent(MainActivity.this,userPreferences.class));
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
}
}
#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);
}
}
My activity_main.xml is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/ic_launcher_sf"
android:layout_width="50px"
android:layout_height="50px"
android:layout_marginLeft="4px"
android:layout_marginRight="10px"
android:layout_marginTop="2px">
</ImageView>
<TextView
android:id="#+id/options"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/travel"
android:textSize="25sp"></TextView>
My welcome.xml is
<?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">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:textSize="30dp" />
my userpreferences.java
public class userPreferences extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userpreferences);
Button save=(Button)findViewById(R.id.button);
save.setOnClickListener(new View.OnClickListener() {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(userPreferences.this);
#Override
public void onClick(View v) {
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Are you sure you want to save?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(userPreferences.this,Welcome.class));
}
});
alertDialog.setNegativeButton("No", null);
alertDialog.show();
}
});
}
}
and my user preferences.xml file
<?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:weightSum="1">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_weight="1"
android:hint="Enter Your Name"
android:textSize="20dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="0dp"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="#+id/button"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true" />
The problem lies in both of these
final EditText editText=(EditText)findViewById(R.id.editText);
final TextView textView=(TextView)findViewById(R.id.textView);
Do not do findViewById without setContentView() called, or especially outside the methods. Make it:
private EditText editText;
private TextView textView;
And also:
inside your onCreate, you don't have to redeclare the views just do:
textView=(TextView)findViewById(R.id.textView);
editText=(EditText)findViewById(R.id.editText);
Plus: Add an EditText on your welcome.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:hint="THIS IS AN EDITTEXT" />
The problem is that you have 2 different views in 2 different xml's called from one single activity. Which is why you get the nullpointerexception. so instead pass the context as an extra via an intent to the required activity and implement it in the findviewbyid method.

I created an Android application with two activities, but cannot switch back from the second activity to the first

I created an Android application with two activities, but somehow the buttons on the second activity do not seem to work properly. The button on the first activity (a map activity and a button to add infromat which takes users to the second activity with an information entry screen) works fine, neither button on the second activity seems to have any effect... I can't even get an OnClick Toast message to work.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback , LocationListener {
public void AddMapInfo(View view) {
Intent intent = new Intent(this, InformationInputActivity.class);
LatLng providedLocation = current;
Bundle args = new Bundle();
args.putParcelable("provided_location", providedLocation);
intent.putExtra("bundle", args);
startActivityForResult(intent, 1);
}
public void onActivityResult (int requestCode, int resultCode, Intent data){
Toast.makeText(this, "back with cheese!", Toast.LENGTH_LONG).show();
if (requestCode != 1){
Toast.makeText(this, "Oops... This shouldn't happen", Toast.LENGTH_LONG).show();
}
else{
setContentView(R.layout.activity_maps);
InformationPoint informationPoint = (InformationPoint) data.getSerializableExtra("information_point");
informationPoint.display(mymap);
}
}
}
The second activity brings on the layout for the screen, and it sets the proper options for the EditText field, so I know it gets control... but that's about it. There is no Toast message from any of the methods (I still get the Toasts when the location update info is received on the first activity instead), and neither the radio button or submit buttons seem to work, I'm also not getting the result and control back in the first activity. (Previously, I used to be able to get a Toast on ever on checked option on the radio button, but now that doesn't seem to work either). Trying to send the activity result aborts the application (since I added finish() to the second activity).
/* java */
package com.example.m.googlemapappfirst;
import android.content.Intent;
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.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
import org.w3c.dom.Text;
public class InformationInputActivity extends ActionBarActivity {
EditText editText;
String content = "";
LatLng providedLocation;
public InfoType infoType = InfoType.NO_INFO;
InformationPoint informationPoint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information_input);
Intent intent = getIntent();
Bundle bundle = getIntent().getParcelableExtra("bundle");
providedLocation = bundle.getParcelable("provided_location");
String message = String.valueOf(providedLocation);
editText = (EditText)findViewById(R.id.description);
editText.setHorizontallyScrolling(false);
editText.setMaxLines(5);
Toast.makeText(this, "enter cheese info", Toast.LENGTH_LONG);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
Toast.makeText(this,"you selected your cheese", Toast.LENGTH_LONG);
}
#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_information_input, 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 AddPictureHandler(View view){
Toast.makeText(this, "i like to take pictures of cheese", Toast.LENGTH_LONG).show();
}
public void SubmitHandler(View view){
content = editText.getText().toString();
Toast.makeText(this, "add cheese info", Toast.LENGTH_LONG).show();
if(infoType == InfoType.NO_INFO){
Toast.makeText(this, "Please select an Information type", Toast.LENGTH_LONG).show();
}
else if(content.equals("")){
Toast.makeText(this, "Please write a description", Toast.LENGTH_LONG).show();
}
informationPoint = new InformationPoint(providedLocation, infoType, content);
Intent returnIntent = new Intent(this, MapsActivity.class);
returnIntent.putExtra("information_point", informationPoint);
this.setResult(1, returnIntent);
finish(); /* added after original post, this makes app crash consistently */
}
}
Here's the xml layout file for the second activity:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.m.googlemapappfirst.InformationInputActivity">
<TextView android:text="#string/instructions"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="#+id/radio_swiss"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/swiss"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_american"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/american"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_gruyere"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/gruyere"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_cheddar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cheddar"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
<TextView android:text="#string/instructions2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/description"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_weight="1"
android:hint="#string/type_here"
android:inputType="text"
android:imeOptions="actionDone"
android:maxLines ="4"
android:maxLength ="2000"
android:scrollHorizontally="false"
/>
<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="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="horizontal">
<Button
android:id="#+id/take_picture_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Picture"
android:onClick="AddPictureHandler" />
<Button
android:id="#+id/submit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Report Information"
android:onClick="SubmitHandler" />
</LinearLayout>
I didn't see any problem but missing invocation of show() after toast creation, just like this:
Toast.makeText(this, "Oops... This shouldn't happen", Toast.LENGTH_LONG).show();

Android: Issuing search method too frequently causing crashes

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).

How to change click event in android

Its been few days over to me, learning Android App development :
I have created an APK which is having two buttons (largeButton & smallButton) if you click on these button test will large and small accordingly.
What i am trying to do :
When i click second time button should change in previous mode i.e Vice Versa should happen.
Here is my code :
mainActivity:
package com.firstapk.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button largButton;
Button smallButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
largButton = (Button) findViewById(R.id.largbutton);
smallButton = (Button) findViewById(R.id.smallbutton);
}
#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;
}
//public void getDisplay(View view){
public void largebuttonclick(View view){
try{
largButton.setTextSize(40);
}catch(Exception e){
Log.d("TestApp", e.getMessage());
}
}
//}
public void smallButtonClick(View view){
try{
smallButton.setTextSize(5);
}catch(Exception e){
Log.d("TestApp",e.getMessage());
}
}
}
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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/largbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="96dp"
android:onClick="largebuttonclick"
android:text="#string/button_large" />
<Button
android:id="#+id/smallbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="320dp"
android:onClick="smallButtonClick"
android:text="#string/button_small" />
</RelativeLayout>
As you did now it's right, if he click "Max size" he will see max size;
So maybe you want to use only one button which works like (+ and -)? If yes use one onClick and a boolean variable to save the current status (max size, small size).
private boolean maxSize; // false if small, true if max
public void onChangeSize(View view)
{
if (maxSize)//max->small
{
smallButton.setTextSize(5);
}
else//small->max
{
largButton.setTextSize(40);
}
maxSize = !maxSize;
}
Then android:onClick="onChangeSize" in the two buttons xml.
You could use the same approch for your current code, but it will work in the same way.

Categories

Resources