Android studio app crashing when going to second activity [duplicate] - android

This question already has answers here:
Resource not found TextView
(2 answers)
Closed 6 years ago.
I"m working on my application, where a user enters a ip address and port number and will connect to the server. As soon as I fill in the ip address and port number and press on connect, the application crashes. These are the errors i'm getting.
EDIT: added xml for both activities
EDIT2: Changed the textview ID and it's still crashing, new error message all the way down.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jobush50.irobot, PID: 2285
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jobush50.irobot/com.example.jobush50.irobot.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x22b8
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x22b8
at android.content.res.Resources.getText(Resources.java:331)
at android.support.v7.widget.ResourcesWrapper.getText(ResourcesWrapper.java:52)
at android.widget.TextView.setText(TextView.java:4550)
at com.example.jobush50.irobot.MainActivity.onCreate(MainActivity.java:45)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
My MainActivity
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
static int port;
static String ip;
private Socket socket;
private static final int SERVERPORT = port;
private static final String SERVER_IP = ip;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
Intent intent = getIntent();
String name = intent.getStringExtra("ip");
int number = intent.getIntExtra("port", 0);
port = number;
ip = name;
TextView textView = (TextView) findViewById(R.id.textView1);
textView.setText(name);
TextView textView2 = (TextView) findViewById(R.id.textView2);
textView2.setText(number);
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
SecondActivity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.widget.EditText;
import android.content.Intent;
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
final EditText editText = (EditText)findViewById(R.id.editText_port);
final EditText editText2 = (EditText)findViewById(R.id.editText_port);
Button sendButton = (Button)findViewById(R.id.button_send);
sendButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String name = editText.getText().toString();
int number = Integer.parseInt(editText2.getText().toString() );
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.putExtra("ip", name);
intent.putExtra("port", number);
startActivity(intent);
}
});
}
}
Activity_main.xml
<?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.jobush50.irobot.MainActivity"
android:background="#android:color/darker_gray">
<EditText
android:id="#+id/EditText01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Input" >
</EditText>
<Button
android:id="#+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Send"
android:layout_below="#+id/EditText01"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="19dp">
</Button>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/myButton"
android:layout_marginLeft="34dp"
android:layout_marginStart="34dp"
android:layout_marginBottom="223dp"
android:id="#+id/textView1" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/textView1"
android:layout_alignStart="#+id/textView1"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:layout_marginBottom="98dp"
android:id="#+id/textView2" />
activity_second.xml
<?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_second"
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.jobush50.irobot.SecondActivity"
android:layout_width="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Enter ip address"
android:ems="10"
android:layout_marginBottom="85dp"
android:id="#+id/editText_ip"
android:layout_above="#+id/button_send"
android:layout_centerHorizontal="true" />
<Button
android:text="Connect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="144dp"
android:id="#+id/button_send"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="Enter port number"
android:ems="10"
android:layout_above="#+id/button_send"
android:layout_marginBottom="17dp"
android:id="#+id/editText_port" />
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jobush50.irobot, PID: 2278
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jobush50.irobot/com.example.jobush50.irobot.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x22b8
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x22b8
at android.content.res.Resources.getText(Resources.java:331)
at android.support.v7.widget.ResourcesWrapper.getText(ResourcesWrapper.java:52)
at android.widget.TextView.setText(TextView.java:4550)
at com.example.jobush50.irobot.MainActivity.onCreate(MainActivity.java:45)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Application terminated.

textView2.setText(number);
The OS is trying to find match id since number is int try
textView2.setText(String.valueOf(number));

Related

I am using ImageSwitcher. When I run the file I'm getting the following error:

