getSelectedItemPosition android - android

I have been racking my brain trying to figure out why this won't work. I need to return the index of a selected item in a spinner (4 spinners actually but can't even get one to work).
Here is the 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.agcinstruments.lab41.MainActivity"
android:background="#color/Navy">
<ImageView
android:id="#+id/resistor2"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:src="#drawable/resistor2"/>
<TextView
android:background="#color/Navy"
android:layout_marginTop="36dp"
android:layout_marginLeft="120dp"
android:layout_width="25dp"
android:layout_height="73dp"
/>
<TextView
android:background="#color/Navy"
android:layout_marginTop="36dp"
android:layout_centerHorizontal="true"
android:layout_width="25dp"
android:layout_height="73dp"
/>
<TextView
android:id="#+id/q"
android:background="#color/Navy"
android:layout_marginTop="36dp"
android:layout_marginLeft="208dp"
android:layout_width="25dp"
android:layout_height="73dp"
/>
<TextView
android:background="#color/Navy"
android:layout_marginTop="26dp"
android:layout_marginLeft="257dp"
android:layout_width="25dp"
android:layout_height="94dp"
/>
<Spinner
android:id="#+id/Spinner1"
android:layout_below="#+id/resistor2"
android:layout_width="85dp"
android:entries="#array/color_array1"
android:layout_height="wrap_content"
android:background="#color/White"/>
<Spinner
android:id="#+id/Spinner2"
android:layout_below="#id/resistor2"
android:layout_toRightOf="#+id/Spinner1"
android:layout_width="85dp"
android:entries="#array/color_array2"
android:layout_height="wrap_content"
android:background="#color/White"/>
<Spinner
android:id="#+id/Spinner3"
android:layout_below="#id/resistor2"
android:layout_toRightOf="#+id/Spinner2"
android:layout_width="85dp"
android:entries="#array/color_array3"
android:layout_height="wrap_content"
android:background="#color/White"/>
<Spinner
android:id="#+id/Spinner4"
android:layout_below="#id/resistor2"
android:layout_toRightOf="#+id/Spinner3"
android:layout_width="85dp"
android:entries="#array/color_array4"
android:layout_height="wrap_content"
android:background="#color/White"/>
<Button
android:id="#+id/calculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/Spinner4"
android:layout_centerHorizontal="true"
android:text="#string/calculate"
android:onClick="onClickCalculate"/>
<TextView
android:id="#+id/resultText"
android:layout_width="50dp"
android:layout_height="50dp"
android:textColor="#color/Red"
android:layout_below="#+id/calculate"
android:layout_centerHorizontal="true"
android:background="#color/White" />
<EditText
android:id="#+id/tolerance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/Red"/>
<EditText
android:id="#+id/ohm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/Red"/>
</RelativeLayout>
And here is the java code
package com.agcinstruments.lab41;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.app.ListActivity;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.server.converter.StringToIntConverter;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public Spinner Spinner1;
public Spinner Spinner2;
public Spinner Spinner3;
public Spinner Spinner4;
int value = 0 ;
int position = 0 ;
TextView resultText;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultText = (TextView) findViewById(R.id.resultText);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void onClickCalculate(View view) {
position = Spinner2.getSelectedItemPosition(); // This is the problem.I suspect the adaptor is not working.
value = position * 10;
resultText.setText(Integer.toString(value));
//resultText.setBackgroundColor()
}
public void resistorValue2(View view) {
value = value + (1);
}
public void resistorMultiplier(View view) {
value = value + (1);
}
public void resistorTolerance(View view) {
value = value + (1);
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.agcinstruments.lab41/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.agcinstruments.lab41/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
This is the strings.xml file i use to populate the array.
<resources>
<string name="app_name">lab4.1</string>
<string name="calculate">CALCULATE</string>
<string-array name="color_array1">
<item>BLACK</item>
<item>BROWN</item>
<item>RED</item>
<item>ORANGE</item>
<item>YELLOW</item>
<item>GREEN</item>
<item>BLUE</item>
<item>PURPLE</item>
<item>GREY</item>
<item>WHITE</item>
</string-array>
<string-array name="color_array2">
<item>BLACK</item>
<item>BROWN</item>
<item>RED</item>
<item>ORANGE</item>
<item>YELLOW</item>
<item>GREEN</item>
<item>BLUE</item>
<item>PURPLE</item>
<item>GREY</item>
<item>WHITE</item>
</string-array>
<string-array name="color_array3">
<item>BLACK</item>
<item>BROWN</item>
<item>RED</item>
<item>ORANGE</item>
<item>YELLOW</item>
<item>GREEN</item>
<item>BLUE</item>
<item>PURPLE</item>
<item>GREY</item>
<item>WHITE</item>
</string-array>
<string-array name="color_array4">
<item>BLACK</item>
<item>BROWN</item>
<item>RED</item>
<item>ORANGE</item>
<item>YELLOW</item>
<item>GREEN</item>
<item>BLUE</item>
<item>PURPLE</item>
<item>GREY</item>
<item>WHITE</item>
</string-array>
I am do not know a lot of JAVA this is a stumbling block on my road to enlightnment hopefully. Any help would be greatly appreciated. I have spent hours trying to figure out a solution.

Related

Android Search not accurate in passing another activity

Android Search is not accurate when passing another activity .
This is my app
This the main page
[Main] https://drive.google.com/open?id=0B2SE2JZYuezja2JqRHcycWdhWTA
When I search of a word the first array description will be display and it is not accurate description .
This is the same output to the one that I click
[Same output]https://drive.google.com/open?id=0B2SE2JZYuezjQmNFSm45RHloT3c
This is my codes
MainActivity.java
package com.skholingua.android.searchview;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater.Filter;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
public class MainActivity extends Activity implements
SearchView.OnQueryTextListener {
String[] stateList;
String[] anotherStringArray;
private SearchView searchView;
private ListView listView;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchView = (SearchView) findViewById(R.id.searchView1);
listView = (ListView) findViewById(R.id.listView1);
stateList = getResources().getStringArray(R.array.stateList);
anotherStringArray = getResources().getStringArray(R.array.anotherStringArray);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, stateList);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
// Sets the default or resting state of the search field.
// If true, a single search icon is shown by default and
// expands to show the text field and other buttons when pressed
//searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(this);
// Sets the hint text to display in the query text field
//searchView.setQueryHint("State Name");
int searchPlateId = searchView.getContext().getResources()
.getIdentifier("android:id/search_plate", null, null);
View searchPlateView = searchView.findViewById(searchPlateId);
if (searchPlateView != null) {
searchPlateView.setBackgroundColor(Color.TRANSPARENT);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String stateName = listView.getAdapter().getItem(position).toString();
// Put selected state to intent.
Intent intent = new Intent(MainActivity.this, NextActivity.class);
intent.putExtra("selectedState", stateName);
intent.putExtra("anotherStringArray",anotherStringArray[position]);
startActivity(intent);
}
});
}
#Override
public boolean onQueryTextChange(String newText) {
android.widget.Filter filter = adapter.getFilter();
if (TextUtils.isEmpty(newText)) {
filter.filter("");
} else {
filter.filter(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
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);
}
}
activity.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"
android:focusableInTouchMode="true"
tools:context="com.skholingua.android.searchview.MainActivity" >
<SearchView
android:id="#+id/searchView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:background="#drawable/search_view_border"
android:iconifiedByDefault="false"
android:padding="2dp"
android:queryHint="Search...."
android:layout_alignParentTop="true" >
</SearchView>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/searchView1"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
NextActivity.class
package com.skholingua.android.searchview;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class NextActivity extends Activity {
TextView t1,t2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.next);
t1 = (TextView) findViewById(R.id.name1);
t2 = (TextView) findViewById(R.id.name2);
Intent intent = getIntent();
String state_name= getIntent().getExtras().getString("selectedState");
String stateDescription= getIntent().getExtras().getString("anotherStringArray");
t1.setText(state_name);
t2.setText(stateDescription);
}
}
next.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:background="#00ffff"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
>
<LinearLayout
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:layout_margin="10dp"
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Word:"
android:typeface="serif"
android:textColor="#000"
android:textSize="19dp" />
<TextView
android:id="#+id/name1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text=""
android:textColor="#f00"
android:textSize="18dp"
android:typeface="serif" />
</LinearLayout>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:textColor="#000"
android:typeface="serif"
android:text="Definition:"
android:textSize="19dp" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/name2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#000"
android:padding="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:text=""
android:background="#fff"
android:textAppearance="?android:attr/textAppearanceMedium" />
</ScrollView>
</LinearLayout>
</RelativeLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">SearchView</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string-array name="stateList">
<item>Abstract Window Toolkit (AWT)</item>
<item>abstract</item>
<item>abstract class</item>
<item>abstract method</item>
<item>access control</item>
<item>ACID</item>
<item>activation</item>
<item>actual parameter list</item>
<item>alpha value</item>
</string-array>
<string-array name="anotherStringArray">
<item>A collection of graphical user interface (GUI) components that were implemented usingnative-platform versions of the components. These components provide that subset of functionalitywhich is common to all native platforms. Largely supplanted by the Project Swing component set.</item>
<item>A Java(TM) programming language keyword used in a class definition to specify that a class is not to be instantiated, but rather inherited by other classes. An abstract class can have abstract method that are not implemented in the abstract class, but in subclasses.</item>
<item>A class that contains one or more abstract methods, and therefore can never be instantiated. Abstract classes are defined so that other classes can extend them and make them concrete by implementing the abstract methods.</item>
<item>A method that has no implementation.</item>
<item>The methods by which interactions with resources are limited to collections of users or programs for the purpose of enforcing integrity, confidentiality, or availability constraints.</item>
<item>The acronym for the four properties guaranteed by transactions: atomicity, consistency, isolation,and durability.</item>
<item>The process of transferring an enterprise bean from secondary storage to memory.</item>
</string-array>
</resources>
I hope you will help me to fix this problem . Thank you.
Here is your solution.
First replace your main activity listView.setOnItemClickListener=> onItemClick method with below code
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String stateName = listView.getAdapter().getItem(position).toString();
int pos=0;
for(int i=0;i<stateList.length;i++)
{
if(stateList[i].equals(stateName))
{
pos=i;
break;
}
}
// Put selected state to intent.
Intent intent = new Intent(MainActivity.this, NextActivity.class);
intent.putExtra("selectedState", stateName);
intent.putExtra("anotherStringArray", anotherStringArray[pos]);
startActivity(intent);
}
});
And also make your stateList array and and anotherStringArray as same size in string.xml file.
<string-array name="stateList">
<item>Abstract Window Toolkit (AWT)</item>
<item>abstract</item>
<item>abstract class</item>
<item>abstract method</item>
<item>access control</item>
<item>ACID</item>
<item>activation</item>
<item>actual parameter list</item>
<item>alpha value</item>
</string-array>
<string-array name="anotherStringArray">
<item>A collection of graphical user interface (GUI) components that were implemented usingnative-platform versions of the components. These components provide that subset of functionalitywhich is common to all native platforms. Largely supplanted by the Project Swing component set.</item>
<item>A Java(TM) programming language keyword used in a class definition to specify that a class is not to be instantiated, but rather inherited by other classes. An abstract class can have abstract method that are not implemented in the abstract class, but in subclasses.</item>
<item>A class that contains one or more abstract methods, and therefore can never be instantiated. Abstract classes are defined so that other classes can extend them and make them concrete by implementing the abstract methods.</item>
<item>A method that has no implementation.</item>
<item>The methods by which interactions with resources are limited to collections of users or programs for the purpose of enforcing integrity, confidentiality, or availability constraints.</item>
<item>The acronym for the four properties guaranteed by transactions: atomicity, consistency, isolation,and durability.</item>
<item>The process of transferring an enterprise bean from secondary storage to memory.</item>
<item>Add your text here</item>
<item>Add some other text here</item>
</string-array>

