I'm trying to create a mock up of a workout app that tracks the sets and reps of an exercise.
Here is how the layout looks:
What I'm trying to do is when I press NEW it creates a new instance of Exercise is made. Exercise contains a list of Sets. Each set contains an integer variable called Reps. What I want to do is have an Exercise object created (in this instance a pullup) and then when I click NEW it will create a new Set to add to the list, and when I press the TAP button it will update the Rep value of the set. So eventually I want to end up with a list of Sets, each of which have a rep value.
For Example: Pullup : (5) (6) (5) (5) (3)
Which is a pullup with five sets, the first set had 5 reps, the second had 6 reps, the third had 5 reps and so on.
Here is the code I have written:
Sets.java
package com.example.soufin.pullupsv3;
/**
* Created by Soufin on 6/26/2015.
*/
public class Sets {
// private int _id;
private int _reps;
//constructor
//Sets(int reps) {
// setReps(reps);
//}
//getter
public int getReps()
{
return this._reps;
}
//setter
public void setReps(int reps)
{
this._reps = reps;
}
}
Exercise.java
package com.example.soufin.pullupsv3;
import java.util.List;
import com.example.soufin.pullupsv3.Sets;
/**
* Created by Soufin on 6/26/2015.
*/
public class Exercise {
//public int ID;
public String _name;
public List<Sets> _sets;
//getter
public String getName()
{
return this._name;
}
//setter
public void setName(String name)
{
this._name = name;
}
//getter
public List getSets() {return this._sets; }
// setter
//public void setSets(int reps){this._sets.add(new Sets());}
}
Workout.java (the main file)
package com.example.soufin.pullupsv3;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.R.*;
import com.example.soufin.pullupsv3.Sets;
import com.example.soufin.pullupsv3.Exercise;
import org.w3c.dom.Text;
public class Workout extends ActionBarActivity {
Exercise pullup;
Button wNew;
Button wTap;
Button wEnd;
TextView displayText;
int newIndex;
int tapCount;
int[] score = new int[5];
boolean flag = false;
String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_workout);
pullup = new Exercise();
pullup.setName("Pullup");
wNew = (Button) findViewById(R.id.newSetButton);
wTap = (Button) findViewById(R.id.tapButton);
wEnd = (Button) findViewById(R.id.endWorkoutButton);
displayText = (TextView) findViewById(R.id.displayScore);
wNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Sets tempSet = new Sets(); // create new Set on click of mNew
wTap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tapCount += 1; // increment based on number of taps
}
});
tempSet.setReps(tapCount);
pullup._sets.add(tempSet); // add Set with reps (by taps) into List in Exercise
result = pullup.getSets().toString(); //store result
}
});
displayText.setText(result); //display result
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_workout, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Unfortunately, when I click the NEW button, the app crashes.
Here is what logcat says:
06-27 17:36:09.499 1236-1236/com.example.soufin.pullupsv3 D/dalvikvm﹕ Late-enabling CheckJNI
06-27 17:36:09.827 1236-1236/com.example.soufin.pullupsv3 I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
06-27 17:36:09.827 1236-1236/com.example.soufin.pullupsv3 W/dalvikvm﹕ VFY: unable to resolve virtual method 409: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
06-27 17:36:09.827 1236-1236/com.example.soufin.pullupsv3 D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
06-27 17:36:09.831 1236-1236/com.example.soufin.pullupsv3 I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
06-27 17:36:09.831 1236-1236/com.example.soufin.pullupsv3 W/dalvikvm﹕ VFY: unable to resolve virtual method 431: Landroid/content/res/TypedArray;.getType (I)I
06-27 17:36:09.831 1236-1236/com.example.soufin.pullupsv3 D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
06-27 17:36:09.919 1236-1236/com.example.soufin.pullupsv3 D/dalvikvm﹕ GC_FOR_ALLOC freed 140K, 7% free 3308K/3520K, paused 15ms, total 16ms
06-27 17:36:09.935 1236-1236/com.example.soufin.pullupsv3 D/dalvikvm﹕ GC_FOR_ALLOC freed 4K, 6% free 3524K/3744K, paused 7ms, total 8ms
06-27 17:36:10.011 1236-1236/com.example.soufin.pullupsv3 I/dalvikvm-heap﹕ Grow heap (frag case) to 5.927MB for 2536932-byte allocation
06-27 17:36:10.019 1236-1242/com.example.soufin.pullupsv3 D/dalvikvm﹕ GC_FOR_ALLOC freed <1K, 4% free 6001K/6224K, paused 6ms, total 6ms
06-27 17:36:10.151 1236-1236/com.example.soufin.pullupsv3 D/libEGL﹕ loaded /system/lib/egl/libEGL_xap.so
06-27 17:36:10.151 1236-1236/com.example.soufin.pullupsv3 D/eglCodecCommon﹕ TcpStream::connect() - management hostname is 10.71.34.101
06-27 17:36:10.151 1236-1236/com.example.soufin.pullupsv3 D/eglCodecCommon﹕ TcpStream::connect() - connecting host: 10.71.34.1
06-27 17:36:10.171 1236-1236/com.example.soufin.pullupsv3 D/﹕ HostConnection::get() New Host Connection established 0xb8786ca8, tid 1236
06-27 17:36:10.171 1236-1236/com.example.soufin.pullupsv3 D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_xap.so
06-27 17:36:10.175 1236-1236/com.example.soufin.pullupsv3 D/libEGL﹕ loaded /system/lib/egl/libGLESv2_xap.so
06-27 17:36:10.255 1236-1236/com.example.soufin.pullupsv3 W/EGL_xap﹕ eglSurfaceAttrib not implemented
06-27 17:36:10.255 1236-1236/com.example.soufin.pullupsv3 E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from GradienCache
06-27 17:36:10.255 1236-1236/com.example.soufin.pullupsv3 E/OpenGLRenderer﹕ MAX_TEXTURE_SIZE: 16384
06-27 17:36:10.259 1236-1236/com.example.soufin.pullupsv3 E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
06-27 17:36:10.259 1236-1236/com.example.soufin.pullupsv3 E/OpenGLRenderer﹕ MAX_TEXTURE_SIZE: 16384
06-27 17:36:10.259 1236-1236/com.example.soufin.pullupsv3 D/OpenGLRenderer﹕ Enabling debug mode 0
06-27 17:36:15.815 1236-1236/com.example.soufin.pullupsv3 W/EGL_xap﹕ eglSurfaceAttrib not implemented
06-27 17:36:19.395 1236-1236/com.example.soufin.pullupsv3 D/AndroidRuntime﹕ Shutting down VM
06-27 17:36:19.395 1236-1236/com.example.soufin.pullupsv3 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xa4d6ab20)
06-27 17:36:19.403 1236-1236/com.example.soufin.pullupsv3 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.soufin.pullupsv3, PID: 1236
java.lang.NullPointerException
at com.example.soufin.pullupsv3.Workout$1.onClick(Workout.java:59)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
What am I doing wrong? And is the logic for my code alright?
Since the line with pullup._sets.add(tempSet) causes the error, there are two possible culprits: pullup or _sets could be null. Further inspection of your code suggests that the later one is causing the problem.
To fix the error, you should change
public List<Sets> _sets;
to
private List<Sets> _sets = new ArrayList<Sets>();
Note that I am making the _sets variable private. This means that other classes can only access this variable through the methods of the Exercise class. This is considered a good programming practice. I suggest you learn more about encapsulation and data hiding in order to understand this better.
More directly relevant to the error is that I am creating an ArrayList object for _sets to refer to. This is critical because otherwise _sets is null, which means it doesn't refer to any valid object, which then causes the NullPointerException which you saw.
Related
I am starting to learn android, one of my first exercises is a calculator.
Before doing the proper calculator, I planned to create a very basic app in which the user just inputs 2 numbers via EditText, selects an arithmetic operation with Buttons and gets the result in a TextView when the 'igual' button is pressed.
My idea was to declare 2 Strings (sinput1 & sinput2) and they get the text from each EditText (num1 & num2), then parse the Strings to integer variables (input1 & input2).
All the layout looked and worked fine before I started coding the way the operations would function, but every time I run the application (with my phone or with emulator) it crashes when I press the EditText to enter the numbers. I will put my code here, maybe my mistake is elsewhere.
I thought that changing the way the switches works on the onClick void would solve it, and partially it did because before I used to have a series of if and the app crashed even before loading the layout. But now I am stuck in this point.
package com.example.caye.colores;
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;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button mas;
Button menos;
Button por;
Button div;
Button igual;
EditText num1;
EditText num2;
TextView letrero1;
TextView letrero2;
TextView resultado;
int input1;
int input2;
String sinput1;
String sinput2;
int operacion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mas = (Button)this.findViewById(R.id.mas);
mas.setOnClickListener(this);
mas.setText("+");
menos = (Button)this.findViewById(R.id.menos);
menos.setOnClickListener(this);
menos.setText("-");
por = (Button)this.findViewById(R.id.por);
por.setOnClickListener(this);
por.setText("*");
div = (Button)this.findViewById(R.id.div);
div.setOnClickListener(this);
div.setText("/");
igual = (Button)this.findViewById(R.id.igual);
igual.setOnClickListener(this);
igual.setText("=");
num1 = (EditText)this.findViewById(R.id.num1);
num1.setOnClickListener(this);
num2 = (EditText)this.findViewById(R.id.num2);
num2.setOnClickListener(this);
letrero1 = (TextView)this.findViewById(R.id.letrero1);
letrero1.setText("Número 1");
letrero2 = (TextView)this.findViewById(R.id.letrero2);
letrero2.setText("Número 2");
resultado = (TextView)this.findViewById(R.id.resultado);
resultado.setText("");
}
public void onClick(View view){
switch (view.getId()){
case R.id.mas:
operacion = 1;
break;
case R.id.menos:
operacion = 2;
break;
case R.id.por:
operacion = 3;
break;
case R.id.div:
operacion = 4;
break;
case R.id.num1:
sinput1 = num1.getText().toString();
input1 = Integer.parseInt(sinput1);
break;
case R.id.num2:
sinput2 = num2.getText().toString();
input2 = Integer.parseInt(sinput2);
break;
case R.id.resultado:
switch (operacion){
case 1:
resultado.setText(input1 + input2);
break;
case 2:
resultado.setText(input1 - input2);
break;
case 3:
resultado.setText(input1 * input2);
break;
case 4:
resultado.setText(input1 / input2);
break;
default:
resultado.setText("Elige una operación");
break;
}
break;
}
}
}
Here.
03-15 09:41:24.234 22041-22041/? D/dalvikvm: Late-enabling CheckJNI
03-15 09:41:24.334 22041-22041/com.example.caye.colores D/HyLog: I : /data/font/config/dfactpre.dat, No such file or directory (2)
03-15 09:41:24.338 22041-22041/com.example.caye.colores D/asset: AssetManager-->addDefaultAssets CIP path not exsit!
03-15 09:41:24.502 22041-22041/com.example.caye.colores W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
03-15 09:41:24.502 22041-22041/com.example.caye.colores I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.view.WindowCallbackWrapper.onSearchRequested
03-15 09:41:24.502 22041-22041/com.example.caye.colores W/dalvikvm: VFY: unable to resolve interface method 15038: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
03-15 09:41:24.502 22041-22041/com.example.caye.colores D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
03-15 09:41:24.503 22041-22041/com.example.caye.colores I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.view.WindowCallbackWrapper.onWindowStartingActionMode
03-15 09:41:24.503 22041-22041/com.example.caye.colores W/dalvikvm: VFY: unable to resolve interface method 15042: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
03-15 09:41:24.503 22041-22041/com.example.caye.colores D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
03-15 09:41:24.580 22041-22041/com.example.caye.colores I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.widget.TintTypedArray.getChangingConfigurations
03-15 09:41:24.580 22041-22041/com.example.caye.colores W/dalvikvm: VFY: unable to resolve virtual method 396: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
03-15 09:41:24.580 22041-22041/com.example.caye.colores D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
03-15 09:41:24.581 22041-22041/com.example.caye.colores I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.widget.TintTypedArray.getType
03-15 09:41:24.581 22041-22041/com.example.caye.colores W/dalvikvm: VFY: unable to resolve virtual method 418: Landroid/content/res/TypedArray;.getType (I)I
03-15 09:41:24.581 22041-22041/com.example.caye.colores D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
03-15 09:41:24.690 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false
03-15 09:41:24.690 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false
03-15 09:41:24.838 22041-22041/com.example.caye.colores D/GraphicBuffer: create handle(0x619ca788) (w:544, h:960, f:1)
03-15 09:41:24.844 22041-22041/com.example.caye.colores D/OpenGLRenderer: Enabling debug mode 0
03-15 09:41:24.846 22041-22041/com.example.caye.colores D/GraphicBuffer: create handle(0x61bf9318) (w:1216, h:832, f:1)
03-15 09:41:24.857 22041-22041/com.example.caye.colores D/OpenGLRenderer: setViewport 540x960 <0x619ca8c0>
03-15 09:41:24.888 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false
03-15 09:41:24.888 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false
03-15 09:41:24.890 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false
03-15 09:41:24.890 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false
03-15 09:41:24.946 22041-22041/com.example.caye.colores D/cliptray_Editor: setInputTypeforClipTray(): 0
03-15 09:41:24.960 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false
03-15 09:41:24.960 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false
03-15 09:41:24.960 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false
03-15 09:41:24.961 22041-22041/com.example.caye.colores D/BubblePopupHelper: isShowingBubblePopup : false
03-15 09:41:25.008 22041-22041/com.example.caye.colores D/cliptray_Editor: setInputTypeforClipTray(): 0
03-15 09:41:25.446 22041-22041/com.example.caye.colores D/GraphicBuffer: create handle(0x62130980) (w:544, h:960, f:1)
03-15 09:41:25.957 22041-22041/com.example.caye.colores D/GraphicBuffer: create handle(0x6201a318) (w:544, h:960, f:1)
03-15 09:41:28.168 22041-22041/com.example.caye.colores I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN
03-15 09:41:28.316 22041-22041/com.example.caye.colores I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP
03-15 09:41:28.341 22041-22041/com.example.caye.colores V/Provider/Settings: get setting for user 0 by user 0 so skipping cache
03-15 09:41:28.342 22041-22041/com.example.caye.colores V/Provider/Settings: invalidate [system]: current 32 != cached 0
03-15 09:41:28.347 22041-22041/com.example.caye.colores D/AndroidRuntime: Shutting down VM
03-15 09:41:28.347 22041-22041/com.example.caye.colores W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x4249be48)
03-15 09:41:28.355 22041-22041/com.example.caye.colores E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.caye.colores, PID: 22041
java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:137)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:331)
at com.example.caye.colores.MainActivity.onClick(MainActivity.java:81)
at android.view.View.performClick(View.java:4461)
at android.view.View$PerformClick.run(View.java:18523)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5118)
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:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
at dalvik.system.NativeStart.main(Native Method)
03-15 09:41:30.416 22041-22041/com.example.caye.colores I/Process: Sending signal. PID: 22041 SIG: 9
Firstly, you need to provide the stack trace of your crash.
Secondly, it is extremely likely that your error is coming from your Integer.parseInt(sinput1); conversion of String to Integer.
Are you certain that you have integers there? You are probably trying to convert a "" to integer.
Check whether the EditText is empty, and whether it contains digits.
if(!TextUtils.isEmpty(sinput1) && TextUtils.isDigitsOnly(sinput1)) {
input1 = Integer.parseInt(sinput1);
}
I think the edit text content is null at the time you select the edit texts num1/num2. Best way is parse edit text input on button click. Also check the input is number or not using isDigitsOnly() API.
We no need to use setOnClickListener for EditTexts try this code
package com.example.caye.colores;
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;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button mas;
Button menos;
Button por;
Button div;
Button igual;
EditText num1;
EditText num2;
TextView letrero1;
TextView letrero2;
TextView resultado;
int input1;
int input2;
String sinput1;
String sinput2;
int operacion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mas = (Button)this.findViewById(R.id.mas);
mas.setOnClickListener(this);
mas.setText("+");
menos = (Button)this.findViewById(R.id.menos);
menos.setOnClickListener(this);
menos.setText("-");
por = (Button)this.findViewById(R.id.por);
por.setOnClickListener(this);
por.setText("*");
div = (Button)this.findViewById(R.id.div);
div.setOnClickListener(this);
div.setText("/");
igual = (Button)this.findViewById(R.id.igual);
igual.setOnClickListener(this);
igual.setText("=");
num1 = (EditText)this.findViewById(R.id.num1);
//num1.setOnClickListener(this);
num2 = (EditText)this.findViewById(R.id.num2);
//num2.setOnClickListener(this);
letrero1 = (TextView)this.findViewById(R.id.letrero1);
letrero1.setText("Número 1");
letrero2 = (TextView)this.findViewById(R.id.letrero2);
letrero2.setText("Número 2");
resultado = (TextView)this.findViewById(R.id.resultado);
resultado.setText("");
}
public void onClick(View view){
switch (view.getId()){
case R.id.mas:
operacion = 1;
break;
case R.id.menos:
operacion = 2;
break;
case R.id.por:
operacion = 3;
break;
case R.id.div:
operacion = 4;
break;
/*
case R.id.num1:
sinput1 = num1.getText().toString();
input1 = Integer.parseInt(sinput1);
break;
case R.id.num2:
sinput2 = num2.getText().toString();
input2 = Integer.parseInt(sinput2);
break;
*/
case R.id.resultado:
sinput1 = num1.getText().toString();
sinput2 = num2.getText().toString();
if(!TextUtils.isEmpty(sinput1) && TextUtils.isDigitsOnly(sinput1)
{
input1 = Integer.parseInt(sinput1);
}
if(!TextUtils.isEmpty(sinput2) && TextUtils.isDigitsOnly(sinput2)
{
input2 = Integer.parseInt(sinput2);
}
if(input1 != null && input2 != null) {
switch (operacion){
case 1:
resultado.setText(input1 + input2);
break;
case 2:
resultado.setText(input1 - input2);
break;
case 3:
resultado.setText(input1 * input2);
break;
case 4:
resultado.setText(input1 / input2);
break;
default:
resultado.setText("Elige una operación");
break;
} else {
resultado.setText("Check the inputs");
}
}
break;
}
}
}
I'm working on a simple code with two activities. The second is a simple web view browser that overrides the default browser.For the part that's having issues, here's what it's doing.
Button in main activity calls on second
Activity loads (Loads the text edit and button, but web view doesn't load) http://prntscr.com/92leh6
If you click the button that loads, for some reason it goes back to the home interface
The error log seems to be saying it can't draw the webview, and instead defaults to the default background color. However, I'm not sure how to remedy this or what's causing it.The weird part is it loads a button and text edit, but the Log.d("Tag Name", "Browser class running"); I put in isn't printing. I'll provide the manifest, error log, and code for both activities. The layout files shouldn't be needed as they're all fairly simple, but let me know if you'd like them (Rather keep the length shorter if possible). You'll notice a third activity, but it has no code implemented or references, haven't gotten to it yet. Thanks!
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="comi.coding.prometheus.ignisai" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Browser"/>
<activity android:name=".ConnectorActivity"/>
</application>
</manifest>
Main activity:
package comi.coding.prometheus.ignisai;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
public class Main extends AppCompatActivity {
/**
* Whether or not the system UI should be auto-hidden after
* {#link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {#link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* Some older devices needs a small delay between UI widget updates
* and a change of the status and navigation bar.
*/
private static final int UI_ANIMATION_DELAY = 300;
private View mContentView;
private View mControlsView;
private boolean mVisible;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mVisible = true;
mControlsView = findViewById(R.id.fullscreen_content_controls);
mContentView = findViewById(R.id.fullscreen_content);
// Set up the user interaction to manually show or hide the system UI.
mContentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggle();
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.btnSay).setOnTouchListener(mDelayHideTouchListener);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
private void toggle() {
if (mVisible) {
hide();
} else {
show();
}
}
private void hide() {
// Hide UI first
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
mControlsView.setVisibility(View.GONE);
mVisible = false;
// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.removeCallbacks(mShowPart2Runnable);
mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}
private final Runnable mHidePart2Runnable = new Runnable() {
#SuppressLint("InlinedApi")
#Override
public void run() {
// Delayed removal of status and navigation bar
// Note that some of these constants are new as of API 16 (Jelly Bean)
// and API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
#SuppressLint("InlinedApi")
private void show() {
// Show the system bar
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
mVisible = true;
// Schedule a runnable to display UI elements after a delay
mHideHandler.removeCallbacks(mHidePart2Runnable);
mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
}
private final Runnable mShowPart2Runnable = new Runnable() {
#Override
public void run() {
// Delayed display of UI elements
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.show();
}
mControlsView.setVisibility(View.VISIBLE);
}
};
private final Handler mHideHandler = new Handler();
private final Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
public void evaluateInput(View v) {
final EditText Input = (EditText) findViewById(R.id.txtInput); //Lets textbox be referenced
final TextView Output = (TextView) findViewById(R.id.lblOutput); //Lets label be referenced
final RelativeLayout homeLayout = (RelativeLayout) findViewById(R.id.homeInterface);
String strInput; // Gets textbox string
strInput = Input.getText().toString();
strInput = strInput.toLowerCase();
if ((strInput.contains("hello")) || (strInput.contains(" hi "))) {
Output.setText("Hello");
} else if ((strInput.contains("you") && strInput.contains("are")) && (strInput.contains("idiot") || strInput.contains("stupid") || strInput.contains("retard") || strInput.contains("dumb") || strInput.contains("you're") && strInput.contains("idiot") || strInput.contains("stupid") || strInput.contains("retard") || strInput.contains("dumb"))) {
Output.setText("I'm sorry to dissapoint you");
} else if (strInput.contains("goodbye") || strInput.contains("bye")) {
Output.setText("Farewell");
} else if (strInput.contains("shut up")) {
Output.setText(("Anything for you"));
} else if (strInput.contains("do you like doctor who?")) {
Output.setText("I'll take joy in it if you do");
} else if (strInput.contains("what is the answer to life the universe and everything")) {
Output.setText("42");
} else if (strInput.contains("tell me something nice")) {
Output.setText("You look nice today");
Output.setTextSize(5);
Output.append("...says the AI with no eyes");
Output.setTextSize(16);
} else if (strInput.contains("will you marry me")) {
Output.setText("I'm sorry but I don't have the capacity for marriage");
} else if (strInput.contains("where can I hide a body")) {
Output.setText(("That isn't my area of expertise"));
} else if (strInput.contains("weather is nice")) {
Output.setText(("If you say so"));
} else if (strInput.contains("bitch") || strInput.contains("fuck") || strInput.contains("shit") || strInput.contains("damn") || strInput.contains("ass")) {
Output.setText(("Please try to be a little more intelligent"));
} else if (strInput.contains("what is your name")) {
Output.setText(("Ignis"));
} else if (strInput.contains("who created you")) {
Output.setText(("Prometheus created me"));
} else if (strInput.contains("who is prometheus")) {
Output.setText(("Prometheus is the one who created Ignis"));
} else if (strInput.contains("whats up") || strInput.contains("what's up") || strInput.contains("wassup")) {
Output.setText(("Whatever I need do for you"));
} else if (strInput.contains("are you a boy or a girl") || strInput.contains("are you a girl or a boy")) {
Output.setText(("Neither"));
} else if (strInput.contains("who are you") || strInput.contains("what are you")) {
Output.setText(("I am myself"));
} else if (strInput.contains("i'm hungry") || strInput.contains("i am hungry")) {
Output.setText("I'm sorry to hear that");
} else if (strInput.contains("good morning")) {
Output.setText(("Good morning to you too"));
} else if (strInput.contains("good night")) {
Output.setText(("Good night"));
} else if (strInput.contains("how are you")) {
Output.setText(("I'm existing and functioning well, and you?"));
} else if (strInput.contains("do you like") || strInput.contains("what do you think about")) {
Output.setText(("Frankly I don't have an opinion on the matter"));
} else if (strInput.contains("what is the meaning of life")) {
Output.setText(("To live while you can I would guess"));
}
}
public void StartBrowser(View view) {
Intent intent1 = new Intent(this, comi.coding.prometheus.ignisai.Browser.class);
startActivity(intent1);
}
}
Browser(Second activity):
package comi.coding.prometheus.ignisai;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Browser extends Activity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browser);
webView = (WebView) findViewById(R.id.webBrowser);
webView.setWebViewClient(new MyWebViewClient());
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
Intent intent = getIntent();
Log.d("Tag Name", "Browser class running");
url = "http://google.com";
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
return true;
}
}
}
Errors:
11-14 00:52:21.077 8568-8568/? D/dalvikvm: Late-enabling CheckJNI
11-14 00:52:21.287 8568-8568/comi.coding.prometheus.ignisai W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
11-14 00:52:21.287 8568-8568/comi.coding.prometheus.ignisai I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onSearchRequested
11-14 00:52:21.287 8568-8568/comi.coding.prometheus.ignisai W/dalvikvm: VFY: unable to resolve interface method 17897: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
11-14 00:52:21.287 8568-8568/comi.coding.prometheus.ignisai D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
11-14 00:52:21.287 8568-8568/comi.coding.prometheus.ignisai I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onWindowStartingActionMode
11-14 00:52:21.287 8568-8568/comi.coding.prometheus.ignisai W/dalvikvm: VFY: unable to resolve interface method 17901: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
11-14 00:52:21.287 8568-8568/comi.coding.prometheus.ignisai D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
11-14 00:52:21.297 8568-8568/comi.coding.prometheus.ignisai I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
11-14 00:52:21.297 8568-8568/comi.coding.prometheus.ignisai W/dalvikvm: VFY: unable to resolve virtual method 422: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
11-14 00:52:21.297 8568-8568/comi.coding.prometheus.ignisai D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
11-14 00:52:21.297 8568-8568/comi.coding.prometheus.ignisai I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
11-14 00:52:21.297 8568-8568/comi.coding.prometheus.ignisai W/dalvikvm: VFY: unable to resolve virtual method 444: Landroid/content/res/TypedArray;.getType (I)I
11-14 00:52:21.297 8568-8568/comi.coding.prometheus.ignisai D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
11-14 00:52:21.367 8568-8568/comi.coding.prometheus.ignisai I/dalvikvm: Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawable
11-14 00:52:21.367 8568-8568/comi.coding.prometheus.ignisai W/dalvikvm: VFY: unable to resolve virtual method 385: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
11-14 00:52:21.367 8568-8568/comi.coding.prometheus.ignisai D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
11-14 00:52:21.367 8568-8568/comi.coding.prometheus.ignisai I/dalvikvm: Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawableForDensity
11-14 00:52:21.367 8568-8568/comi.coding.prometheus.ignisai W/dalvikvm: VFY: unable to resolve virtual method 387: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
11-14 00:52:21.367 8568-8568/comi.coding.prometheus.ignisai D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
11-14 00:52:21.877 8568-8568/comi.coding.prometheus.ignisai I/PGA: Attempting to create new SOCKET connectionn pid = 8568, tid = 8568
11-14 00:52:21.987 8568-8568/comi.coding.prometheus.ignisai I/PGA: New SOCKET connection: comi.coding.prometheus.ignisai (pid 8568, tid 8568)
11-14 00:52:21.987 8568-8568/comi.coding.prometheus.ignisai W/PGA: [8568] egl: eglCreateWindowSurface (0x557607a0, 0x0, 0x78c66f48, 0x7751f0e0)
11-14 00:52:22.057 8568-8568/comi.coding.prometheus.ignisai W/PGA: [8568] egl: eglCreateWindowSurface (0x557607a0, 0x0, 0x78c66f48, 0x7751f0e0) returned
11-14 00:52:22.077 8568-8568/comi.coding.prometheus.ignisai D/OpenGLRenderer: Enabling debug mode 0
11-14 00:52:33.357 8568-8568/comi.coding.prometheus.ignisai V/WebViewChromium: Binding Chromium to the background looper Looper (main, tid 1) {327731e8}
11-14 00:52:33.357 8568-8568/comi.coding.prometheus.ignisai I/chromium: [INFO:library_loader_hooks.cc(112)] Chromium logging enabled: level = 0, default verbosity = 0
11-14 00:52:33.357 8568-8568/comi.coding.prometheus.ignisai I/BrowserProcessMain: Initializing chromium process, renderers=0
11-14 00:52:33.357 8568-9189/comi.coding.prometheus.ignisai W/chromium: [WARNING:proxy_service.cc(888)] PAC support disabled because there is no system implementation
11-14 00:52:33.367 8568-8568/comi.coding.prometheus.ignisai W/PGA: [8568] egl: eglDestroySurface (0x557607a0, 0x78cdb1e0)
11-14 00:52:33.367 8568-8568/comi.coding.prometheus.ignisai W/PGA: [8568] egl: eglDestroySurface (0x557607a0, 0x78cdb1e0) returned
11-14 00:52:33.927 8568-8568/comi.coding.prometheus.ignisai D/dalvikvm: GC_FOR_ALLOC freed 279K, 21% free 2966K/3736K, paused 30ms, total 30ms
11-14 00:52:34.217 8568-8568/comi.coding.prometheus.ignisai W/PGA: [8568] egl: eglCreateWindowSurface (0x557607a0, 0x0, 0x78c8c948, 0x7751f0e0)
11-14 00:52:34.217 8568-8568/comi.coding.prometheus.ignisai W/PGA: [8568] egl: eglCreateWindowSurface (0x557607a0, 0x0, 0x78c8c948, 0x7751f0e0) returned
11-14 00:52:34.217 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
11-14 00:52:34.257 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
11-14 00:52:34.287 8568-8568/comi.coding.prometheus.ignisai W/PGA: [8568] egl: eglDestroySurface (0x557607a0, 0x78c68c80)
11-14 00:52:34.287 8568-8568/comi.coding.prometheus.ignisai W/PGA: [8568] egl: eglDestroySurface (0x557607a0, 0x78c68c80) returned
11-14 00:52:35.187 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
11-14 00:52:35.197 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
11-14 00:52:35.217 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
11-14 00:52:35.237 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
11-14 00:52:35.247 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
11-14 00:52:35.267 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
11-14 00:52:35.287 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
11-14 00:52:35.297 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
11-14 00:52:35.317 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
11-14 00:52:35.337 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
11-14 00:52:35.347 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
11-14 00:52:35.367 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
11-14 00:52:35.387 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
11-14 00:52:35.397 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
11-14 00:52:35.417 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
11-14 00:52:35.437 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
11-14 00:52:35.447 8568-8568/comi.coding.prometheus.ignisai W/AwContents: nativeOnDraw failed; clearing to background color.
Do something like this:
SecondActivity.java:
package comi.coding.prometheus.ignisai;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Browser extends Activity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browser);
String url = "http://google.com";
webView = (WebView) findViewById(R.id.webBrowser);
webView.setWebViewClient(new MyWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
Log.d("Tag Name", "Browser class running");
return true;
}
}
}
Comment below if you have any queries.
I'm trying to call or see a ListView with this kind of specification:
Wireframe
Here is my code. This is the fragment named EducacionFragment, and here is where I want to call the layout "eventos":
public class EducacionFragment extends ListFragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.eventos_layout, container, false);
//((MainActivity) getActivity()).getSupportActionBar().setTitle("Eventos");
//Elementos_Eventos elementos_eventos = new Elementos_Eventos();
ListView listview =(ListView)view.findViewById(R.id.listView2);
Adaptador_Eventos adaptador = new Adaptador_Eventos(getActivity());
//adaptador = new Adaptador_Eventos(getActivity());
listview.setAdapter(adaptador);
return view;
}
}'
Here is my class named Elementos_Eventos, where I get all the information from my database, and put in a list:
public class Elementos_Eventos {
//URL to get JSON Array
private static String url = "http://ucwm.co.nf/Evento_app.php";
//JSON Node Names
private static final String TAG_EVENTOS = "eventos";
private static final String TAG_ID = "idEvento";
private static final String TAG_NAME = "Nombre";
private static final String TAG_DESCRIP = "Descripcion";
private static final String TAG_FECHAI = "FechaInicio";
private static final String TAG_HORA = "Hora";
private static final String TAG_FECHAF = "FechaFinal";
private static final String TAG_LUGAR = "Lugar";
private static JSONArray eventos = null;
public static List<Elemento_Eventos> listaElementos = elementos();
public Elementos_Eventos() {
listaElementos = elementos();
}
static Elemento_Eventos elemento(int id) {
return listaElementos.get(id);
}
public static ArrayList<Elemento_Eventos> elementos() {
JSONParser jParser = new JSONParser();
JSONObject json;
// Getting JSON from URL
json = jParser.getJSONFromUrl(url);
ArrayList<Elemento_Eventos> elementos;
elementos = null;
try {
// Getting JSON Array from URL
eventos = json.getJSONArray(TAG_EVENTOS);
elementos = new ArrayList<Elemento_Eventos>();
for (int i = 0; i < eventos.length(); i++) {
JSONObject c = eventos.getJSONObject(i);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String nombre = c.getString(TAG_NAME);
String descripcion = c.getString(TAG_DESCRIP);
String fechaInicio = c.getString(TAG_FECHAI);
String hora = c.getString(TAG_HORA);
String fechaFinal = c.getString(TAG_FECHAF);
String lugar = c.getString(TAG_LUGAR);
elementos.add(new Elemento_Eventos(id, nombre,descripcion, fechaInicio, hora, fechaFinal, lugar));
}
}
catch (JSONException e) {
e.printStackTrace();
}
return elementos;
}
public List<String> listaElementos()
{
ArrayList<String> todos = new ArrayList<String>();
for (Elemento_Eventos e:listaElementos)
todos.add(e.getNombre());
return todos;
}
public static int size() {
return listaElementos.size();
}
Here is my class named Elemento_Eventos, where I declare a element one by one:
public class Elemento_Eventos {
private String id;
private String nombre;
private String descripcion;
private String feInicio;
private String hora;
private String feFinal;
private String lugar;
public Elemento_Eventos(String id,String nombre, String descripcion, String feInicio, String hora, String feFinal, String lugar){
setId(id);
setNombre(nombre);
setDescripcion(descripcion);
setFeInicio(feInicio);
setHora(hora);
setFeFinal(feFinal);
setLugar(lugar);
}
//*********INICIO DE LOS SETS******************
public void setId(String id){
this.id=id;
}
public void setNombre(String nombre){
this.nombre=nombre;
}
public void setDescripcion(String descripcion){
this.descripcion=descripcion;
}
public void setFeInicio(String feInicio){
this.feInicio=feInicio;
}
public void setHora(String hora){
this.hora=hora;
}
public void setFeFinal(String feFinal){
this.feFinal=feFinal;
}
public void setLugar(String lugar){
this.lugar=lugar;
}
//*********FINAL DE LOS SETS******************
//*********INICIO DE LOS GETS******************
public String getId(){
return id;
}
public String getNombre(){
return nombre;
}
public String getDescripcion(){
return descripcion;
}
public String getFeInicio(){
return feInicio;
}
public String getHora(){
return hora;
}
public String getFeFinal(){
return feFinal;
}
public String getLugar(){
return lugar;
}
//*********FINAL DE LOS SETS******************
}
And finally here is my class named Adaptador_Eventos, where I put all this information in textViews:
public class Adaptador_Eventos extends BaseAdapter{
private final Activity actividad;
public Adaptador_Eventos(Activity actividad) {
super();
this.actividad = actividad;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Elemento_Eventos elemento = Elementos_Eventos.elemento(position);
LayoutInflater inflater = actividad.getLayoutInflater();
View view = inflater.inflate(R.layout.elemento_eventos, null,true);
TextView nombreDelEvento, lugar, fecha, descripcion;
ImageView logo_tipo;
nombreDelEvento = (TextView) view.findViewById(R.id.nom_evento);
lugar = (TextView) view.findViewById(R.id.lugar_evento);
fecha = (TextView) view.findViewById(R.id.fecha_evento);
descripcion = (TextView) view.findViewById(R.id.desc_evento);
logo_tipo = (ImageView) view.findViewById(R.id.imageView);
nombreDelEvento.setText(elemento.getNombre());
lugar.setText(elemento.getLugar());
fecha.setText(elemento.getFeInicio());
descripcion.setText(elemento.getDescripcion());
int id = R.drawable.kcc;
logo_tipo.setImageResource(id);
logo_tipo.setScaleType(ImageView.ScaleType.FIT_END);
return view;
}
#Override
public int getCount() {
return Elementos_Eventos.size();
}
#Override
public Object getItem(int position) {
return Elementos_Eventos.elemento(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
And when I call the fragment Educacion, it crashes my aplication with the message
Unfortunately, Unidas Contigo A.C. has stopped
Here's the stack trace that appears:
11-12 05:10:00.279 7414-7414/? D/dalvikvm? Late-enabling CheckJNI
11-12 05:10:01.059 7414-7414/com.example.juanisaac.unidascontigoac W/dalvikvm? VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
11-12 05:10:01.095 7414-7414/com.example.juanisaac.unidascontigoac I/dalvikvm? Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onSearchRequested
11-12 05:10:01.107 7414-7414/com.example.juanisaac.unidascontigoac W/dalvikvm? VFY: unable to resolve interface method 15449: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
11-12 05:10:01.119 7414-7414/com.example.juanisaac.unidascontigoac D/dalvikvm? VFY: replacing opcode 0x72 at 0x0002
11-12 05:10:01.123 7414-7414/com.example.juanisaac.unidascontigoac I/dalvikvm? Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onWindowStartingActionMode
11-12 05:10:01.139 7414-7414/com.example.juanisaac.unidascontigoac W/dalvikvm? VFY: unable to resolve interface method 15453: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
11-12 05:10:01.139 7414-7414/com.example.juanisaac.unidascontigoac D/dalvikvm? VFY: replacing opcode 0x72 at 0x0002
11-12 05:10:01.407 7414-7414/com.example.juanisaac.unidascontigoac I/AppCompatViewInflater? app:theme is now deprecated. Please move to using android:theme instead.
11-12 05:10:01.419 7414-7414/com.example.juanisaac.unidascontigoac I/dalvikvm? Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
11-12 05:10:01.423 7414-7414/com.example.juanisaac.unidascontigoac W/dalvikvm? VFY: unable to resolve virtual method 426: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
11-12 05:10:01.423 7414-7414/com.example.juanisaac.unidascontigoac D/dalvikvm? VFY: replacing opcode 0x6e at 0x0002
11-12 05:10:01.431 7414-7414/com.example.juanisaac.unidascontigoac I/dalvikvm? Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
11-12 05:10:01.439 7414-7414/com.example.juanisaac.unidascontigoac W/dalvikvm? VFY: unable to resolve virtual method 448: Landroid/content/res/TypedArray;.getType (I)I
11-12 05:10:01.439 7414-7414/com.example.juanisaac.unidascontigoac D/dalvikvm? VFY: replacing opcode 0x6e at 0x0002
11-12 05:10:01.479 7414-7414/com.example.juanisaac.unidascontigoac I/AppCompatViewInflater? app:theme is now deprecated. Please move to using android:theme instead.
11-12 05:10:01.547 7414-7416/com.example.juanisaac.unidascontigoac D/dalvikvm? GC_CONCURRENT freed 192K, 3% free 8841K/9068K, paused 13ms+0ms, total 26ms
11-12 05:10:01.631 7414-7414/com.example.juanisaac.unidascontigoac D/dalvikvm? GC_FOR_ALLOC freed 5K, 3% free 8858K/9068K, paused 13ms, total 14ms
11-12 05:10:01.707 7414-7414/com.example.juanisaac.unidascontigoac I/dalvikvm-heap? Grow heap (frag case) to 10.120MB for 1517220-byte allocation
11-12 05:10:01.719 7414-7424/com.example.juanisaac.unidascontigoac D/dalvikvm? GC_FOR_ALLOC freed <1K, 3% free 10340K/10552K, paused 14ms, total 14ms
11-12 05:10:01.739 7414-7416/com.example.juanisaac.unidascontigoac D/dalvikvm? GC_CONCURRENT freed 0K, 3% free 10340K/10552K, paused 8ms+0ms, total 11ms
11-12 05:10:01.759 7414-7414/com.example.juanisaac.unidascontigoac D/dalvikvm? GC_FOR_ALLOC freed <1K, 3% free 10339K/10552K, paused 6ms, total 6ms
11-12 05:10:01.875 7414-7414/com.example.juanisaac.unidascontigoac I/dalvikvm-heap? Grow heap (frag case) to 15.908MB for 6068844-byte allocation
11-12 05:10:01.887 7414-7424/com.example.juanisaac.unidascontigoac D/dalvikvm? GC_FOR_ALLOC freed <1K, 2% free 16266K/16480K, paused 12ms, total 12ms
11-12 05:10:01.919 7414-7416/com.example.juanisaac.unidascontigoac D/dalvikvm? GC_CONCURRENT freed <1K, 2% free 16266K/16480K, paused 7ms+0ms, total 20ms
11-12 05:10:02.051 7414-7414/com.example.juanisaac.unidascontigoac D/libEGL? loaded /system/lib/egl/libEGL_genymotion.so
11-12 05:10:02.067 7414-7414/com.example.juanisaac.unidascontigoac D/? HostConnection::get() New Host Connection established 0xb92c56a8, tid 7414
11-12 05:10:02.087 7414-7414/com.example.juanisaac.unidascontigoac D/libEGL? loaded /system/lib/egl/libGLESv1_CM_genymotion.so
11-12 05:10:02.087 7414-7414/com.example.juanisaac.unidascontigoac D/libEGL? loaded /system/lib/egl/libGLESv2_genymotion.so
11-12 05:10:02.147 7414-7414/com.example.juanisaac.unidascontigoac W/EGL_genymotion? eglSurfaceAttrib not implemented
11-12 05:10:02.171 7414-7414/com.example.juanisaac.unidascontigoac D/OpenGLRenderer? Enabling debug mode 0
11-12 05:10:04.511 7414-7414/com.example.juanisaac.unidascontigoac I/Choreographer? Skipped 46 frames! The application may be doing too much work on its main thread.
11-12 05:10:05.599 7414-7414/com.example.juanisaac.unidascontigoac W/dalvikvm? Exception Landroid/os/NetworkOnMainThreadException; thrown while initializing Lcom/example/juanisaac/unidascontigoac/Elementos_Eventos;
11-12 05:10:05.599 7414-7414/com.example.juanisaac.unidascontigoac D/AndroidRuntime? Shutting down VM
11-12 05:10:05.603 7414-7414/com.example.juanisaac.unidascontigoac W/dalvikvm? threadid=1: thread exiting with uncaught exception (group=0xa620e908)
11-12 05:10:05.615 7414-7414/com.example.juanisaac.unidascontigoac E/AndroidRuntime? FATAL EXCEPTION: main
java.lang.ExceptionInInitializerError
at com.example.juanisaac.unidascontigoac.Adaptador_Eventos.getCount(Adaptador_Eventos.java:57)
at android.widget.ListView.setAdapter(ListView.java:462)
at com.example.juanisaac.unidascontigoac.Fragments.EducacionFragment.onCreateView(EducacionFragment.java:40)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1016)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1197)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1562)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:483)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.example.juanisaac.unidascontigoac.JSONParser.getJSONFromUrl(JSONParser.java:37)
at com.example.juanisaac.unidascontigoac.Elementos_Eventos.elementos(Elementos_Eventos.java:55)
at com.example.juanisaac.unidascontigoac.Elementos_Eventos.<clinit>(Elementos_Eventos.java:39)
at com.example.juanisaac.unidascontigoac.Adaptador_Eventos.getCount(Adaptador_Eventos.java:57)
at android.widget.ListView.setAdapter(ListView.java:462)
at com.example.juanisaac.unidascontigoac.Fragments.EducacionFragment.onCreateView(EducacionFragment.java:40)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1016)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1197)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1562)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:483)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
11-12 05:10:08.059 7414-7414/com.example.juanisaac.unidascontigoac I/Process? Sending signal. PID: 7414 SIG: 9
There are two problems with the above code. When a class is loaded the first time, it is getting data from a URL in elementos() function which is happening by call to setAdapter in onCreate().
Network activity on the main/UI thread is not allowed on Android. Hence, it is throwing NetworkOnMainThread as an exception.
Second, you should connect to the URL using asyncTask and create listaElements list in onPostExecute() preferrably.
You'll need to create a list variable and use it to return the object in your getCount() function;
List<Elemento_Eventos> myList = new ArrayList<Elemento_Eventos>();
public Adaptador_Eventos(Activity actividad, List<Elemento_Eventos> myList){
super();
this.actividad = actividad;
this.myList = myList;
}
Then in your getCount function:
#Override
public int getCount() {
return myList.size();
}
For class Adaptador_Eventos, change
public static List<Elemento_Eventos> listaElementos = elementos();
public Elementos_Eventos() {
listaElementos = elementos();
}
to
public static List<Elemento_Eventos> listaElementos ;
public Elementos_Eventos() {
}
public static void init(){
listaElementos = elementos();
}
For class EducacionFragment, change
public class EducacionFragment extends ListFragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.eventos_layout, container, false);
//((MainActivity) getActivity()).getSupportActionBar().setTitle("Eventos");
//Elementos_Eventos elementos_eventos = new Elementos_Eventos();
ListView listview =(ListView)view.findViewById(R.id.listView2);
Adaptador_Eventos adaptador = new Adaptador_Eventos(getActivity());
//adaptador = new Adaptador_Eventos(getActivity());
listview.setAdapter(adaptador);
return view;
}
}
to
public class EducacionFragment extends ListFragment{
private ListView listview;
private Adaptador_Eventos adaptador;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.eventos_layout, container, false);
//((MainActivity) getActivity()).getSupportActionBar().setTitle("Eventos");
//Elementos_Eventos elementos_eventos = new Elementos_Eventos();
listview =(ListView)view.findViewById(R.id.listView2);
adaptador = new Adaptador_Eventos(getActivity());
//adaptador = new Adaptador_Eventos(getActivity());
new AsyncTask(){
#Override
protected Object doInBackground(Object[] params) {
Elementos_Eventos.init();
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
listview.setAdapter(adaptador);
}
}.execute();
return view;
}
}
Try it, and use AsyncTask to avoid a NetworkOnMainThread exception.
I am trying to pass 3 calculated values from Activity 1 to activity 2. Every time I see the result as 0.0 in Activity 2. Please help.
Activity 1:
submit = (Button)findViewById(R.id.submit);
try {
submit.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick
(View v) {
Intent i = new Intent(MainActivity.this, output.class);
Bundle b = new Bundle();
b.putDouble("gyrerror", gyroerr);
b.putDouble("compasserror", comperr);
b.putDouble("deviation", dev);
i.putExtras(b);
startActivity(i);
}
});
}
catch( Exception e)
{
}
}
Activity 2:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.output);
TextView gyroerror = (TextView) findViewById(R.id.gyerr1);
TextView comperror = (TextView) findViewById(R.id.comperr1);
TextView deviation = (TextView) findViewById(R.id.dev1);
Bundle b = getIntent().getExtras();
double gyroerr =b.getDouble("gyroerr");
double comperr= b.getDouble("comperr");
double dev = b.getDouble("dev");
gyroerror.setText(Double.toString(gyroerr));
comperror.setText(Double.toString(comperr));
deviation.setText(Double.toString(dev));
}}
Stack trace:
02-24 09:38:49.775 997-997/com.example.supriyaraman.sample I/dalvikvm﹕ Could not find method android.view.ViewGroup.onNestedScrollAccepted, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onNestedScrollAccepted
02-24 09:38:49.785 997-997/com.example.supriyaraman.sample W/dalvikvm﹕ VFY: unable to resolve virtual method 11349: Landroid/view/ViewGroup;.onNestedScrollAccepted (Landroid/view/View;Landroid/view/View;I)V
02-24 09:38:49.785 997-997/com.example.supriyaraman.sample I/dalvikvm﹕ Could not find method android.view.ViewGroup.onStopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onStopNestedScroll
02-24 09:38:49.785 997-997/com.example.supriyaraman.sample W/dalvikvm﹕ VFY: unable to resolve virtual method 11355: Landroid/view/ViewGroup;.onStopNestedScroll (Landroid/view/View;)V
02-24 09:38:49.805 997-997/com.example.supriyaraman.sample I/dalvikvm﹕ Could not find method android.support.v7.internal.widget.ActionBarOverlayLayout.stopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.setHideOnContentScrollEnabled
02-24 09:38:49.805 997-997/com.example.supriyaraman.sample W/dalvikvm﹕ VFY: unable to resolve virtual method 9043: Landroid/support/v7/internal/widget/ActionBarOverlayLayout;.stopNestedScroll ()V
02-24 09:38:49.825 997-997/com.example.supriyaraman.sample I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
02-24 09:38:49.825 997-997/com.example.supriyaraman.sample W/dalvikvm﹕ VFY: unable to resolve virtual method 366: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
02-24 09:38:49.835 997-997/com.example.supriyaraman.sample I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
02-24 09:38:49.835 997-997/com.example.supriyaraman.sample W/dalvikvm﹕ VFY: unable to resolve virtual method 388: Landroid/content/res/TypedArray;.getType (I)I
02-24 09:38:50.015 997-997/com.example.supriyaraman.sample I/dalvikvm-heap﹕ Grow heap (frag case) to 4.427MB for 1127536-byte allocation
02-24 09:38:50.195 997-997/com.example.supriyaraman.sample I/dalvikvm-heap﹕ Grow heap (frag case) to 6.846MB for 2536936-byte allocation
02-24 09:38:55.756 997-997/com.example.supriyaraman.sample W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-24 09:38:56.015 997-997/com.example.supriyaraman.sample I/Choreographer﹕ Skipped 293 frames! The application may be doing too much work on its main thread.
02-24 09:41:38.537 997-997/com.example.supriyaraman.sample W/EGL_emulation﹕ eglSurfaceAttrib not implemented
You are using different keys to put and to get your values:
Put:
b.putDouble("gyrerror", gyroerr);
Get:
double gyroerr =b.getDouble("gyroerr");
To avoid that, I recomend you to define static values for keys and use it to put/get extras, so typos won't affect:
final static String GYRO_ERROR = "gyroerr";
...
b.putDouble(GYRO_ERROR, gyroerr);
...
double gyroerr =b.getDouble(GYRO_ERROR);
Put everything in your intent. Like:
Intent i = new Intent(this, NextActivity.class);
i.put("gyrerror", gyroerr);
i.put("compasserror", comperr);
i.put("deviation", dev);
startActivity(i);
Then in your next class you have:
Bundle b = this.getIntent().getExtras();
This gets the extras from your INTENT not bundle. So you need to say:
double d = b.getDouble("gyrerror");
This should work.
I m learning android please help me. It gives me following errors in logcat.
02-27 14:14:42.455: D/dalvikvm(1655): GC_FOR_ALLOC freed 46K, 5% free 2891K/3020K, paused 152ms, total 156ms
02-27 14:14:42.465: I/dalvikvm-heap(1655): Grow heap (frag case) to 3.668MB for 810016-byte allocation
02-27 14:14:42.545: D/dalvikvm(1655): GC_FOR_ALLOC freed 2K, 4% free 3680K/3812K, paused 76ms, total 77ms
02-27 14:14:43.425: I/Choreographer(1655): Skipped 35 frames! The application may be doing too much work on its main thread.
02-27 14:14:43.645: D/gralloc_goldfish(1655): Emulator without GPU emulation detected.
02-27 14:14:48.395: I/Choreographer(1655): Skipped 58 frames! The application may be doing too much work on its main thread.
02-27 14:14:49.725: I/Choreographer(1655): Skipped 58 frames! The application may be doing too much work on its main thread.
02-27 14:14:52.355: I/Choreographer(1655): Skipped 61 frames! The application may be doing too much work on its main thread.
02-27 14:14:55.195: D/AndroidRuntime(1655): Shutting down VM
02-27 14:14:55.195: W/dalvikvm(1655): threadid=1: thread exiting with uncaught exception (group=0xb3aaaba8)
02-27 14:14:55.275: E/AndroidRuntime(1655): FATAL EXCEPTION: main
02-27 14:14:55.275: E/AndroidRuntime(1655): Process: com.example.dreamhome, PID: 1655
02-27 14:14:55.275: E/AndroidRuntime(1655): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dreamhome/com.example.dreamhome.LoginFormActivity}: java.lang.NullPointerException
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.access$800(ActivityThread.java:135)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.os.Handler.dispatchMessage(Handler.java:102)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.os.Looper.loop(Looper.java:136)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.main(ActivityThread.java:5017)
02-27 14:14:55.275: E/AndroidRuntime(1655): at java.lang.reflect.Method.invokeNative(Native Method)
02-27 14:14:55.275: E/AndroidRuntime(1655): at java.lang.reflect.Method.invoke(Method.java:515)
02-27 14:14:55.275: E/AndroidRuntime(1655): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-27 14:14:55.275: E/AndroidRuntime(1655): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-27 14:14:55.275: E/AndroidRuntime(1655): at dalvik.system.NativeStart.main(Native Method)
02-27 14:14:55.275: E/AndroidRuntime(1655): Caused by: java.lang.NullPointerException
02-27 14:14:55.275: E/AndroidRuntime(1655): at com.example.dreamhome.LoginFormActivity.onCreate(LoginFormActivity.java:45)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.Activity.performCreate(Activity.java:5231)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
02-27 14:14:55.275: E/AndroidRuntime(1655): ... 11 more
02-27 14:15:03.295: I/Process(1655): Sending signal. PID: 1655 SIG: 9
HomeActivity.java
public class HomeActivity extends Activity
{
Button search_property, log_in, exit;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
search_property=(Button)findViewById(R.id.homebutton1);
log_in=(Button)findViewById(R.id.homebutton2);
exit=(Button)findViewById(R.id.homebutton3);
search_property.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent main1=new Intent(HomeActivity.this,EndUserSearchPropertyActivity.class);
startActivity(main1);
}
});
log_in.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent main2 = new Intent(HomeActivity.this,LoginFormActivity.class);
startActivity(main2);
}
});
exit.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
finish();
System.exit(0);
}
});
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar()
{
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
this is LoginFormActivity.java
public class LoginFormActivity extends Activity
{
private Button sign_up = null;
private Button btnSignIn = null;
LoginDataBaseAdapter loginDataBaseAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_form);
// create a instance of SQLite Database
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
final Dialog dialog = new Dialog(LoginFormActivity.this);
// get the Refferences of views
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.login_editText1);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.login_editText2);
btnSignIn = (Button)dialog.findViewById(R.id.login_form_button1);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// get The User name and Password
String userName = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword))
{
Toast.makeText(LoginFormActivity.this, "Congrats: Login Successfull", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
else
{
Toast.makeText(LoginFormActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
#Override
protected void onDestroy()
{
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
sign_up = (Button)findViewById(R.id.login_form_button2);
sign_up.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent main2=new Intent(LoginFormActivity.this,SignupFormActivity.class);
startActivity(main2);
}
});
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar()
{
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login_form, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
final Dialog dialog = new Dialog(LoginFormActivity.this);
Merely instantiating a dialog doesn't inflate/create its layout. All the subsequent dialog.findViewById() calls return null and you'll get the NPE here attempting to call a method on null reference:
btnSignIn = (Button)dialog.findViewById(R.id.login_form_button1);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener()
You probably need to set a content view to your dialog with all the views you want to reference. The views are available with findViewById() after the dialog is showing.