Hi am trying to create a simple application using button and spinners. Here is my code. i am facing a nullpointexception error.
Code
package baman.lankahomes.lk.jaffnatemples;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
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.Spinner;
public class MainActivity extends AppCompatActivity {
public final Button btn_search = (Button) findViewById(R.id.btn_search);
public final Spinner spn_from = (Spinner) findViewById(R.id.spinner_from);
public final Spinner spn_radius = (Spinner) findViewById(R.id.spinner_radius);
public final Spinner spn_temple_type = (Spinner) findViewById(R.id.spinner_temple_type);
public final Spinner Spn_no_temple = (Spinner) findViewById(R.id.spinner_no_of_temples);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
validate_form();
goToNextActivity();
}
});
}
public void goToNextActivity(){
Intent intent = new Intent(getApplicationContext(), SearchResult.class);
startActivity(intent);
}
public int validate_form(){
String from = spn_from.getSelectedItem().toString();
if(from == "Please Select"){
show_error_message("Error!", "Please select the from location");
}
return 1;
}
private void show_error_message(String data, String title){
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(data)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
Layout XML
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/search_from"
android:id="#+id/txt_from"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textStyle="bold"
android:clickable="false"
android:textColor="#ffffff"
android:textSize="18sp" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner_from"
android:layout_below="#+id/txt_from"
android:entries="#array/from_spinnerItems"
android:layout_marginTop="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/distance_radius"
android:id="#+id/tv_distance"
android:textStyle="bold"
android:clickable="false"
android:textColor="#ffffff"
android:textSize="18sp"
android:layout_below="#+id/spinner_from"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="8dp" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner_radius"
android:layout_below="#+id/tv_distance"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:entries="#array/distanceRadiusItems"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/temple_type"
android:id="#+id/tv_temple_type"
android:textStyle="bold"
android:clickable="false"
android:textColor="#ffffff"
android:textSize="18sp"
android:layout_below="#+id/spinner_radius"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="8dp" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner_temple_type"
android:layout_below="#+id/tv_temple_type"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:entries="#array/templeTypeItems"
android:layout_marginTop="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/nooftemples"
android:id="#+id/tv_nooftemples"
android:textStyle="bold"
android:clickable="false"
android:textColor="#ffffff"
android:textSize="18sp"
android:layout_below="#+id/spinner_temple_type"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="8dp" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner_no_of_temples"
android:layout_below="#+id/tv_nooftemples"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:entries="#array/NoOfTemplesItems"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/search"
android:id="#+id/btn_search"
android:layout_below="#+id/spinner_no_of_temples"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp"
android:background="#drawable/button_selector"
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18dp" />
</RelativeLayout>
Error
FATAL EXCEPTION: main
Process: baman.lankahomes.lk.jaffnatemples, PID: 6424
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{baman.lankahomes.lk.jaffnatemples/baman.lankahomes.lk.jaffnatemples.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2378)
at android.app.ActivityThread.access$800(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5433)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1954)
at baman.lankahomes.lk.jaffnatemples.MainActivity.<init>(MainActivity.java:16)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2186)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2378)
at android.app.ActivityThread.access$800(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5433)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
public final Button btn_search = (Button) findViewById(R.id.btn_search);
public final Spinner spn_from = (Spinner) findViewById(R.id.spinner_from);
public final Spinner spn_radius = (Spinner) findViewById(R.id.spinner_radius);
public final Spinner spn_temple_type = (Spinner) findViewById(R.id.spinner_temple_type);
public final Spinner Spn_no_temple = (Spinner) findViewById(R.id.spinner_no_of_temples);
needs to be inside onCreate() after setContentView()..that is how your activity will know about your components avoiding the null pointer exception.
Move
Button btn_search = (Button) findViewById(R.id.btn_search);
under onCreate(....) and after setContentView(R.layout.activity_main);
do for others too
Correct:
public class MainActivity extends AppCompatActivity {
public Button btn_search;
public Spinner spn_from;
public Spinner spn_radius;
public Spinner spn_temple_type;
public Spinner Spn_no_temple;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_search = (Button) findViewById(R.id.btn_search);
spn_from = (Spinner) findViewById(R.id.spinner_from);
spn_radius = (Spinner) findViewById(R.id.spinner_radius);
spn_temple_type = (Spinner) findViewById(R.id.spinner_temple_type);
Spn_no_temple = (Spinner) findViewById(R.id.spinner_no_of_temples);
btn_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
validate_form();
goToNextActivity();
}
});
}
Move
public final Button btn_search = (Button) findViewById(R.id.btn_search);
public final Spinner spn_from = (Spinner) findViewById(R.id.spinner_from);
public final Spinner spn_radius = (Spinner) findViewById(R.id.spinner_radius);
public final Spinner spn_temple_type = (Spinner) findViewById(R.id.spinner_temple_type);
public final Spinner Spn_no_temple = (Spinner) findViewById(R.id.spinner_no_of_temples);
to onCreate() after setContentView(R.layout.activity_main);
Related
i made a simple betting app for me and my friend.
I press one button from the bottom to set the value of the bid. and after that if i win i press i win and otherwise i press i lost. when i press i lost or i win the text view get the value of the bet. I dont have any errors , i dont know why is it crashing when i open the app.
here is the code:
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int totalMoney= 0;
int betValue = 0;
String savedMoney;
TextView textView = (TextView) findViewById(R.id.textView);
public void clickP(View view){
totalMoney= totalMoney - betValue;
}
public void clickC(View view){
totalMoney= totalMoney + betValue;
}
public void click1(View view){
betValue = 1;
}
public void click2(View view){
betValue = 2;
}
public void click3(View view){
betValue = 3;
}
public void click4(View view){
betValue = 4;
}
public void click5(View view){
betValue = 5;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedMoney = textView.getText().toString();
totalMoney = Integer.parseInt(savedbani);
SharedPreferences sharedPreferences = this.getSharedPreferences("com.markusappcompany.baniipemasa", Context.MODE_PRIVATE);
sharedPreferences.edit().putInt("Money", totalMoney).apply();
sharedPreferences.getInt("Money", totalMoney);
textView.setText(totalMoney);
}
}
This is what i get in Logcat:
05-22 19:54:52.918 20536-20536/com.markusappcompany.baniipemasa E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.markusappcompany.baniipemasa, PID: 20536
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.markusappcompany.baniipemasa/com.markusappcompany.baniipemasa.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:338)
at android.widget.TextView.setText(TextView.java:5494)
at com.markusappcompany.baniipemasa.MainActivity.onCreate(MainActivity.java:61)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
This is my xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context="com.markusappcompany.baniipemasa.MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="117dp"
android:layout_marginEnd="1dp"
android:layout_marginStart="80dp"
android:layout_marginTop="228dp"
android:text="I LOST"
app:layout_constraintBottom_toTopOf="#+id/button3"
app:layout_constraintEnd_toStartOf="#+id/button2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="117dp"
android:layout_marginEnd="80dp"
android:layout_marginStart="1dp"
android:layout_marginTop="228dp"
android:text="I WIN"
app:layout_constraintBottom_toTopOf="#+id/button4"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/button"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:layout_marginBottom="70dp"
android:layout_marginStart="16dp"
android:text="1 EUR"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/button4"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="70dp"
android:layout_marginTop="117dp"
android:text="2 EUR"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/button5"
app:layout_constraintStart_toEndOf="#+id/button3"
app:layout_constraintTop_toBottomOf="#+id/button" />
<Button
android:id="#+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="70dp"
android:layout_marginTop="117dp"
android:text="3 EUR"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/button6"
app:layout_constraintStart_toEndOf="#+id/button4"
app:layout_constraintTop_toBottomOf="#+id/button2" />
<Button
android:id="#+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="70dp"
android:layout_marginEnd="16dp"
android:layout_marginTop="117dp"
android:text="4 LEI"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/button5"
app:layout_constraintTop_toBottomOf="#+id/button2" />
<Button
android:id="#+id/button7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:layout_marginEnd="148dp"
android:layout_marginStart="148dp"
android:text="5 LEI"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="163dp"
android:layout_marginEnd="221dp"
android:layout_marginStart="190dp"
android:layout_marginTop="16dp"
android:text="0"
android:textSize="36sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.487"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginTop="25dp"
android:text="Total money:"
android:textSize="24sp"
app:layout_constraintEnd_toStartOf="#+id/textView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
thanks in advance!
First of all you remove all click methods your activity should look like this:
public class MainActivity extends AppCompatActivity {
int totalMoney= 0;
int betValue = 0;
String savedMoney;
TextView textView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
Button yourButton = findViewById(R.layout.yourButtonId)
Button yourButton2 = findViewById(R.layout.yourButtonId2)
// for all Buttons
}}
You also must give the button an id in the activity_main file. After that you have to implement an onClickListener for all thes buttons like this:
yourButton1.setOnClickListener(this);
// the same for every Button
then you add this line:
public class MainActivity extends AppCompatActivity implements View.OnClickListener
at the end the listener:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.yourButtonID:
// when button with this ID is clicked do your stuff here
case R.id.otherButtonID:
// when button with this ID is clicked do your stuff here
}
}
Here the explanation first you find the buttons and the textView after that you set an onclicklistener so when you click one button the button call the method onClick. The switch statment is called an finds out which button is called.
Place your Textview's findTextViewById inside OnCreateView.
Try to find the Buttons and textViews in the onCreate method.
Also try to handle the Buttons with OnClickListener like this:
Button yourButtton = findViewById(R.id.yourButttonID);
yourButtton.setOnClickListener(this);
And this for all Buttons.
then:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.yourButtonID:
// when button with this ID is clicked
case R.id.otherButtonID:
// when button with this ID is clicked
}
}
Here, the user has to input names and phone numbers of 3 contacts in this app and register. I have used sharedpreferences method to save the data input. But the setOnclickListener and View remains cannot resolve symbol. Kindly help as I am a beginner. Any help is appreciated.
This is the MainActivity.java file
package com.me.addcontact
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Button btn1= (Button) findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText name1 = (EditText)findViewById(R.id.name1);
EditText num1 = (EditText)findViewById(R.id.num1);
EditText name2 = (EditText)findViewById(R.id.name2);
EditText num2 = (EditText)findViewById(R.id.num2);
EditText name3 = (EditText)findViewById(R.id.name3);
EditText num3 = (EditText)findViewById(R.id.num3);
editor = sharedPreferences.edit();
editor.putString("name1", name1.getText().toString());
editor.putInt("num1", Integer.parseInt(num1.getText().toString()));
editor.putString("name2", name2.getText().toString());
editor.putInt("num2", Integer.parseInt(num2.getText().toString()));
editor.putString("name3", name3.getText().toString());
editor.putInt("num3", Integer.parseInt(num3.getText().toString()));
editor.commit();
Toast.makeText(getApplicationContext(), "Details Saved", Toast.LENGTH_SHORT).show();
}});
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = this.getSharedPreferences("com.me.addcontact", Context.MODE_PRIVATE);
}
}
This 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: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.ashmi.addcontact.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="70sp"
android:background="#cccccc"
android:id="#+id/buttonLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true">
<Button
android:layout_width="300sp"
android:layout_height="50sp"
android:text=" Register"
android:textColor="#bfdfdf"
android:textSize="15sp"
android:background="#003366"
android:id="#+id/button1"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/name1"
android:hint="Emergency Contact Name 1"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:layout_below="#+id/name1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/num1"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Number" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_below="#+id/num1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="34dp"
android:id="#+id/name2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Emergency Contact Name 2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:layout_below="#+id/name2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/num2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Number" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_marginTop="34dp"
android:id="#+id/name3"
android:hint="Emergency Contact Name 3"
android:layout_below="#+id/num2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:layout_below="#+id/name3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/num3"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Number" />
</RelativeLayout>
you must use setOnclickListener interface in onCreate method like this
package com.me.addcontact
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = this.getSharedPreferences("com.me.addcontact", Context.MODE_PRIVATE);
Button btn1= (Button) findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText name1 = (EditText)findViewById(R.id.name1);
EditText num1 = (EditText)findViewById(R.id.num1);
EditText name2 = (EditText)findViewById(R.id.name2);
EditText num2 = (EditText)findViewById(R.id.num2);
EditText name3 = (EditText)findViewById(R.id.name3);
EditText num3 = (EditText)findViewById(R.id.num3);
editor = sharedPreferences.edit();
editor.putString("name1", name1.getText().toString());
editor.putInt("num1", Integer.parseInt(num1.getText().toString()));
editor.putString("name2", name2.getText().toString());
editor.putInt("num2", Integer.parseInt(num2.getText().toString()));
editor.putString("name3", name3.getText().toString());
editor.putInt("num3", Integer.parseInt(num3.getText().toString()));
editor.commit();
Toast.makeText(getApplicationContext(), "Details Saved", Toast.LENGTH_SHORT).show();
}
});
}
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Button btn1;
EditText name1, num1, name2, num2, name3, num3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1= (Button) findViewById(R.id.button1);
sharedPreferences = this.getSharedPreferences("com.me.addcontact", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
name1 = (EditText)findViewById(R.id.name1);
num1 = (EditText)findViewById(R.id.num1);
name2 = (EditText)findViewById(R.id.name2);
num2 = (EditText)findViewById(R.id.num2);
name3 = (EditText)findViewById(R.id.name3);
num3 = (EditText)findViewById(R.id.num3);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putString("name1", name1.getText().toString());
editor.putInt("num1", Integer.parseInt(num1.getText().toString()));
editor.putString("name2", name2.getText().toString());
editor.putInt("num2", Integer.parseInt(num2.getText().toString()));
editor.putString("name3", name3.getText().toString());
editor.putInt("num3", Integer.parseInt(num3.getText().toString()));
editor.commit();
Toast.makeText(getApplicationContext(), "Details Saved", Toast.LENGTH_SHORT).show();
}});
}
}
I hope this will solve your error ..
I'm developing a Calorie app where the user can delete an item from the listview.
PROBLEM: When the user clicks on the item it goes to the calorie details activity,when they click delete it goes back to the home fragment. As soon as I click on add another entry it crashes. Also when it goes back to fragment home it doesnt look the same the calorie details activity is over lapping the fragment home not completely replacing it.
calorieDetails.java
public class CalorieDetails extends AppCompatActivity {
private TextView foodName, calories, dateTaken;
private Button shareButton;
private int foodId;
private Button deleteButton;
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calorie_details);
foodName = (TextView) findViewById(R.id.detsFoodName);
calories = (TextView) findViewById(R.id.detscaloriesValue);
dateTaken = (TextView) findViewById(R.id.detsDateText);
deleteButton = (Button) findViewById(R.id.deleteButton);
Food food = (Food) getIntent().getSerializableExtra("userObj");
foodName.setText(food.getFoodName());
calories.setText(String.valueOf(food.getCalories()));
dateTaken.setText(food.getRecordDate());
foodId = food.getFoodId();
foodName.setTextColor(Color.WHITE);
dateTaken.setTextColor(Color.WHITE);
calories.setTextSize(34.9 f);
calories.setTextColor(Color.WHITE);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO: put delete functionality here
android.support.v7.app.AlertDialog.Builder alert = new
android.support.v7.app.AlertDialog.Builder(CalorieDetails.this);
alert.setTitle("Delete?");
alert.setMessage("Are you sure you want to delete this item?");
alert.setNegativeButton("No", null);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DatabaseHandler dba = new
DatabaseHandler(getApplicationContext());
dba.deleteFood(foodId);
Toast.makeText(CalorieDetails.this, "Food Item
Deleted!", Toast.LENGTH_SHORT).show();
FragmentHome homeFragment = new FragmentHome();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.FragmentHolder,
homeFragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit();
}
});
alert.show();
}
});
}
}
FragmentHome.java
public class FragmentHome extends Fragment implements
View.OnClickListener {
private TextView caloriesTotal;
private TextView caloriesRemain;
private ListView listView;
private LinearLayout mLayout;
ImageButton AddEntrybtn;
ImageButton ResetEntry;
Context context;
int goalCalories;
int totalCalorie;
Button mButton;
//Database
private DatabaseHandler dba;
private ArrayList < Food > dbFoods = new ArrayList < > ();
private CustomListViewAdapter foodAdapter;
private Food myFood;
//fragment
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
public FragmentHome() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_home, container,
false);
caloriesTotal = (TextView)
myView.findViewById(R.id.tv_calorie_amount);
caloriesRemain = (TextView) myView.findViewById(R.id.calorieRemain);
listView = (ListView) myView.findViewById(R.id.ListId);
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getActivity());
PreferenceManager.setDefaultValues(getActivity(),
R.xml.activity_preference, false);
goalCalories =
Integer.parseInt(prefs.getString("prefs_key_daily_calorie_amount",
"2000"));
AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
AddEntrybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
((appMain) getActivity()).loadSelection(4);
}
});
ResetEntry = (ImageButton) myView.findViewById(R.id.ResetEntry);
ResetEntry.setOnClickListener(this);
refreshData();
return myView;
}
public void reset() {
dbFoods.clear();
dba = new DatabaseHandler(getActivity());
ArrayList < Food > foodsFromDB = dba.getFoods();
//Loop
for (int i = 0; i < foodsFromDB.size(); i++) {
String name = foodsFromDB.get(i).getFoodName();
String date = foodsFromDB.get(i).getRecordDate();
int cal = foodsFromDB.get(i).getCalories();
int foodId = foodsFromDB.get(i).getFoodId();
Log.v("Food Id", String.valueOf(foodId));
myFood = new Food();
myFood.setFoodId(foodId);
myFood.setFoodName(name);
myFood.setCalories(cal);
myFood.setRecordDate(date);
dbFoods.clear();
dbFoods.remove(myFood);
foodsFromDB.remove(myFood);
dba.deleteFood(foodId);
}
dba.close();
//setting food Adapter:
foodAdapter = new CustomListViewAdapter(getActivity(),
R.layout.row_item, dbFoods);
listView.setAdapter(foodAdapter);
foodAdapter.notifyDataSetChanged();
}
public void refreshData() {
dbFoods.clear();
dba = new DatabaseHandler(getActivity());
ArrayList < Food > foodsFromDB = dba.getFoods();
totalCalorie = dba.totalCalories();
String formattedCalories = Utils.formatNumber(totalCalorie);
String formattedRemain = Utils.formatNumber(goalCalories -
totalCalorie);
//setting the editTexts:
caloriesTotal.setText("Total Calories: " + formattedCalories);
caloriesRemain.setText(formattedRemain);
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getContext());
PreferenceManager.setDefaultValues(getActivity(),
R.xml.activity_preference, false);
goalCalories =
Integer.parseInt(prefs.getString("prefs_key_daily_calorie_amount", "2000"));
//Loop
for (int i = 0; i < foodsFromDB.size(); i++) {
String name = foodsFromDB.get(i).getFoodName();
String date = foodsFromDB.get(i).getRecordDate();
int cal = foodsFromDB.get(i).getCalories();
int foodId = foodsFromDB.get(i).getFoodId();
Log.v("Food Id", String.valueOf(foodId));
myFood = new Food();
myFood.setFoodId(foodId);
myFood.setFoodName(name);
myFood.setCalories(cal);
myFood.setRecordDate(date);
dbFoods.add(myFood);
}
dba.close();
//setting food Adapter:
foodAdapter = new CustomListViewAdapter(getActivity(),
R.layout.row_item, dbFoods);
listView.setAdapter(foodAdapter);
foodAdapter.notifyDataSetChanged();
}
//save prefs
public void savePrefs(String key, int value) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.apply();
}
//get prefs
public int loadPrefs(String key, int value) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getContext());
return sharedPreferences.getInt(key, value);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle username = getActivity().getIntent().getExtras();
String username1 = username.getString("Username");
TextView userMain = (TextView) getView().findViewById(R.id.User);
userMain.setText(username1);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
startActivity(new Intent(getContext(), MainActivity.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddItems:
AddEntry addEntry = new AddEntry();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.FragmentHolder, addEntry).commit();
break;
case R.id.action_settings:
Intent preferenceScreenIntent = new Intent(getContext(),
PreferenceScreenActivity.class);
startActivity(preferenceScreenIntent);
break;
case R.id.ResetEntry:
reset();
break;
}
}
activity_calorie_details.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:id="#+id/FragmentHolder"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
tools:context=".CalorieDetails"
android:background="#drawable/imgbackground2"
style="#style/AppTheme">
<ImageView
android:id="#+id/logo"
android:src="#drawable/weight"
android:layout_centerHorizontal="true"
android:layout_width="180dp"
android:layout_height="180dp" />
<LinearLayout
android:id="#+id/layout"
android:elevation="4dp"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/logo"
android:layout_centerHorizontal="true">
<TextView
android:id="#+id/detsFoodName"
android:elevation="4dp"
android:text="dkdad"
android:textSize="19sp"
android:textStyle="bold"
android:layout_marginTop="18dp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/detsCaloriesTitle"
android:text="Calories:"
android:textSize="18sp"
android:layout_marginTop="18dp"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/detscaloriesValue"
android:text="200"
android:textSize="18sp"
android:layout_marginTop="18dp"
android:layout_gravity="center_horizontal"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/detsDateText"
android:text="Consumed on..."
android:textStyle="italic"
android:textSize="14sp"
android:layout_marginTop="14dp"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/deleteButton"
android:text="DELETE"
android:textColor="#ffff"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:layout_gravity="center_horizontal"
android:layout_width="200dp"
android:background="#color/colorBackground2"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
Home_fragment.xml
<FrameLayout
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:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:background="#drawable/imgbackground2"
style="#style/AppTheme"
tools:context="layout.HomeFragment"
android:id="#+id/HomeFragment">
<RelativeLayout
android:layout_width="match_parent"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:layout_height="271dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Welcome,"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="85dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/emptyString"
android:id="#+id/User"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/tv_main_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="24dp"
android:textSize="24sp"
android:textColor="#ffffff"
android:text="#string/activity_text_calorie_title"
android:layout_gravity="center_horizontal"
android:textAlignment="center"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/tv_calorie_amount"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:paddingTop="0dp"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#ffffff"
tools:text="1600"
android:paddingRight="0dp"
android:paddingLeft="10dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:layout_below="#+id/tv_main_title"
android:layout_alignParentStart="true"
android:gravity="center"
android:layout_alignParentBottom="false"
android:layout_alignParentLeft="false"
android:layout_alignParentRight="false" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/AddItems"
android:background="?android:attr/selectableItemBackground"
android:src="#drawable/add"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_gravity="right"
android:layout_below="#+id/tv_calorie_amount"
android:layout_alignParentEnd="true" />
<TextView
tools:text="1600"
android:id="#+id/calorieRemain"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:paddingTop="0dp"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#ffffff"
android:paddingRight="0dp"
android:paddingLeft="10dp"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:layout_below="#+id/tv_main_title"
android:layout_toEndOf="#+id/textView" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ResetEntry"
android:background="?android:attr/selectableItemBackground"
android:src="#drawable/removecircle"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_gravity="right"
android:paddingRight="0dp"
android:layout_alignBottom="#+id/AddItems"
android:layout_toStartOf="#+id/AddItems" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="274dp"
android:layout_gravity="center_horizontal|bottom">
<ListView
android:id="#+id/ListId"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:dividerHeight="2dp"
android:divider="#212121"
android:scrollingCache="false"
android:smoothScrollbar="false"
android:layout_below="#+id/tv_calorie_amount"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"></ListView>
</LinearLayout>
</FrameLayout>
Here is a screenshot of what happens after clicking delete:
http://www.tiikoni.com/tis/view/?id=c0939b3
Here is what the Home Fragment Looks like before deleting item:
http://www.tiikoni.com/tis/view/?id=70e433d
logcat when I click Delete on the Calorie Details fragment
05-04 02:25:25.561 5830-5830/com.example.treycoco.calorietracker
E/MotionRecognitionManager: mSContextService =
android.hardware.scontext.ISContextService$Stub$Proxy#14b764b
05-04 02:25:25.571 5830-5830/com.example.treycoco.calorietracker
E/MotionRecognitionManager: motionService =
com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy#42e6828
05-04 02:25:25.571 5830-5830/com.example.treycoco.calorietracker
E/MotionRecognitionManager: motionService =
com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy#42e6828
05-04 02:25:25.581 5830-5830/com.example.treycoco.calorietracker
E/ViewRootImpl: sendUserActionEvent() mView == null
When I click on Add Entry After Clicking on Delete
Logcat:
05-04 02:28:04.761 5830-
5830/com.example.treycoco.calorietracker E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.example.treycoco.calorietracker, PID: 5830
java.lang.ClassCastException
com.example.treycoco.calorietracker.CalorieDetails cannot be cast
to com.example.treycoco.calorietracker.appMain
at com.example.treycoco.calorietracker.
FragmentHome$1.onClick(FragmentHome.java:118)
at android.view.View.performClick(View.java:5697)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
I get a nullpointer error at smashlist.setAdapter(Lincadapter); in Activity B.
I made sure the id's were all correct so the problem isn't there. What am I doing wrong and how do I fix this?
Activity A -->
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popwindow);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*.8), (int)(height*.7));
}
public void enter(View view){
Intent i = new Intent(Pop.this, MainActivity.class);
final EditText name = (EditText)findViewById(R.id.name);
final EditText age = (EditText)findViewById(R.id.age);
final EditText ethnicity = (EditText)findViewById(R.id.ethnicity);
final EditText hair = (EditText)findViewById(R.id.hair);
final EditText date = (EditText)findViewById(R.id.date);
final EditText extras = (EditText)findViewById(R.id.extras);
String nameinput = name.getText().toString();
String ageinput = age.getText().toString();
String ethnicityinput = ethnicity.getText().toString();
String hairinput = hair.getText().toString();
String dateinput = date.getText().toString();
String extrasinput = extras.getText().toString();
i.putExtra("name", nameinput);
i.putExtra("age", ageinput);
i.putExtra("ethnicity", ethnicityinput);
i.putExtra("hair", hairinput);
i.putExtra("date", dateinput);
i.putExtra("extras", extrasinput);
startActivity(i);
};
}
Activity A XML -->
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:maxLines="1"
android:maxLength="25"
android:singleLine="true"
android:capitalize="words"
android:layout_weight="1"
android:id="#+id/name"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Age"
android:inputType="number"
android:maxLength="2"
android:layout_weight="1"
android:id="#+id/age"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Ethnicity"
android:maxLines="1"
android:maxLength="25"
android:singleLine="true"
android:capitalize="words"
android:layout_weight="1"
android:id="#+id/ethnicity"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Hair color"
android:maxLines="1"
android:maxLength="25"
android:singleLine="true"
android:capitalize="sentences"
android:layout_weight="1"
android:id="#+id/hair"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="date"
android:ems="10"
android:hint="Date"
android:maxLines="1"
android:maxLength="10"
android:singleLine="true"
android:layout_weight="1"
android:id="#+id/date"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Extras"
android:maxLines="3"
android:maxLength="200"
android:capitalize="sentences"
android:layout_weight="1"
android:id="#+id/extras"/>
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/tickbutton"
android:clickable="true"
android:layout_gravity="right"
android:layout_weight="1"
android:onClick="enter"/>
Activity B-->
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
Bundle smashdata = getIntent().getExtras();
if (smashdata == null){
return;
}
String nameinput = smashdata.getString("name");
String ageinput = smashdata.getString("age");
String ethnicityinput = smashdata.getString("ethnicity");
String hairinput = smashdata.getString("hair");
String dateinput = smashdata.getString("date");
String extrasinput = smashdata.getString("extras");
final ListView smashlist = (ListView) findViewById(R.id.smashlist);
String[] info = {nameinput, ageinput, ethnicityinput, hairinput, dateinput, extrasinput};
ListAdapter lincadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, info);
smashlist.setAdapter(lincadapter);
smashlist.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
);
Activity B XML -->
<TextView android:text="I've Smashed 0 Girls"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="30sp"
android:textColor="#000000"
/>
<ListView
android:id="#+id/smashlist"
android:layout_width="wrap_content"
android:layout_height="272dp"
android:layout_weight="1.00"
android:background="#ff0000"/>
<ImageView
android:layout_width="75dp"
android:layout_height="75dp"
android:clickable="true"
android:src="#drawable/plusbutton"
android:layout_gravity="center_horizontal"
android:onClick="add"/>
Crash log --->
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
at android.app.ActivityThread.access$700(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.kongapps.smashlog.MainActivity.onCreate(MainActivity.java:52)
at android.app.Activity.performCreate(Activity.java:5372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
at android.app.ActivityThread.access$700(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
I think the error is this:
Activity A
i.putExtra("date", dateinput);
and then
Activity B
String dateinput = smashdata.getString("datename");
you call differently to that variable.
My advice would be to use static constants to be free from such errors . :)
Regards.
it seems your string array has problem, check if the string's inside actually have some value of not other wise you will get Null error
String[] info = {nameinput, ageinput, ethnicityinput, hairinput, dateinput, extrasinput};
for now write your info array like this to verify it works
String[] info = new String[]{"nameinput", "ageinput", "ethnicityinput", "hairinput", "dateinput", "extrasinput"};
Create a static ArrayList in A activity add all values in pass this array in ListView adapter
Example:
ArrayList<String>_array = new ArrayList<>();
_array.add(nameinput);
In B Activity
ListAdapter lincadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, A._array)
Write
String [] info= new String[6];
And then add the values in info={your values};
This might solve your null pointer exception
I'm starter programmer on Android environment. And I need your help.
Here is the what I'm trying to do
package com.codeherenow.sicalculator;
import com.codeherenow.sicalculator.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
public class SICalculatorActivity extends Activity {
private TextView PA;
private TextView Interest_Rate;
private TextView Years;
private EditText PA_bar;
private EditText IR_bar;
private SeekBar year_bar;
private Button calculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
PA = (TextView) findViewById(R.id.PA);
Interest_Rate = (TextView) findViewById(R.id.Interest_Rate);
Years= (TextView) findViewById(R.id.Years);
PA_bar= (EditText) findViewById(R.id.PA_bar);
IR_bar= (EditText) findViewById(R.id.IR_bar);
year_bar=(SeekBar) findViewById(R.id.year_bar);
calculate=(Button) findViewById(R.id.calculate);
calculate.setOnClickListener(new OnClickListener(){
public void onClick(View v){
}
}
}
}
My 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=".SICalculatorActivity" >
<TextView
android:id="#+id/Years"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/IR_bar"
android:layout_centerVertical="true"
android:text="2 Year(s)"
android:textSize="20sp" />
<SeekBar
android:id="#+id/year_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Years"
android:layout_below="#+id/Years"
android:layout_marginTop="21dp" />
<Button
android:id="#+id/calculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/year_bar"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/year_bar"
android:text="Calculate" />
<EditText
android:id="#+id/IR_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Years"
android:layout_marginBottom="14dp"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/Interest_Rate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/IR_bar"
android:layout_alignLeft="#+id/IR_bar"
android:layout_marginBottom="15dp"
android:text="Interest Rate"
android:textSize="20sp" />
<TextView
android:id="#+id/PA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/PA_bar"
android:layout_alignParentTop="true"
android:layout_marginTop="14dp"
android:text="Principal Amount"
android:textSize="20sp" />
<EditText
android:id="#+id/PA_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Interest_rate"
android:layout_below="#+id/PA"
android:layout_marginTop="17dp"
android:ems="10"
android:inputType="number" />
</RelativeLayout>
Actually , I need help for not xml part. I need help for java coding part. Even if i'm trying to use onclicklistener , compiler always show error on coding page? Could someone help me?
Try this:
public class MainActivity extends Activity {
TextView PA;
TextView Interest_Rate;
TextView Years;
EditText PA_bar;
EditText IR_bar;
EditText year_bar;
Button calculate;
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PA = (TextView) findViewById(R.id.PA);
Interest_Rate = (TextView) findViewById(R.id.Interest_Rate);
Years = (TextView) findViewById(R.id.Years);
PA_bar = (EditText) findViewById(R.id.PA_bar);
IR_bar = (EditText) findViewById(R.id.IR_bar);
year_bar = (EditText) findViewById(R.id.year_bar);
calculate = (Button) findViewById(R.id.calculate);
t1 = (TextView) findViewById(R.id.t1);
calculate.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
int num1 = Integer.parseInt(PA_bar.getText().toString());
int num2 = Integer.parseInt(IR_bar.getText().toString());
int num = Integer.parseInt(year_bar.getText().toString());
int si = (num1 * num2 * num) / 100;
t1.setText(Integer.toString(si));
}
});
}};
You have a syntactical error in your code. You are missing the closing parentheses and semi-colon.
calculate.setOnClickListener(new OnClickListener() {
public void onClick(View v){
}
}); //<--- Change is here.