Function calling wrong class - java

I am trying to use an intent to start two different classes in which I change either the text size or text colour of an entered message. Starting these classes is triggered by two different button push events in android studio. However, only the TextSize class is being started no matter what button I push and I cannot see the reason why. Below I have the problem activities class code and xml code
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
public static final String EXTRAA_MESSAGE ="message2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void changeText(View v){
EditText messageView = (EditText)findViewById(R.id.message);
String messageText = messageView.getText().toString();
Intent result = new Intent(this, TextSize.class);
result.putExtra("message",messageText);
startActivity(result);
}
public void changeColour(View v){
EditText messageView = (EditText)findViewById(R.id.message);
String messageText = messageView.getText().toString();
Intent result = new Intent(this, ColourChange.class);
result.putExtra("message",messageText);
startActivity(result);
}
My XML File
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView2"
android:layout_alignParentTop="true"
android:layout_marginTop="14dp" />
<EditText
android:id="#+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="28dp"
android:ems="10"
android:layout_below="#+id/textView2"
android:layout_alignParentStart="true" />
<Button
android:text="Change Colour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Colour"
android:onClick="changeColour"
android:layout_centerVertical="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="36dp"
android:onClick="changeText"
android:text="Change Text Size"
android:layout_alignBaseline="#+id/Colour"
android:layout_alignBottom="#+id/Colour"
android:layout_alignParentEnd="true"
android:layout_marginEnd="33dp"
android:id="#+id/TextSize" />

In Android just implements the OnClickListener for you when you define the android:onClick="someMethod" attribute.
you can implemented just different way.
Button btnColour = (Button) findViewById(R.id.Colour);
btnColour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// call your method here
changeColour(v);
}
});
// your method code
public void changeColour(View v) {
// your method code
}
As You doing
check your xml file that have you define context with parent layout or not
tools:context="com.example.YourActivity"
// com.example.YourActivity should be your activity with package name

Related

Android Studio : When ever i run my app, it says Unfortunately app has stopped [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 4 years ago.
I am trying to get an input from user and then covert it into double and divide it by 1000 and then set the value in a textview but i while running the app, the app closes and says Unfortunately the app has stopped.
Here's my MainActivity.java file :
package com.blogspot.techtutorialsajen.androiddevelopmentpractice;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity{
private Button btn1;
private EditText get;
private TextView result;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.btn1);
result = (TextView)findViewById(R.id.result);
get = (EditText)findViewById(R.id.get);
final double value = Double.parseDouble(get.getText().toString()) / 1000;
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
result.setText(String.valueOf(value));
}
});
}
}
And My activity_main.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">
<EditText
android:id="#+id/get"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="#string/enter_a_number"
android:layout_marginTop="48dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/btn1"
android:text="#string/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/result"
android:layout_centerHorizontal="true"
android:layout_marginBottom="28dp" />
<TextView
android:id="#+id/result"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textSize="20pt"
android:text="0"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Well, Your app is crashes because of java.lang.RuntimeException:java.lang.NumberFormatException: Invalid double: ""
that means you are trying to convert empty string to Double.
So, Because the EditText is empty your app is crashes and I have re-write your code so that you can copy-paste.
Here is your MainActivity.Java
package com.blogspot.techtutorialsajen.androiddevelopmentpractice;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity{
private Button btn1;
private EditText get;
private TextView result;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.btn1);
result = (TextView)findViewById(R.id.result);
get = (EditText)findViewById(R.id.get);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (get.getText().toString().isEmpty()) {
Toast.makeText(MainActivity .this, "Please input something", Toast.LENGTH_LONG).show();
} else {
final double value = Double.parseDouble(get.getText().toString()) / 1000;
result.setText(String.valueOf(value));
}
}
});
}
}
and here is your activity_main.XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<EditText
android:id="#+id/get"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="#string/enter_a_number"
android:layout_marginTop="48dp"
android:inputType="number"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/btn1"
android:text="#string/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/result"
android:layout_centerHorizontal="true"
android:layout_marginBottom="28dp" />
<TextView
android:id="#+id/result"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textSize="20pt"
android:text="0"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
I have added android:inputType="number" property to your EditText so that, now on, it will only take Number from the user.
From your xml file and activity code, it clearly says your edittext is empty while launching app.
And you are using this code in oncreate()
final double value = Double.parseDouble(get.getText().toString()) / 1000;
which throws java.lang.NumberFormatException: empty String
You can change your code like,
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!get.getText().toString().isEmpty)
final double value = Double.parseDouble(get.getText().toString()) / 1000;
result.setText(String.valueOf(value));
}
});
}