MainActivity.java
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import com.example.app38.databinding.ActivityMainBinding;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.ViewSwitcher;
public class MainActivity extends AppCompatActivity implements ViewSwitcher.ViewFactory {
LinearLayout linearLayoutHorizontal;
ImageSwitcher imgSwitcher;
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.toolbar);
linearLayoutHorizontal = findViewById(R.id.linearLayoutHorizontal);
imgSwitcher = findViewById(R.id.imgSwitcher);
imgSwitcher.setFactory(MainActivity.this);
imgSwitcher.setInAnimation(AnimationUtils.loadAnimation(MainActivity.this,
android.R.anim.slide_in_left));
imgSwitcher.setOutAnimation(AnimationUtils.loadAnimation(MainActivity.this,
android.R.anim.fade_out));
for (int index = 0; index < Animal.animalImages.length; index++) {
final int i = index;
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(Animal.animalImages[index]);
letsSetlayoutParamsForImageView(imageView);
imageView.setPadding(100,100,100,100);
imageView.setOnClickListener(view -> {
imgSwitcher.setImageResource(Animal.animalImages[i]);
Toast.makeText(MainActivity.this, "This is "+ Animal.animalNames[i], Toast.LENGTH_SHORT).show();
});
linearLayoutHorizontal.addView(imageView);
}
}
public void letsSetlayoutParamsForImageView(ImageView imageView) {
imageView.setLayoutParams(new LinearLayout.LayoutParams(1000,1000));
}
#Override
public View makeView() {
ImageView imgView = new ImageView(MainActivity.this);
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
return imgView;
}
}
Animal.java
public class Animal {
static int[] animalImages = { R.drawable.bear, R.drawable.bird, R.drawable.cat, R.drawable.cow,
R.drawable.dolphin, R.drawable.fish, R.drawable.fox, R.drawable.horse, R.drawable.lion, R.drawable.tiger};
static String[] animalNames = {"Bear","Bird","Cat","Cow","Dolphin","Fish","Fox","Horse","Lion","Tiger"};
}
content_main.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/linearLayoutHorizontal"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</HorizontalScrollView>
<ImageSwitcher
android:id="#+id/imgSwitcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ImageSwitcher>
</LinearLayout>
</ScrollView>
</LinearLayout>
</RelativeLayout>
Logcat
FATAL EXCEPTION: main
Process: com.example.app38, PID: 14499
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app38/com.example.app38.MainActivity}: java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.widget.FrameLayout$LayoutParams
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3635)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.widget.FrameLayout$LayoutParams
at android.widget.ViewSwitcher.obtainView(ViewSwitcher.java:86)
at android.widget.ViewSwitcher.setFactory(ViewSwitcher.java:104)
at com.example.app38.MainActivity.onCreate(MainActivity.java:33)
at android.app.Activity.performCreate(Activity.java:8051)
at android.app.Activity.performCreate(Activity.java:8031)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3608)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loopOnce(Looper.java:201) 
at android.os.Looper.loop(Looper.java:288) 
at android.app.ActivityThread.main(ActivityThread.java:7839) 
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 
The line of code at line 33:
imgSwitcher.setFactory(MainActivity.this);
Can any one suggest a answer for my problem.
change
imgView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
to
imgView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));

I keep getting a error when I execute the send Credentials void