Android App crashes on Button click

I have made a simple application which takes two numbers and add them but on button click my app crashes every time. I am new to android, Id really appreciate if someone can help me with this
<?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:id="#+id/activity_main"
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.ornadmin.myapplication.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="21dp"
android:layout_marginTop="29dp"
android:id="#+id/editText"
android:hint="number 1" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:layout_below="#+id/editText"
android:layout_alignEnd="#+id/editText"
android:layout_marginTop="32dp"
android:id="#+id/editText2"
android:hint="number 2" />
<TextView
android:text="Result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="13dp"
android:id="#+id/textView"
android:layout_below="#+id/editText2"
android:layout_alignStart="#+id/editText2"
android:layout_marginTop="57dp"
android:textSize="30sp" />
<Button
android:text="sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:onClick="onButtonClick (MainActivity)"
android:layout_alignTop="#+id/textView"
android:layout_alignStart="#+id/textView"
android:layout_marginTop="97dp" />
</RelativeLayout>
Main Activity
package com.example.ornadmin.myapplication;
import android.app.Activity;
import android.app.IntentService;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends Activity {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void onButtonClick(View v) {
EditText e1 = (EditText)findViewById(R.id.editText);
EditText e2 = (EditText)findViewById(R.id.editText2);
TextView t1 = (TextView)findViewById(R.id.textView);
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int sum = num1 + num2;
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
}
LOG
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ornadmin.myapplication, PID: 3812
java.lang.IllegalStateException: Could not find method onButtonClick (MainActivity)(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.widget.Button with id 'button'
at android.view.View$DeclaredOnClickListener.resolveMethod(View.java:4479)
at android.view.View$DeclaredOnClickListener.onClick(View.java:4443)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Application terminated.
the problem is in this line
android:onClick="onButtonClick (MainActivity)"
the correction would be like this
android:onClick="onButtonClick"

How to enable disabled submit button after any one of the radioButton of RadioGroup?

Here I am trying to make an app where I have 4 options on my MainActivity Screen, User should able to Click on submit only when one of the radio button is selected.(OTHERWISE NOT), which help me to avoid null pointer Exception while submitting the option.
============================= MainActivity.java====================
package com.Xapp.radiobuttondemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
public class MainActivity extends Activity {
RadioGroup radioGroup;
Button submit;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submit=(Button) findViewById(R.id.submit);
radioGroup=(RadioGroup) findViewById(R.id.radioOptions);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
boolean is=group.isActivated(); //This must be something else,Please suggest
if(is==true)
{
submit.setEnabled(true);
}
else
{
submit.setEnabled(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;
}
}
==============================activity_main.xml============================
<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: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" >
<RadioGroup
android:id="#+id/radioOptions"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/option1" />
<RadioButton
android:id="#+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/option2" />
<RadioButton
android:id="#+id/radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/option3" />
<RadioButton
android:id="#+id/radioButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/option4" />
</RadioGroup>
<Button
android:id="#+id/submit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:enabled="false"
android:text="Submit" />
</LinearLayout>
=======================================strings.xml=================================
<string name="app_name">RadioButtonDemo</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Select One</string>
<string name="option1">Red</string>
<string name="option2">Blue</string>
<string name="option3">Green</string>
<string name="option4">Pink</string>
try this
if (checkedId == R.id.radioButton1) {
//do something
} else if (checkedId == R.id.radioButton2) {
//do something
Actually I think, that if you receive a OnCheckChanged event, is because one of the radiobutton was selected.
OnCheckChanged -> "Called when the checked radio button has changed."
So there is no need to check, because one of then was already selected.
You don't need to do this:
if(is==true)
{
submit.setEnabled(true);
}
else
{
submit.setEnabled(false);
}
Because on a radiogroup once you select one of then, then always there will be one selected.
First of all you are writing Button ENABLE OR DISABLE code inside CheckChanged Event of Radiogroup which will never call if any radio button is not selected.
Updated code:::::
try the below code for what you want.
// get selected radio button from radioGroup
int selectedId = radioOptions.getCheckedRadioButtonId();
if(selectedId == null || selectedId < 1)
{
submit.setEnabled(false);
}
else
{
submit.setEnabled(true);
}
Hope this helps you.

write multiple strings to a file and add a new line

I'm building a basic app that you choose from a spinner, select a color and click save. If the color you're looking for isn't in the spinner, you press a button and you can type it in to the EditText.
I'm trying to make it so I can write both the chosen spinner/edittext color and the date inside of the "colors.txt" file. at the moment, there are no errors but when i launch the app on my android it instantly crashes.
Colorchooser.java
package com.example.scalendar;
import java.io.IOException;
import java.io.OutputStreamWriter;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
public class Colorchooser extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colorchooser);
}
public void writetoFile(String str) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("colors.txt", Context.MODE_PRIVATE));
outputStreamWriter.write("colorstring , datestring");
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.colorchooser, menu);
return true;
}
}`
And here is my Strings.XML file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">SCalendar</string>
<string name="action_settings">Settings</string>
<string name="color_prompt">What was todays color?</string>
<string name="SaveButtonText">Save To Calendar</string>
<string name="textfieldhint">Enter color</string>
<string name="otherbuttontext">Color not listed</string>
<string name="othercolorexplanationtext">Dont see the color here? Click the button below and type it yourself.</string>
<string-array name="color_arrays">
<item>Select a color:</item>
<item>Purple</item>
<item>Orange</item>
<item>Green</item>
<item>Red</item>
<item>Blue</item>
<item>Pink</item>
<item>Brown</item>
<item>Yellow</item>
<item>Black</item>
<item>White</item>
</string-array>
<string name="colorstring">
colorSpinner = findViewById(R.id.colorSpinner)
colorSpinner.getSelectedItem().toString()
</string>
<string name="datestring">
SimpleDateFormat formatter = new SimpleDateFormat("dd_MM_yyyy");
Date now = new Date();
String fileName = formatter.format(now).toString();
</string>
</resources>`
And here's my Mainactivity.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="Colorchooser" >
<Spinner
android:id="#+id/colorSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:entries="#array/color_arrays"
android:prompt="#string/color_prompt" />
<TextView
android:id="#+id/othercolorexplaination"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/colorSpinner"
android:layout_below="#+id/colorSpinner"
android:layout_marginTop="15dp"
android:text="#string/othercolorexplanationtext"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/ButtonSave"
style="#style/AppTheme"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/othercolorexplaination"
android:layout_alignParentBottom="true"
android:layout_marginBottom="62dp"
android:onClick="writetoFile(String getcolor)"
android:text="#string/SaveButtonText" />
<EditText
android:id="#+id/othercolor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ButtonSave"
android:layout_below="#+id/otherbutton"
android:layout_marginTop="42dp"
android:ems="10"
android:focusable="false"
android:hint="#string/textfieldhint"
android:inputType="textEmailAddress" >
</EditText>
<Button
android:id="#+id/otherbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/othercolorexplaination"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:onClick="othercolor.focusableInTouchMode(true)"
android:text="#string/otherbuttontext" />
</RelativeLayout>`
It seems you have some major misunderstandings on the relation between Java strings vs string variables, and string variables vs string resources:
This:
outputStreamWriter.write("colorstring , datestring");
Will always write "colorstring, datestring" to your file, so the file will look like:
colorstring, datestring
colorstring, datestring
colorstring, datestring
You cannot expect Java code in your string resources to be executed:
<string name="colorstring">
colorSpinner = findViewById(R.id.colorSpinner)
colorSpinner.getSelectedItem().toString()
</string>
Strings in your resources are Constants. There is no way to change them at run time.

How to change textView to a #string and raising

so what i am tring to do is, i am having a book like-app, and want to setup a button when click it change the textview to a string in the #string rec. but in a different way
i will put the code just a moment, lets say i have a string in #string that is NH1,NH2,NH3
i can do for button View.setText(R.string.NH1); that will work but i want to create a counter and make it so every time clicked counter++ and want it to be like this View.setText(R.string.NH+counter); if you know what i mean so each time it clicked to goes to next #string without changing layout every time and without an array because the paragraph are very long
also if i have NH1-10 and the counter did not stop and still goes on what will i do.
if you are sill here thank you for reading.
XML(sheetpaper)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="496dp"
android:background="#drawable/bg1"
android:gravity="top"
android:orientation="vertical"
android:weightSum="100" >
<Button
android:id="#+id/bPrev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="51dp"
android:background="#android:color/transparent"
android:text=" " />
<TextView
android:id="#+id/tvHadith"
android:layout_width="310dp"
android:layout_height="210dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="64dp"
android:text="#string/NH1"
android:textColor="#android:color/white" />
<Button
android:id="#+id/bNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/bPrev"
android:layout_alignBottom="#+id/bPrev"
android:layout_alignRight="#+id/tvHadith"
android:background="#android:color/transparent"
android:gravity="center"
android:text=" " />
"
</RelativeLayout>
</LinearLayout>
Java (Nawawi)
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Nawawi extends Activity {
private static final String NH = null;
Button Next;
Button Prev;
TextView View;
int counter = 0;
String H=NH;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sheetpaper);
Next = (Button) findViewById(R.id.bNext);
Prev = (Button) findViewById(R.id.bPrev);
View = (TextView) findViewById(R.id.tvHadith);
Next.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter++;
View.setText(R.string.H);
}
}); Prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter--;
View.setText(R.string.);
}
});
}
}
You could do this by creating an XML string array, so your strings will still be referenced in resources, but you'll be able to loop through them.
Something like this, in values/strings.xml:
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
</string-array>
And then in Activity:
Resources res = getResources();
final String[] planets = res.getStringArray(R.array.planets_array);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (counter < planets.length) {
textView.setText(planets[counter]);
counter++;
}
}
});
Be sure to check the counter against arrays length, otherwise you will get an IndexOutOfBoundsException.

Categories

Resources