Unable to make EditText multi-line

I am making an Android app for storing notes. I have made my editText behave like textView before button click. Clicking on edit button makes the editText take value. Now problem arises when i save that value and when it is displayed. EditText doesnt come in multi-line as I want but in a single line.
I declared the inputType property of editText as multi-line in xml file but in the code upon initialising the editText i set its inputType property as null in an attempt to make it both null and multi-line but alas! It doesn't happen.
Below is my xml and java code:
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:theme="#style/AppTheme.AppBarOverlay"
android:background="#color/colorToolBar"
android:id="#+id/idToolbarNoteDetails"
android:padding="10dp"/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/idFloatingActionButtonEdit"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
app:srcCompat="#android:drawable/ic_menu_edit"
android:layout_margin="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Colors: "
android:textStyle="italic"
android:visibility="invisible"
android:id="#+id/idTextViewColors"
android:layout_below="#+id/idToolbarNoteDetails"
android:layout_margin="10dp"
android:textSize="15dp"/>
<TextView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/idColorRed"
android:visibility="invisible"
android:layout_margin="10dp"
android:layout_below="#+id/idToolbarNoteDetails"
android:layout_toRightOf="#+id/idTextViewColors"
android:background="#drawable/textview_circle_red" />
<TextView
android:layout_width="25dp"
android:layout_height="25dp"
android:visibility="invisible"
android:id="#+id/idColorBlue"
android:layout_margin="10dp"
android:layout_below="#id/idToolbarNoteDetails"
android:layout_toRightOf="#+id/idColorRed"
android:background="#drawable/textview_circle_blue"/>
<TextView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/idColorGreen"
android:visibility="invisible"
android:layout_margin="10dp"
android:layout_below="#id/idToolbarNoteDetails"
android:layout_toRightOf="#+id/idColorBlue"
android:background="#drawable/textview_circle_green"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/idTextViewColors"
android:layout_margin="10dp"
android:inputType="textShortMessage"
android:background="#android:color/transparent"
android:textSize="40sp"
android:hint="Title"
android:textStyle="bold"
android:id="#+id/idEditTextTitle"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/idEditTextTitle"
android:hint="Content"
android:inputType="textMultiLine"
android:lines="5"
android:gravity="top|left"
android:layout_margin="10dp"
android:textSize="20sp"
android:background="#android:color/transparent"
android:id="#+id/idEditTextContent"/>
<EditText
android:layout_width="250dp"
android:id="#+id/idEditTextTag"
android:layout_height="35dp"
android:hint="#TAG"
android:background="#android:color/transparent"
android:layout_alignParentBottom="true"
android:textSize="15dp"
android:textStyle="italic"
android:layout_margin="10dp"/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/idFloatingActionButtonSave"
android:layout_above="#+id/idFloatingActionButtonEdit"
android:layout_margin="20dp"
android:visibility="invisible"
app:srcCompat="#android:drawable/ic_menu_save"
android:layout_alignParentRight="true"/>
JAVA
package mynotes.pawanjotsingh.com.mynotes.activities;
import android.content.Intent;
import android.graphics.Color;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import mynotes.pawanjotsingh.com.mynotes.R;
import mynotes.pawanjotsingh.com.mynotes.adapters.RecyclerAdapter;
import mynotes.pawanjotsingh.com.mynotes.dbhelper.DataBaseHelper;
import mynotes.pawanjotsingh.com.mynotes.models.NoteModel;
public class NoteDetailsActivity extends AppCompatActivity {
enum Colors{RED, BLUE, GREEN, WHITE}
DataBaseHelper dataBaseHelper;
FloatingActionButton floatingActionButtonEdit,floatingActionButtonSave;
EditText editTextTitle,editTextContent,editTextTag;
String stringTitle,stringContent,stringTag;
TextView textViewColors,textViewRed,textViewBlue,textViewGreen;
Toolbar toolbar;
int color,colorRed,colorBlue,colorGreen;
String id="";
Colors currentBackgroundColour = Colors.WHITE;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_details);
editTextTitle=(EditText) findViewById(R.id.idEditTextTitle);
editTextTitle.setInputType(InputType.TYPE_NULL);
editTextContent=(EditText) findViewById(R.id.idEditTextContent);
editTextContent.setInputType(InputType.TYPE_NULL);
editTextTag=(EditText) findViewById(R.id.idEditTextTag);
editTextTag.setInputType(InputType.TYPE_NULL);
toolbar=(Toolbar) findViewById(R.id.idToolbarNoteDetails);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Edit");
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
dataBaseHelper=new DataBaseHelper(this);
textViewColors=(TextView) findViewById(R.id.idTextViewColors);
textViewRed=(TextView) findViewById(R.id.idColorRed);
textViewBlue=(TextView) findViewById(R.id.idColorBlue);
textViewGreen=(TextView) findViewById(R.id.idColorGreen);
colorRed=Color.parseColor("#FE7676");
colorBlue=Color.parseColor("#76FEEC");
colorGreen=Color.parseColor("#99FE76");
stringTitle=getIntent().getStringExtra("text_title");
stringContent=getIntent().getStringExtra("text_content");
stringTag=getIntent().getStringExtra("text_tag");
id = getIntent().getStringExtra("id");
color=getIntent().getIntExtra("color", Color.WHITE);
getWindow().getDecorView().setBackgroundColor(color);
editTextTitle.setText(stringTitle);
editTextContent.setText(stringContent);
editTextTag.setText(stringTag);
floatingActionButtonSave=(FloatingActionButton) findViewById(R.id.idFloatingActionButtonSave);
floatingActionButtonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
save();
}
});
floatingActionButtonEdit=(FloatingActionButton) findViewById(R.id.idFloatingActionButtonEdit);
floatingActionButtonEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
floatingActionButtonSave.setVisibility(View.VISIBLE);
Animation animationLeft=AnimationUtils.loadAnimation(getApplicationContext(),R.anim.move_left);
floatingActionButtonSave.startAnimation(animationLeft);
textViewColors.setVisibility(View.VISIBLE);
Animation animationDown= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.move_down);
textViewColors.startAnimation(animationDown);
textViewRed.setVisibility(View.VISIBLE);
textViewRed.startAnimation(animationDown);
textViewBlue.setVisibility(View.VISIBLE);
textViewBlue.startAnimation(animationDown);
textViewGreen.setVisibility(View.VISIBLE);
textViewGreen.startAnimation(animationDown);
editNote();
}
});
textViewRed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentBackgroundColour=Colors.RED;
getWindow().getDecorView().setBackgroundColor(Color.parseColor("#FE7676"));
}
});
textViewBlue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentBackgroundColour=Colors.BLUE;
getWindow().getDecorView().setBackgroundColor(Color.parseColor("#76FEEC"));
}
});
textViewGreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentBackgroundColour = Colors.GREEN;
getWindow().getDecorView().setBackgroundColor(Color.parseColor("#99FE76"));
}
});
}
#Override
public void onBackPressed() {
Intent intent=new Intent(this,MainActivity.class);
startActivity(intent);
}
public void editNote(){
editTextTitle.setInputType(InputType.TYPE_CLASS_TEXT);
editTextTitle.setFocusable(true);
editTextTitle.requestFocus();
editTextContent.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
editTextTag.setInputType(InputType.TYPE_CLASS_TEXT);
}
public void save() {
int colour=Color.WHITE;
switch (currentBackgroundColour){
case RED:
colour = colorRed;
break;
case BLUE:
colour = colorBlue;
break;
case GREEN:
colour = colorGreen;
break;
}
final NoteModel noteModel = new NoteModel();
noteModel.setTitle(editTextTitle.getText().toString());
noteModel.setContent(editTextContent.getText().toString());
noteModel.setTag(editTextTag.getText().toString());
noteModel.setId(id);
noteModel.setDate(getDateTime());
noteModel.setColor(colour);
boolean isModified=dataBaseHelper.editNote(noteModel);
if(isModified==true){
Toast.makeText(this, "Modifications saved", Toast.LENGTH_SHORT).show();
finish();
}
else Toast.makeText(this, "Unable to save modifications", Toast.LENGTH_SHORT).show();
}
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
Links to screenshots
This image is when I click edit button. This works just fine, text goes to another line.
This image is when i click the save button. The text goes back to single line instead of multi-line.
Okay so, I knew that the problem arises when I click on the edit button. Clicking the button made the editText single lined automatically even though I had mentioned the InputType as Multi-line in XML very clearly.
What I did to make the editText multi-line after the button click is that I wrote editTextContent.setSingleLine(false); in my java file inside the onClick button code.
And that is it. :)