When I run my code i get a error when the SendCredentials void is executed.
The error is:-
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.messager, PID: 16131
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:6614)
at android.view.View.performClickInternal(View.java:6591)
at android.view.View.access$3100(View.java:786)
at android.view.View$PerformClick.run(View.java:25948)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6806)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6614) 
at android.view.View.performClickInternal(View.java:6591) 
at android.view.View.access$3100(View.java:786) 
at android.view.View$PerformClick.run(View.java:25948) 
at android.os.Handler.handleCallback(Handler.java:873) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:201) 
at android.app.ActivityThread.main(ActivityThread.java:6806) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.io.DataInputStream.readLine()'
on a null object reference
at com.example.messager.MainActivity.SendCredentials(MainActivity.java:69)
at com.example.messager.MainActivity.SendMessage(MainActivity.java:26)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
at android.view.View.performClick(View.java:6614) 
at android.view.View.performClickInternal(View.java:6591) 
at android.view.View.access$3100(View.java:786) 
at android.view.View$PerformClick.run(View.java:25948) 
at android.os.Handler.handleCallback(Handler.java:873) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:201) 
at android.app.ActivityThread.main(ActivityThread.java:6806) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
My Code is
package com.example.messager;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import java.net.*;
import java.io.*;
public class MainActivity extends AppCompatActivity {
EditText stopPort;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void SendMessage(View view)throws IOException{
EditText emailText = (EditText) findViewById(R.id.Email);
String Username = emailText.getText().toString();
EditText passwordText = (EditText) findViewById(R.id.Password);
String Password = passwordText.getText().toString();
System.out.println("Your username is " + Username + "Your Password is " + Password);
SendCredentials();
}
public void SendCredentials()throws IOException {
System.out.println("Work");
Socket socket = new Socket("192.168.0.114", 4321);
System.out.println("Work");
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeByte(1);
dOut.writeUTF("This is a test");
dOut.flush();
System.out.println("Work");
}
public void Check(){
}
}
`
 
Looking to above code and exception trace 2 things can be wrong.
check your code for
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.io.DataInputStream.readLine()' on a null object reference at
In xml layout file, have you declared "check" method on android:onClick
i.e. android:onClick="check", if yes then your check method should look like this
public void Check(View view){
}
Can you share you xml layout file as well.
yea my xml code is '
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=".MainActivity">
<TextView
android:id="#+id/Welcome"
android:layout_width="198dp"
android:layout_height="52dp"
android:layout_marginStart="104dp"
android:layout_marginTop="68dp"
android:text="Welcome"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#color/colorPrimaryDark"
android:textSize="36sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.design.widget.TextInputLayout
android:id="#+id/passwordWrapper"
android:layout_width="387dp"
android:layout_height="56dp"
android:layout_marginStart="8dp"
android:layout_marginTop="444dp"
android:hint="Password"
app:hintEnabled="true"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="#+id/Password"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="Password"
android:inputType="textPassword"
android:textSize="18sp"
tools:text="" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/emailWrapper"
android:layout_width="397dp"
android:layout_height="56dp"
android:layout_marginStart="8dp"
android:layout_marginTop="368dp"
android:hint="Email"
app:hintEnabled="true"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="#+id/Email"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="Email"
android:inputType="textWebEmailAddress"
android:textAlignment="textStart"
android:textSize="18sp"
tools:text=""/>
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/LoginButton"
android:layout_width="348dp"
android:layout_height="45dp"
android:layout_marginStart="28dp"
android:layout_marginTop="520dp"
android:text="LOGIN"
android:onClick="SendMessage"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
'
public void SendMessage(View view) throws IOException {
EditText emailText = (EditText) findViewById(R.id.Email);
String Username = emailText.getText().toString();
EditText passwordText = (EditText) findViewById(R.id.Password);
String Password = passwordText.getText().toString();
System.out.println("Your username is " + Username + "Your Password is " + Password);
SendCredentials();
}
public void SendCredentials() throws IOException {
new MyAsyncTask().execute();
}
public void Check() {
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
Activity activity;
IOException ioException;
MyAsyncTask() {
super();
}
#Override
protected Void doInBackground(Void... voids) {
StringBuilder sb = new StringBuilder();
try {
System.out.println("Work");
Socket socket = new Socket("192.168.0.114", 4321);
System.out.println("Work");
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeByte(1);
dOut.writeUTF("This is a test");
dOut.flush();
System.out.println("Work");
socket.close();
} catch (IOException e) {
this.ioException = e;
}
}
}

Unable to start new activity involving Firebase

I am building an app that has a charity and restaurant. They register themselves and then proceed using Firebase for database handling. When I register charity register charity should open but it shows error. Logcat and register charity file attached.
activity register charity
package com.example.aayu.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
/**
* Created by AAYU on 30-May-17.
*/
public class regc extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reg_c);
final DatabaseReference rootref = FirebaseDatabase.getInstance()
.getReferenceFromUrl("https://myapplication-6e0b9.firebaseio.com/charity");
final EditText mname = (EditText) findViewById(R.id.cname);
final EditText madd = (EditText) findViewById(R.id.cadd);
final EditText mcity = (EditText) findViewById(R.id.ccity);
final EditText mstate = (EditText) findViewById(R.id.cstate);
final EditText mpin = (EditText) findViewById(R.id.cpin);
final Button mnext= (Button) findViewById(R.id.cnext);
mnext.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
String name = mname.getText().toString();
String add = madd.getText().toString();
String city = mcity.getText().toString();
String state = mstate.getText().toString();
String pin = mpin.getText().toString();
DatabaseReference childref = rootref.child("Charity Name");
childref.setValue(name);
childref = rootref.child("Address");
childref.setValue(add);
childref = rootref.child("City");
childref.setValue(city);
childref = rootref.child("State");
childref.setValue(state);
childref = rootref.child("Pincode");
childref.setValue(pin);
}
});
//setContentView(R.layout.reg2_c);
final EditText memail = (EditText) findViewById(R.id.cemail);
final EditText mph = (EditText) findViewById(R.id.cph);
final EditText muname = (EditText) findViewById(R.id.cuname);
final EditText mpwd = (EditText) findViewById(R.id.cpwd);
final Button mreg=(Button) findViewById(R.id.creg);
mreg.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
String email = memail.getText().toString();
String ph = mph.getText().toString();
String uname = muname.getText().toString();
String pwd = mpwd.getText().toString();
DatabaseReference childref = rootref.child("Email Id");
childref.setValue(email);
childref = rootref.child("Phone No");
childref.setValue(ph);
childref = rootref.child("Username");
childref.setValue(uname);
childref = rootref.child("Password");
childref.setValue(pwd);
Toast.makeText(view.getContext(), "Registration done successfully", Toast.LENGTH_SHORT).show();
}
});
// Intent loginc = new Intent(this, loginc.class);
// startActivity(loginc);
}
}
logcat
W/GooglePlayServicesUtil: Google Play services out of date. Requires 11011000 but found 9877470
V/FA: Activity paused, time: 32230643
V/FA: Processing queued up service tasks: 2
E/FA: Failed to send current screen to service
E/FA: Discarding data. Failed to send event to service
D/AndroidRuntime: Shutting down VM
E/UncaughtException: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aayu.myapplication/com.example.aayu.myapplication.regc}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.aayu.myapplication.regc.onCreate(regc.java:76)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.aayu.myapplication, PID: 9023
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aayu.myapplication/com.example.aayu.myapplication.regc}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.aayu.myapplication.regc.onCreate(regc.java:76)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
Application terminated.
reg_c.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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_marginStart="51dp"
android:layout_marginTop="49dp"
android:id="#+id/cname"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:hint="Charity Home Name"
android:selectAllOnFocus="true" />
<Button
android:text="NEXT"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cnext"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:background="#color/colorPrimary"
android:textStyle="normal|bold"
android:textSize="20sp"
android:elevation="21dp"
android:onClick="next" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_marginTop="24dp"
android:id="#+id/cadd"
android:layout_below="#+id/cname"
android:layout_alignStart="#+id/cname"
android:hint="Address "
android:selectAllOnFocus="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_marginTop="36dp"
android:id="#+id/ccity"
android:hint="City"
android:selectAllOnFocus="true"
android:layout_below="#+id/cadd"
android:layout_alignStart="#+id/cadd" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_marginTop="48dp"
android:id="#+id/cstate"
android:hint="State"
android:selectAllOnFocus="true"
android:layout_below="#+id/ccity"
android:layout_alignStart="#+id/ccity" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:layout_marginTop="34dp"
android:id="#+id/cpin"
android:hint="Pincode"
android:selectAllOnFocus="true"
android:layout_below="#+id/cstate"
android:layout_alignStart="#+id/cstate" />
</RelativeLayout>
layout for reg_c.xml
The issue is here:
final Button mreg=(Button) findViewById(R.id.creg);
mreg.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
String email = memail.getText().toString();
String ph = mph.getText().toString();
String uname = muname.getText().toString();
String pwd = mpwd.getText().toString();
DatabaseReference childref = rootref.child("Email Id");
childref.setValue(email);
childref = rootref.child("Phone No");
childref.setValue(ph);
childref = rootref.child("Username");
childref.setValue(uname);
childref = rootref.child("Password");
childref.setValue(pwd);
Toast.makeText(view.getContext(), "Registration done successfully", Toast.LENGTH_SHORT).show();
}
});
You don't have any button with this id in your XML file but you are trying to access it in your Activity. That is causing Null Pointer Exception.
You have two solution:
If you need this button then add a button with the id "creg" in your XML file.
OR
If you don't need that button then remove the code given above from your Activity.

Android compare 2 images and tell to fruit category to is fruit (apple/banana) or not fruit

Android compare 2 images to use Bitmap code and tell to fruit category to is fruit (apple/banana) or not fruit.
I have problem to compare with Bitmap and BitmapFactory to have runtime error , I have solution to problem.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/buttonIntent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Gallery" />
<Button
android:text="OK to Search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/buttonIntent"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/button" />
</RelativeLayout>
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Have fruit as Apple"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/textView"
android:textSize="20sp"
android:textColor="#android:color/black" />
</RelativeLayout>
MainActivity.java
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.FileNotFoundException;
import java.io.IOException;
public class MainActivity extends Activity {
public static final int REQUEST_GALLERY = 1;
// Code to compare picture.
Bitmap bitmap; // Picture with select file in gallery.
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.a1); // Picture to compare.
// Code to compare picture.
ImageView imageView1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView1 = (ImageView)findViewById(R.id.imageView);
Button buttonIntent = (Button)findViewById(R.id.buttonIntent);
buttonIntent.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent
, "Select Picture"), REQUEST_GALLERY);
}
});
Button buttonIntent2 = (Button)findViewById(R.id.button);
buttonIntent2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(bitmap == b) { // Have to error.
Intent newActivity = new Intent(MainActivity.this, ActivityForm2.class);
startActivity(newActivity);
}
}
});
}
public void onActivityResult(int requestCode, int resultCode
, Intent data) {
if (requestCode == REQUEST_GALLERY && resultCode == RESULT_OK) {
Uri uri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
imageView1.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ActivityForm2.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
/**
* Created by sumate on 10/30/2016 AD.
*/
public class ActivityForm2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
}
Image example
5.1 Image to Bitmap bitmap;
5.2 Image to Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.a1);
Runtime Error
11-13 21:08:42.244 26248-26248/com.spv.babaimile.fruitsearchwithpic E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.spv.babaimile.fruitsearchwithpic, PID: 26248
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.spv.babaimile.fruitsearchwithpic/com.spv.babaimile.fruitsearchwithpic.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:86)
at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:127)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:121)
at com.spv.babaimile.fruitsearchwithpic.MainActivity.<init>(MainActivity.java:22)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
I have answered to compare fruit with OpenCV color blob detection for Android complete.
Source : https://github.com/doanga2007/FruitSearch
Tutorial : https://docs.google.com/presentation/d/1s0KvqZm0kmPYRdjQNgKFPan0RjNWBCjkem23UkXh2GE/edit#slide=id.g2e200109_1_0

app crashes on button click when editText is empty

i am creating a single screen app of grocery but while checking total price if a user doesnt type anything it should by default be equal to 0 but instead my app crashes
Below is the code for same
Activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ashis.singlescreenapp.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/headline"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView2" />
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#mipmap/grocery_logo"
android:id="#+id/imageView"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/qty_heading"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView_qty"
android:layout_below="#+id/imageView"
android:layout_alignLeft="#+id/imageView"
android:layout_alignStart="#+id/imageView" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView_qty"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/linearLayout">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText_apples"
android:layout_weight="1"
android:hint="Apples ($2 per piece)" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText_orange"
android:layout_weight="1"
android:hint="Orange($3 per piece)" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/linearLayout2">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText_mango"
android:layout_weight="1"
android:hint="Mango($4 per piece)" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText_banana"
android:layout_weight="1"
android:hint="Banana($1 per piece)" />
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_confirm"
android:text="#string/btn_confirm"
android:onClick="onbuttonClicked"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView_result"
android:minWidth="300dp"
android:layout_below="#+id/linearLayout2"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check"
android:id="#+id/button"
android:layout_above="#+id/button_confirm"
android:layout_centerHorizontal="true"
android:onClick="checkPrice" />
</RelativeLayout>
MainActivity.java
package com.example.ashis.singlescreenapp;
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 android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText editText_apples,editText_orange,editText_mango,editText_banana;
int apples,orange,mango,banana;
TextView textView_result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void checkPrice(View view)
{
editText_apples=(EditText) findViewById(R.id.editText_apples);
editText_orange=(EditText) findViewById(R.id.editText_orange);
editText_banana=(EditText) findViewById(R.id.editText_banana);
editText_mango=(EditText) findViewById(R.id.editText_mango);
textView_result=(TextView) findViewById(R.id.textView_result);
apples=Integer.parseInt(editText_apples.getText().toString());
orange=Integer.parseInt(editText_orange.getText().toString());
mango=Integer.parseInt(editText_mango.getText().toString());
banana=Integer.parseInt(editText_banana.getText().toString());
if (editText_apples.getText().toString().equals(""))
{
apples=0;
}
else if (editText_banana.getText().toString().equals(""))
{
banana=0;
}
else if (editText_orange.getText().toString().equals(""))
{
orange=0;
}
else if (editText_mango.getText().toString().equals(""))
{
mango=0;
}
else {
int result = getPrice(apples, orange, mango, banana);
textView_result.setText(String.valueOf(result));
}
}
private int getPrice(int apples, int orange, int mango, int banana) {
int result= (apples*2) + (orange*3) + (mango*4) + (banana);
return result;
}
/*
public void onbuttonClicked(View view)
{
String email_body = "Dear Grocery Store, \n" + "Send all the following ";
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL,"ashish.choudhary#groceryStore.com");
intent.putExtra(Intent.EXTRA_SUBJECT," Send All these Product");
intent.putExtra(Intent.EXTRA_TEXT,"");
}
*/
}
Here is the logCat when i click on Confirm Button
FATAL EXCEPTION: main
Process: com.example.ashis.singlescreenapp, PID: 22748
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5226)
at android.view.View$PerformClick.run(View.java:21350)
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:5571)
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)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5226) 
at android.view.View$PerformClick.run(View.java:21350) 
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:5571) 
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) 
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at com.example.ashis.singlescreenapp.MainActivity.checkPrice(MainActivity.java:36)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5226) 
at android.view.View$PerformClick.run(View.java:21350) 
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:5571) 
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) 
The problem is you are trying to format an empty String. Just check
if(!edittext.getText().toString().equals("")) {
apples = Integer.parseInt(edittext.getText().toString());
} else {
apples = 0;
}
Or you could use the short form:
apples = edittext.getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());
You are calling parseInt before you check for empty string. parseInt on empty string will throw exception. You should in any case surround parseInt with a try catch.
You can debug your code and you see - you are trying to parse int before checking text.
You need something like this for each edit text:
if (editText_apples.getText().toString().equals("")) {
apples=0;
} else {
apples=Integer.parseInt(editText_apples.getText().toString());
}
or short variant:
apples = editText_apples.getText().toString().isEmpty() ? 0
: Integer.parseInt(editText_apples.getText().toString());
To be sure, that in edit text will be only numbers, you can add inputType for edit text:
<EditText
...
android:inputType="number"/>
You have some issues trying to parse for integers from empty strings. Try replace this piece of code:
apples=Integer.parseInt(editText_apples.getText().toString());
orange=Integer.parseInt(editText_orange.getText().toString());
mango=Integer.parseInt(editText_mango.getText().toString());
banana=Integer.parseInt(editText_banana.getText().toString());
if (editText_apples.getText().toString().equals(""))
{
apples=0;
}
else if (editText_banana.getText().toString().equals(""))
{
banana=0;
}
else if (editText_orange.getText().toString().equals(""))
{
orange=0;
}
else if (editText_mango.getText().toString().equals(""))
{
mango=0;
}
else {
int result = getPrice(apples, orange, mango, banana);
textView_result.setText(String.valueOf(result));
}
with this:
String txt1 = editText_apples.getText().toString();
apples=Integer.parseInt("".equals(txt1.trim()) ? "0" : txt1);
String txt2 = editText_orange.getText().toString();
orange=Integer.parseInt("".equals(txt2.trim()) ? "0" : txt2);
String txt3 = editText_mango.getText().toString();
mango=Integer.parseInt("".equals(txt3.trim()) ? "0" : txt3);
String txt4 = editText_banana.getText().toString();
banana=Integer.parseInt("".equals(txt4.trim()) ? "0" : txt4);
int result = getPrice(apples, orange, mango, banana);
textView_result.setText(String.valueOf(result));
Initialise view while setting content
public class MainActivity extends AppCompatActivity {
EditText editText_apples,editText_orange,editText_mango,editText_banana;
int apples,orange,mango,banana;
TextView textView_result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText_apples=(EditText) findViewById(R.id.editText_apples);
editText_orange=(EditText) findViewById(R.id.editText_orange);
editText_banana=(EditText) findViewById(R.id.editText_banana);
editText_mango=(EditText) findViewById(R.id.editText_mango);
textView_result=(TextView) findViewById(R.id.textView_result);
}
public void checkPrice(View view)
{
if(TextUtils.isDigitOnly(editText_apples.getText().toString()){
apples=Integer.parseInt(editText_apples.getText().toString());
}else{
apples=0;
}
if(TextUtils.isDigitOnly(editText_orange.getText().toString()){
orange=Integer.parseInt(editText_orange.getText().toString());
}else{
orange=0;
}
if(TextUtils.isDigitOnly(editText_mango.getText().toString()){
mango=Integer.parseInt(editText_mango.getText().toString());
}else{
mango=0;
}
if(TextUtils.isDigitOnly(editText_banana.getText().toString()){
banana=Integer.parseInt(editText_banana.getText().toString());
}else{
banana=0;
}
int result = getPrice(apples, orange, mango, banana);
textView_result.setText(String.valueOf(result));
}
private int getPrice(int apples, int orange, int mango, int banana) {
int result= (apples*2) + (orange*3) + (mango*4) + (banana);
return result;
}
}
in your code at the time of button clicks views are getting initialized and then u will be able to use them and the values are null in edit text so casting them in integer generates null pointer exception.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText_apples=(EditText) findViewById(R.id.editText_apples);
editText_orange=(EditText) findViewById(R.id.editText_orange);
editText_banana=(EditText) findViewById(R.id.editText_banana);
editText_mango=(EditText) findViewById(R.id.editText_mango);
textView_result=(TextView) findViewById(R.id.textView_result);
checkPrice();
}
public void checkPrice()
{
apples = edittext_apples.getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());
orange=editText_orange..getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());
mango=editText_mango..getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());
banana=editText_banana.getText().toString().equals("") ? 0 : Integer.parseInt(edittext.getText().toString());
...............
}

Categories

Resources