Changing text colour of a text view using a spinner [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
So I am attempting to use a spinner to change the text colour of a message in a text view. However, when I attempt to use the function attached to my button click the activity crashes. I have attached the relevant part of the java code and the xml file
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Spinner;
import android.widget.TextView;
public class Colour extends AppCompatActivity {
private Spinner mySpinner;
public static final String EXTRA_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colour);
Intent intent = getIntent();
String messageText = intent.getStringExtra(EXTRA_MESSAGE);
TextView messageView = (TextView)findViewById(R.id.message);
messageView.setText(messageText);
}
public void change(View v){
String text = mySpinner.getSelectedItem().toString();
TextView newColour = (TextView) findViewById(R.id.message);
if(text == "Red"){
newColour.setTextColor(Color.RED);
}
if(text == "Blue"){
newColour.setTextColor(Color.BLUE);
}
if(text == "Green"){
newColour.setTextColor(Color.GREEN);
}
}
XML file:
<TextView
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/message" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/colours"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:id="#+id/spinner" />
<Button
android:text="HOME"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:onClick="home"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="52dp" />
<Button
android:text="changeColour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button4"
android:layout_above="#+id/button"
android:layout_alignStart="#+id/button"
android:layout_marginBottom="101dp"
android:onClick="change" />
mySpinner is not initialized before access it's method. please initialize mySpinner first. use following code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySpinner = (Spinner)findViewById(R.id.spinner);
}
public void change(View v){
String text = mySpinner.getSelectedItem().toString();
TextView newColour = (TextView) findViewById(R.id.message);
if(text.equals("Red")){
newColour.setTextColor(Color.RED);
}
if(text.equals("Blue")){
newColour.setTextColor(Color.BLUE);
}
if(text.equals("Green")){
newColour.setTextColor(Color.GREEN);
}
}
it seems that you did not setup the spinner in the change method so you need to initialize it first

How to add strings from editText to a listView

I have a MainActivity with a ListView and an add Button. When the user clicks the add Button it takes you to another activity the CreateActivity for you to enter in data or strings into the editText boxes. After that you click the create Button and it adds the strings to the ListView it shows up, but every time I try to add another item to the ListView it just overrides the first item and doesn't add on to the ListView.
MainActivity.java with listView and add button
package com.example.brian.inventoryapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static android.R.layout.simple_list_item_1;
public class MainActivity extends AppCompatActivity {
Button addButton;
ListView itemListView;
public static ArrayList<String> arrayList;
public static ArrayAdapter arrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle editTextData = getIntent().getExtras();
if(editTextData != null){
itemListView = (ListView)findViewById(R.id.itemListView);
String data = editTextData.getString("data");
arrayList = new ArrayList<String>();
arrayList.add(data);
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
itemListView.setAdapter(arrayAdapter);
if(data != ""){
arrayAdapter.notifyDataSetChanged();
}
}
addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, CreateActivity.class);
startActivity(intent);
}
});
}
}
activity_main xml with listView and add button
<?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.brian.inventoryapp.MainActivity"
android:weightSum="1">
<Button
android:text="Add"
android:layout_width="wrap_content"
android:layout_height="58dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/addButton" />
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/itemListView"
/>
</RelativeLayout>
CreateActivity.java with four editText boxes and create button
package com.example.brian.inventoryapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import static com.example.brian.inventoryapp.R.id.editTextItem;
public class CreateActivity extends AppCompatActivity {
EditText editTextItem;
EditText editTextModel;
EditText editTextSerial;
EditText editTextID;
Button createButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
getIntent();
editTextItem = (EditText)findViewById(R.id.editTextItem);
editTextModel = (EditText)findViewById(R.id.editTextModel);
editTextSerial = (EditText)findViewById(R.id.editTextSerial);
editTextID = (EditText)findViewById(R.id.editTextID);
createButton = (Button) findViewById(R.id.createButton);
createButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String item = "";
item = editTextItem.getText().toString().trim() +
editTextModel.getText().toString().trim() +
editTextSerial.getText().toString().trim() +
editTextID.getText().toString().trim();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("data", item);
startActivity(intent);
}
});
}
}
activity_create xml with the four editText boxes and the create button
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_create"
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.brian.inventoryapp.CreateActivity">
<TextView
android:text="Item Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/textView" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/editTextItem" />
<TextView
android:text="Model Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
android:id="#+id/textView2"
android:layout_below="#+id/editTextItem"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_below="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/editTextModel" />
<TextView
android:text="Serial Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editTextModel"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp"
android:id="#+id/textView3" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_below="#+id/textView3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/editTextSerial" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_launcher"
android:layout_below="#+id/editTextID"
android:layout_centerHorizontal="true"
android:layout_marginTop="64dp"
android:id="#+id/imageButton" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/editTextID"
android:layout_below="#+id/editTextSerial"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp" />
<TextView
android:text="ID Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView4"
android:layout_below="#+id/editTextSerial"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:text="Create"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/createButton"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
every time you restart the MainActivity, it is be created, the onCreate method was executed .one method you can use the comment method:use startactivityforResult;
you can read this question how to manage startactivityforResult.the second method is to set MainActivity model to SingleInstance.
You are starting MainActivity over and over again, clearing all data previously loaded.
Try this solution
Main activity:
package com.example.brian.inventoryapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static android.R.layout.simple_list_item_1;
public class MainActivity extends AppCompatActivity {
public static final int CREATE_REQUEST = 1;
private Button addButton;
private ListView itemListView;
private ArrayList<String> arrayList;
private ArrayAdapter<String> arrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemListView = (ListView) findViewById(R.id.itemListView);
addButton = (Button) findViewById(R.id.addButton);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
itemListView.setAdapter(arrayAdapter);
addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, CreateActivity.class);
startActivityForResult(intent, CREATE_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CREATE_REQUEST) {
if (resultCode == RESULT_OK) {
String item = data.getStringExtra("data");
arrayList.add(item);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
itemListView.setAdapter(arrayAdapter);
}
}
}
}
In your CreateActivity change createButton listener to this one:
createButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String item = "";
item = editTextItem.getText().toString().trim() +
editTextModel.getText().toString().trim() +
editTextSerial.getText().toString().trim() +
editTextID.getText().toString().trim();
Intent intent = new Intent();
intent.putExtra("data", item);
setResult(RESULT_OK, intent);
finish();
}
});
Yes it will assume as if the MainActivity is started for the first time so you should use startActivityForResult() method instead of startActivity().This will continue your MainActivity and do not override your list View.

setOnClickListener causes force close in Android

I am trying to create an onClickListener for a button. Everything shows up fine before I create the event listener, but force closes when I add it in.
Here is the code:
package com.austin.mobile;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class TxtLingoActivity extends Activity {
/** Called when the activity is first created. */
Button convert;
EditText inputText, outputText;
String myCopy;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
convert = (Button) findViewById(R.id.inputTextBox);
convert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
}
Here is the xml:
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Input"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/inputTextBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
<Button
android:id="#+id/convert"
android:layout_gravity="right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:text="Convert" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Output"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/outputTextBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Log Cat is showing this error:
03-19 18:05:21.726: E/dalvikvm(662): Unable to open stack trace file'/data/anr/traces.txt': Permission denied
Any suggestions?
Looks like you are referring to the incorrect id when 'finding' the Button:
Try to change this:
convert = (Button) findViewById(R.id.inputTextBox);
to this:
convert = (Button) findViewById(R.id.convert);
Hope this helps...
its ClassCastException in this line convert = (Button) findViewById(R.id.inputTextBox);
Because R.id.inputTextBox is EditText and you use as Button .change it in R.id.convert

Categories