Hey guys i have funny little bug that i have been trying to figure now keep in mind i am student. Would like to know why it is happening ill display the class and where the error is occuring. Thankyou in advanced.
package com.example.assignment;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ViewRate extends Activity implements OnClickListener {
private int rowID;
private TextView codetv;
private TextView signtv;
private TextView ratetv;
private final String dbName="CurrencyDB";
private final String tableName="Rates";
SQLiteDatabase sampleDB=null;
//
EditText torate, fromrate;
Button convertto,convertfrom;
TextView conRate;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.viewrate);
setViews();
Bundle extra=getIntent().getExtras();
rowID=extra.getInt(MainActivity.ROW_ID);
fillViews();
convertto = (Button)findViewById(R.id.convertto);
convertfrom =(Button)findViewById(R.id.convertfrom);
convertfrom.setOnClickListener(from);
convertto.setOnClickListener(to);}
private OnClickListener to = new OnClickListener() { <-------ERROR
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//converttocur();
conRate.setText("pressed"); <------testing still wont work
}
};
private OnClickListener from = new OnClickListener() { <--------ERROR
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//convertfromcur();
conRate.setText("pressed"); <--------testing
}
};
private void convertfromcur() {
// TODO Auto-generated method stub
try {
double val = Double.parseDouble(ratetv.getText().toString());
double val2 = Double.parseDouble(fromrate.getText().toString());
double com = (val / val2);
conRate.setText("RATE:" + com);
} catch (Exception e) {
// TODO: handle exception
conRate.setText("Error");
}
}
private void converttocur() {
// TODO Auto-generated method stub
try {
double val = Double.parseDouble(ratetv.getText().toString());
double val2 = Double.parseDouble(torate.getText().toString());
double com = (val * val2);
conRate.setText("RATE:" + com);
} catch (Exception e) {
// TODO: handle exception
conRate.setText("Error");
}
}
private void fillViews() {
// TODO Auto-generated method stub
try{
sampleDB=this.openOrCreateDatabase(dbName, MODE_PRIVATE, null);
Cursor c = sampleDB.rawQuery("Select * from " +tableName+" where id ?", new String[] {String.valueOf(rowID)});
if(c!=null && c.moveToFirst()==true){
String code=c.getString(c.getColumnIndex("Code"));
String sign=c.getString(c.getColumnIndex("Sign"));
String rate=c.getString(c.getColumnIndex("Rate"));
codetv.setText(code);
signtv.setText(sign);
ratetv.setText(rate);
}
}
catch(SQLException e){
Log.e(getClass().getSimpleName(),"Could not open database");
}
finally{
if(sampleDB!=null){
sampleDB.close();
}
}
}
private void setViews() {
// TODO Auto-generated method stub
codetv=(TextView)findViewById(R.id.code);
signtv=(TextView)findViewById(R.id.sign);
ratetv=(TextView)findViewById(R.id.rate);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.viewtask,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case R.id.edit:
getEdit();
return true;
case R.id.delete:
getDelete();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void getDelete() {
//TODO Auto-generated method stub
try{
sampleDB=this.openOrCreateDatabase(dbName, MODE_PRIVATE,null);
sampleDB.delete(tableName, "id= "+rowID,null);
}
catch(SQLException e){
Log.e(getClass().getSimpleName(),"Could not open dB");
}
finally {
if(sampleDB!=null){
sampleDB.close();
}
}
}
private void getEdit(){
//TODO Auto-generated method stub
Intent addEdit=new Intent(this,AddEdit.class);
addEdit.putExtra("ID",rowID);
addEdit.putExtra("code",codetv.getText().toString());
addEdit.putExtra("sign",signtv.getText().toString());
addEdit.putExtra("rate",ratetv.getText().toString());
startActivity(addEdit);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
And so the error is on the button clicks and i getting this error message
E/AndroidRuntime(2524): FATAL EXCEPTION: main
E/AndroidRuntime(2524): java.lang.NullPointerException
E/AndroidRuntime(2524):at .example.assignment.ViewRate.converttocur(ViewRate.java:96)
E/AndroidRuntime(2524):at com.example.assignment.ViewRate.access$0(ViewRate.java:86)
E/AndroidRuntime(2524):at com.example.assignment.ViewRate$1.onClick(ViewRate.java:55)
E/AndroidRuntime(2524): at android.view.View.performClick(View.java:4202)
E/AndroidRuntime(2524): at android.view.View$PerformClick.run(View.java:17340)
E/AndroidRuntime(2524): at android.os.Handler.handleCallback(Handler.java:725)
E/AndroidRuntime(2524): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(2524): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(2524):at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(2524):at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2524): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(2524):at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(2524): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(2524): at dalvik.system.NativeStart.main(Native Method)
so here is the other logcat
E/AndroidRuntime(2743): FATAL EXCEPTION: main
E/AndroidRuntime(2743): java.lang.NullPointerException
E/AndroidRuntime(2743): at com.example.assignment.ViewRate$1.onClick(ViewRate.java:56)
E/AndroidRuntime(2743): at android.view.View.performClick(View.java:4202)
E/AndroidRuntime(2743): at android.view.View$PerformClick.run(View.java:17340)
E/AndroidRuntime(2743): at android.os.Handler.handleCallback(Handler.java:725)
E/AndroidRuntime(2743): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(2743): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(2743): at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(2743): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2743): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(2743): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(2743): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(2743): at dalvik.system.NativeStart.main(Native Method)
I have seen your code, you missed this line under onCreate method to initialize the Textview conRate so by default it initialize by null and you are referring conRate.setText("") where conRate is null thats why you are getting NullPointerException on OnClick.
conRate =(TextView)findViewById(R.id.conRate);
Hope this will help you...:)
One of these values is null:
ratetv
torate
ratetv.getText()
torate.getText()
You cannot dereference null (essentially, you cannot call methods on a null value), so you get a NullPointerException.
I think you have missed the following in your onCreate()
torate = (EditText) findViewById(R.id.to_rate)
ratetv = (TextView) findViewById(R.id.rate_tv)
Plz first check your all UI components are referenced well in your java file means in activity.
this may be the place where you get NPE.
also you are accessing intent value from other activity in onCreate() method so olz confirm that you will get value in intent or you get null value
Blockquote
just change your code::
Blockquote
you have implemented onClickListener in your activity so definetly you will get it's override method onClick so just in that method write your button click event conditionally like
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId == R.id.convertto)
{
//Here write you code when converTo button Clicked
}
else if(v.getId == R.id.converfrom)
{
//Here write your code when converfrom button clicked
}
}
Related
I am trying to communicate simple node js (socket.io) server with my android app I am using Gottox socket.io-java-client lib converted to jar file as client but it always returning the error (error while handshaking file not found) I am testing the app on my mobile device on local network using wifi my ip is 192.168.1.69
I have tested the server communication over web it is working fine
Code of node js socket server
var mongo = require('mongodb').MongoClient,
Client = require('socket.io').listen(8080).sockets;
mongo.connect('mongodb://192.168.1.69/chat',function(err, db){
if(err) throw err;
Client.on('connection',function(socket){
//get mongo db collection
console.log("Connected to server");
var col = db.collection("messages"),
sendStatus = function(s){
socket.emit('status',s);
};
//emit all messages
col.find().limit(100).sort({_id:1}).toArray(function(err, res){
if(err) throw err;
socket.emit("output",res);
});
//wait for input
socket.on('input',function(data){
console.log("data-------> name: "+data.name+" message: "+data.message);
//insert into mongodb server
//json data from client
var name = data.name,
message = data.message,
whitespacePattern = /^\s*$/;
if(whitespacePattern.test(name) || whitespacePattern.test(message)){
sendStatus("Name and Message is required.");
console.log("invalid data");
}else{
col.insert({name: name,message:message},function(){
//emit latest to all clients
Client.emit('output',[data]);
sendStatus({
message:"message sent",
clear:true
});
});
}
//on input
});
//on connection
});
//mongo db connect
});
Code of android client
package com.example.socketio;
import java.net.MalformedURLException;
import org.json.JSONObject;
import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.button1);
final TextView text = (TextView) findViewById(R.id.textView2);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
SocketIO socket = new SocketIO("http://192.168.1.69:8080");
socket.connect(new IOCallback() {
#Override
public void onMessage(JSONObject arg0, IOAcknowledge arg1) {
// TODO Auto-generated method stub
}
#Override
public void onMessage(String arg0, IOAcknowledge arg1) {
// TODO Auto-generated method stub
}
#Override
public void onError(SocketIOException arg0) {
// TODO Auto-generated method stub
arg0.printStackTrace();
}
#Override
public void onDisconnect() {
// TODO Auto-generated method stub
}
#Override
public void onConnect() {
// TODO Auto-generated method stub
}
#Override
public void on(String arg0, IOAcknowledge arg1, Object... arg2) {
// TODO Auto-generated method stub
}
});
socket.emit("input", "hello");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Error:
06-07 11:05:35.414: W/System.err(26605): io.socket.SocketIOException: Error while handshaking
06-07 11:05:35.414: W/System.err(26605): at io.socket.IOConnection.handshake(IOConnection.java:322)
06-07 11:05:35.414: W/System.err(26605): at io.socket.IOConnection.access$600(IOConnection.java:39)
06-07 11:05:35.424: W/System.err(26605): at io.socket.IOConnection$ConnectThread.run(IOConnection.java:199)
06-07 11:05:35.424: W/System.err(26605): Caused by: java.io.FileNotFoundException: http://192.168.1.69:8080/socket.io/1/
06-07 11:05:35.424: W/System.err(26605): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
06-07 11:05:35.424: W/System.err(26605): at io.socket.IOConnection.handshake(IOConnection.java:313)
06-07 11:05:35.424: W/System.err(26605): ... 2 more
Problem solved (sort of), here: Android developpement, Gottox socket.io-java-client: file not fount Exception /socket.io/1/
(try using an earlier version of socket.io - by first deleting socket.io folder from node_modules and then install an older version, e.g., 0.9.16, using this command: npm install socket.io#0.9.16)
Use this new library to get going with socket.io 1.0 on Java
https://github.com/nkzawa/socket.io-client.java/blob/master/README.md
I'm developing an app with eclipse and arduino which connects to a bluetooth module. I can then control the LEDS on the board. However my code shows no errors but the app force closes everytime I hit a button. Here is my code:
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class BluetoothTest extends Activity
{
TextView labelConnect;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button openButton = (Button)findViewById(R.id.open);
Button closeButton = (Button)findViewById(R.id.close);
Button onButton = (Button)findViewById(R.id.onButton);
Button offButton = (Button)findViewById(R.id.offButton);
Button redButton = (Button)findViewById(R.id.redButton);
Button greenButton = (Button)findViewById(R.id.greenButton);
Button blueButton = (Button)findViewById(R.id.blueButton);
labelConnect = (TextView)findViewById(R.id.mylabel);
//Open Bluetooth
openButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
findBT();
openBT();
}
catch (IOException ex) { }
}
});
//Close Bluetooth
closeButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
closeBT();
}
catch (IOException ex) { }
}
});
//Red Button
redButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
redButton();
}
catch (IOException ex) { }
}
});
//Green Button
greenButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
greenButton();
}
catch (IOException ex) { }
}
});
//Blue Button
blueButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
blueButton();
}
catch (IOException ex) { }
}
});
//On Button - set strip to white
onButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
onButton();
} catch (Exception e) {
// TODO: handle exception
}
}
});
//Off Button - set strip to all OFF
offButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
offButton();
} catch (Exception e) {
// TODO: handle exception
}
}
});
} // end onCreate
void findBT()
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null)
{
labelConnect.setText("No bluetooth adapter available");
}
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals("BTNode0")) // Change to match RN42 - node name
{
mmDevice = device;
Log.i("ArduinoBT", "findBT found device named " + mmDevice.getName());
Log.i("ArduinoBT", "device address is " + mmDevice.getAddress());
break;
}
}
}
labelConnect.setText("Bluetooth Device Found");
}
void openBT() throws IOException
{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
labelConnect.setText("BT << " + mmDevice.getName() + " >> is now open ");
}
void closeBT() throws IOException
{
mmOutputStream.close();
mmSocket.close();
labelConnect.setText("Bluetooth Closed");
}
void offButton() throws IOException
{
mmOutputStream.write("0".getBytes());
}
void redButton() throws IOException
{
mmOutputStream.write("1".getBytes());
}
void greenButton() throws IOException
{
mmOutputStream.write("2".getBytes());
}
void blueButton() throws IOException
{
mmOutputStream.write("3".getBytes());
}
void onButton() throws IOException
{
mmOutputStream.write("4".getBytes());
}
}
And here is my log for what happens when I hit the connect button
04-25 12:15:10.771: W/asset(22604): Copying FileAsset 0x74c0a9d8 (zip:/data/app/Android.Arduino.Bluetooth-2.apk:/resources.arsc) to buffer size 1912 to make it aligned.
04-25 12:15:10.821: D/RenderPolicy(22604): ViewRootImpl.enableHardwareAcceleration -> enableRenderPolicy
04-25 12:15:10.881: I/Adreno-EGL(22604): <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: (CL4169980)
04-25 12:15:10.881: I/Adreno-EGL(22604): OpenGL ES Shader Compiler Version: 17.01.10.SPL
04-25 12:15:10.881: I/Adreno-EGL(22604): Build Date: 02/04/14 Tue
04-25 12:15:10.881: I/Adreno-EGL(22604): Local Branch:
04-25 12:15:10.881: I/Adreno-EGL(22604): Remote Branch:
04-25 12:15:10.881: I/Adreno-EGL(22604): Local Patches:
04-25 12:15:10.881: I/Adreno-EGL(22604): Reconstruct Branch:
04-25 12:15:12.363: W/dalvikvm(22604): threadid=1: thread exiting with uncaught exception (group=0x41625e18)
04-25 12:15:12.373: E/AndroidRuntime(22604): FATAL EXCEPTION: main
04-25 12:15:12.373: E/AndroidRuntime(22604): Process: Android.Arduino.Bluetooth, PID: 22604
04-25 12:15:12.373: E/AndroidRuntime(22604): java.lang.NullPointerException
04-25 12:15:12.373: E/AndroidRuntime(22604): at Android.Arduino.Bluetooth.BluetoothTest.openBT(BluetoothTest.java:185)
04-25 12:15:12.373: E/AndroidRuntime(22604): at Android.Arduino.Bluetooth.BluetoothTest$1.onClick(BluetoothTest.java:53)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.view.View.performClick(View.java:4480)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.view.View$PerformClick.run(View.java:18673)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.os.Handler.handleCallback(Handler.java:733)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.os.Handler.dispatchMessage(Handler.java:95)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.os.Looper.loop(Looper.java:157)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.app.ActivityThread.main(ActivityThread.java:5872)
04-25 12:15:12.373: E/AndroidRuntime(22604): at java.lang.reflect.Method.invokeNative(Native Method)
04-25 12:15:12.373: E/AndroidRuntime(22604): at java.lang.reflect.Method.invoke(Method.java:515)
04-25 12:15:12.373: E/AndroidRuntime(22604): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1069)
04-25 12:15:12.373: E/AndroidRuntime(22604): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
04-25 12:15:12.373: E/AndroidRuntime(22604): at dalvik.system.NativeStart.main(Native Method)
As they have already said in the comments, the mmDevice you are trying to use in the openBT method is null, because no device was found in the findBT method and the variable was not initialized. You need to fix your code so that you don't try to open the connection if the device was not found.
The other main issue in your code, once you solve this, is the SocketConnection you are trying to open in the Main Thread. Button handlers and GUI events are executed in the main thread, so your openBT should be moved to a separate thread (or better, a Service).
I have the following Activity:
package com.example.myapp;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.Toast;
public class HomeActivity extends Activity implements AnimationListener {
// Animation
Animation animFadein;
Animation animFadeout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_start);
// load the animation
animFadein = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fade_in);
animFadeout = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fade_out);
// set animation listener
animFadein.setAnimationListener(this);
ImageButton homepage =(ImageButton)findViewById(R.id.homepage);
ImageButton new_b =(ImageButton)findViewById(R.id.new_b);
ImageButton view_b =(ImageButton)findViewById(R.id.view_b);
ImageButton home_b =(ImageButton)findViewById(R.id.home_b);
ImageButton info_b =(ImageButton)findViewById(R.id.info_b);
Button back_b =(Button)findViewById(R.id.back_b);
Button site =(Button)findViewById(R.id.site);
homepage.startAnimation(animFadein);
//Click on screen to start
homepage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View homepage = (View)findViewById(R.id.homepage);
View startpage = (View)findViewById(R.id.startpage);
homepage.setVisibility(View.GONE);
homepage.startAnimation(animFadeout);
startpage.setVisibility(View.VISIBLE);
startpage.setAnimation(animFadein);};});
new_b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences values = getSharedPreferences("valoar", 0);
SharedPreferences.Editor editor = values.edit();
editor.clear();
editor.commit();
View startpage = (View)findViewById(R.id.startpage);
startpage.setAnimation(animFadeout);
Intent intent = new Intent(HomeActivity.this,QuestionsActivity.class);
startActivity(intent);}});
home_b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View homepage = (View)findViewById(R.id.homepage);
View startpage = (View)findViewById(R.id.startpage);
homepage.setVisibility(View.VISIBLE);
homepage.startAnimation(animFadein);
startpage.startAnimation(animFadeout);
startpage.setVisibility(View.GONE);};});
info_b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View startpage = (View)findViewById(R.id.startpage);
View infopage = (View)findViewById(R.id.infopage);
ScrollView info_s = (ScrollView)findViewById(R.id.info_s);
infopage.setVisibility(View.VISIBLE);
info_s.setVisibility(View.VISIBLE);
infopage.startAnimation(animFadein);
startpage.startAnimation(animFadeout);
startpage.setVisibility(View.GONE);};});
back_b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View startpage = (View)findViewById(R.id.startpage);
View infopage = (View)findViewById(R.id.infopage);
ScrollView info_s = (ScrollView)findViewById(R.id.info_s);
infopage.setVisibility(View.GONE);
info_s.setVisibility(View.GONE);
infopage.startAnimation(animFadeout);
startpage.startAnimation(animFadein);
startpage.setVisibility(View.VISIBLE);};});
**site.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent internetIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.i-amapp.com"));
internetIntent.setComponent(new ComponentName("com.android.browser","com.android.browser.BrowserActivity"));
internetIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(internetIntent);};});**
}
#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 void onAnimationEnd(Animation arg0) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
/**
* Back button listener.
* Will close the application if the back button pressed twice.
*/
#Override
public void onBackPressed()
{
int backButtonCount = 0;
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
else
{
Toast.makeText(this, "Press the x button to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
}
It works very well in android 4.1.2, but in android 2.3.7 it crashes, and Logcat displays:
D/AndroidRuntime(2172): Shutting down VM
W/dalvikvm(2172): threadid=1: thread exiting with uncaught exception (group=0x40018560)
E/AndroidRuntime(2172): FATAL EXCEPTION: main
E/AndroidRuntime(2172): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapp/com.example.myapp.HomeActivity}: java.lang.NullPointerException
E/AndroidRuntime(2172): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1768)
E/AndroidRuntime(2172): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1784)
E/AndroidRuntime(2172): at android.app.ActivityThread.access$1500(ActivityThread.java:123)
E/AndroidRuntime(2172): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939)
E/AndroidRuntime(2172): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(2172): at android.os.Looper.loop(Looper.java:130)
E/AndroidRuntime(2172): at android.app.ActivityThread.main(ActivityThread.java:3835)
E/AndroidRuntime(2172): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2172): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime(2172): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
E/AndroidRuntime(2172): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
E/AndroidRuntime(2172): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(2172): Caused by: java.lang.NullPointerException
E/AndroidRuntime(2172): at com.example.myapp.HomeActivity.onCreate(HomeActivity.java:107)
E/AndroidRuntime(2172): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
E/AndroidRuntime(2172): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722)
E/AndroidRuntime(2172): ... 11 more
D/dalvikvm(3117): GC_EXTERNAL_ALLOC freed 61K, 50% free 2724K/5379K, external 0K/0K, paused 44ms
D/dalvikvm(3117): GC_EXTERNAL_ALLOC freed 4K, 50% free 2730K/5379K, external 507K/513K, paused 43ms
D/dalvikvm(3117): GC_EXTERNAL_ALLOC freed 1K, 50% free 2736K/5379K, external 1068K/1524K, paused 43ms
D/dalvikvm(3117): GC_EXTERNAL_ALLOC freed 1K, 50% free 2741K/5379K, external 1669K/2086K, paused
This is all that logcat is displaying. I can't figure out what is the problem!
Why does it crash in android 2.3?
I have 3 spinners in my view. 1st spinner has fixed initial values. rest of it are empty initially.
when i select a value from first spinner , new values are added to spinner 2 and 3 according to the selection of 1st spinner.
Here i Did something for only two Spinners ! There isn't any code error but i got run time error it's listed below the code ! can any one help me? Thanks in advance !
Coding
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import com.gtustudents.R;
import com.gtustudents.common.BaseActivity;
import com.gtustudents.login.HomePage;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class demo extends BaseActivity {
public Spinner spinner1;
public Spinner spinner2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.MY_LAYOUT);
spinner1= (Spinner)findViewById(R.id.degree);
spinner1.setOnItemSelectedListener(new spinnerListen());
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
startActivity(new Intent(this,HomePage.class));
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
class spinnerListen extends BaseActivity implements OnItemSelectedListener{
public Spinner spinner2;
public void onItemSelected(AdapterView<?> parent, View v, int pos,long id) {
// TODO Auto-generated method stub
//use the selected station and departure time to calculate the required time
Toast toast = Toast.makeText(parent.getContext(),"You've chosen: " + parent.getItemAtPosition(pos), 2);
toast.show();
String str = (String) parent.getSelectedItem();
Log.d("Select Item", str);
if(str.equals("SOME_VALUE"))
{
Log.d("Enter","YES");
final String[] items2 = new String[] {"SOne", "STwo", "SThree"};
Log.d("Enter","ArrayAdapter");
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items2);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Log.d("BE Enter","ArrayAdapter -2 ");
spinner2.setAdapter(dataAdapter);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
RunTime Error
08-30 16:49:18.586: ERROR/AndroidRuntime(865): FATAL EXCEPTION: main
08-30 16:49:18.586: ERROR/AndroidRuntime(865): java.lang.IllegalStateException: System services not available to Activities before onCreate()
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.app.Activity.getSystemService(Activity.java:3526)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.widget.ArrayAdapter.init(ArrayAdapter.java:271)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:125)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.widget.AdapterView.fireOnSelected(AdapterView.java:864)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.widget.AdapterView.access$200(AdapterView.java:42)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:830)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.os.Handler.handleCallback(Handler.java:587)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.os.Handler.dispatchMessage(Handler.java:92)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.os.Looper.loop(Looper.java:123)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.app.ActivityThread.main(ActivityThread.java:4627)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at java.lang.reflect.Method.invokeNative(Native Method)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at java.lang.reflect.Method.invoke(Method.java:521)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at dalvik.system.NativeStart.main(Native Method)
In your 2nd Class {{ spinnerListen }} your have declared a flied called spinner2 which is never intiated, but your tying to set an adapter to it.
I havent tried it, but i guess thats why the framework assume that you havent passed onCreate yet.
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import com.gtustudents.R;
import com.gtustudents.common.BaseActivity;
import com.gtustudents.login.HomePage;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class demo extends BaseActivity implements OnItemSelectedListener{
public Spinner spinner1;
public Spinner spinner2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.MY_LAYOUT);
spinner1= (Spinner)findViewById(R.id.degree);
spinner1.setOnItemSelectedListener(this);
spinner2 = (Spinner)findViewById(R.id.degree2); // TODO reference Proper id
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
startActivity(new Intent(this,HomePage.class));
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
public void onItemSelected(AdapterView<?> parent, View v, int pos,long id) {
// TODO Auto-generated method stub
//use the selected station and departure time to calculate the required time
Toast toast = Toast.makeText(parent.getContext(),"You've chosen: " + parent.getItemAtPosition(pos), 2);
toast.show();
String str = (String) parent.getSelectedItem();
Log.d("Select Item", str);
if(str.equals("SOME_VALUE"))
{
Log.d("Enter","YES");
final String[] items2 = new String[] {"SOne", "STwo", "SThree"};
Log.d("Enter","ArrayAdapter");
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items2);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Log.d("BE Enter","ArrayAdapter -2 ");
spinner2.setAdapter(dataAdapter);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
I've started on another class that get's two strings from another class, I've only set up one so far, but I just tested it out, but when I fill in my two edit text's and hit submit it crashes.
First Class (Launcher Class)
package com.gta5news.bananaphone;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.R.string;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LogIn extends Activity implements OnClickListener {
Button send;
EditText user;
EditText pass;
CheckBox staySignedIn;
FileOutputStream Fos;
String FILENAME = "userandpass";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
send = (Button) findViewById(R.id.bLogIn);
user = (EditText) findViewById(R.id.eTuser);
pass = (EditText) findViewById(R.id.eTpassword);
staySignedIn = (CheckBox) findViewById(R.id.Cbstay);
send.setOnClickListener(this);
try {
Fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
Fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (staySignedIn.isChecked()) {
String a = user.getText().toString();
String b = pass.getText().toString();
File f = new File(FILENAME);
try {
Fos = new FileOutputStream(f);
//Write some Data
Fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogIn:
if (pass.length() == 0)
Toast.makeText(this,
"Try to type in your username and password again!",
Toast.LENGTH_LONG).show();
else if (user.length() == 0)
Toast.makeText(this,
"Try to type in your username and password again!",
Toast.LENGTH_LONG).show();
else {
String u = user.getText().toString();
String p = pass.getText().toString();
Bundle send = new Bundle();
send.putString("key", u);
send.putString("key", p);
Intent a = new Intent(LogIn.this, logincheck.class);
startActivity(a);
Toast.makeText(this, "Were signing you in!", Toast.LENGTH_LONG)
.show();
break;
}
}
}
}
Second Class:
package com.gta5news.bananaphone;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class logincheck extends Activity {
String GotBread;
TextView user;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.logincheck);
user = (TextView) findViewById(R.layout.logincheck);
SetUp();
}
public void SetUp() {
// TODO Auto-generated method stub
Bundle GotData = getIntent().getExtras();
GotBread = GotData.getString("key");
user.setText(GotBread); {
}
}
}
LogCat:
01-19 08:53:56.641: E/AndroidRuntime(3319): ... 11 more
01-19 08:56:28.561: E/AndroidRuntime(3384): FATAL EXCEPTION: main
01-19 08:56:28.561: E/AndroidRuntime(3384): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gta5news.bananaphone/com.gta5news.bananaphone.logincheck}: java.lang.NullPointerException
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.os.Handler.dispatchMessage(Handler.java:99)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.os.Looper.loop(Looper.java:123)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-19 08:56:28.561: E/AndroidRuntime(3384): at java.lang.reflect.Method.invokeNative(Native Method)
01-19 08:56:28.561: E/AndroidRuntime(3384): at java.lang.reflect.Method.invoke(Method.java:521)
01-19 08:56:28.561: E/AndroidRuntime(3384): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-19 08:56:28.561: E/AndroidRuntime(3384): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-19 08:56:28.561: E/AndroidRuntime(3384): at dalvik.system.NativeStart.main(Native Method)
01-19 08:56:28.561: E/AndroidRuntime(3384): Caused by: java.lang.NullPointerException
01-19 08:56:28.561: E/AndroidRuntime(3384): at com.gta5news.bananaphone.logincheck.SetUp(logincheck.java:24)
01-19 08:56:28.561: E/AndroidRuntime(3384): at com.gta5news.bananaphone.logincheck.onCreate(logincheck.java:17)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-19 08:56:28.561: E/AndroidRuntime(3384): ... 11 more
Get Bundle in Oncreate Method
And
Use Like
Intent i = new Intent(Login.this,logincheck.class);
i.putExtra("key", user);
i.putExtra("key1", pass);
startActivity(i);
And
user = (TextView) findViewById(R.layout.logincheck);
Instead of
user = (TextView) findViewById(R.id.logincheck);
So User is Null
On your main activity you're creating the Bundle and inserting the content in it, but you're not sending it to the the intent.
You should put the information on the Intent before starting the second activity. Do something like this:
Intent a = new Intent(LogIn.this, logincheck.class);
a.putExtra("key", u);
a.putExtra("key", p);
startActivity(a);
I will try to give u a clue how to solve it..it can be even more fail-proffed but this should work for u..
Intent i = new Intent(LogIn.this, logincheck.class);
i.putExtra("username", sUsername);
i.putExtra("password", SPassword);
To get the saved data in new activity try with:
String newString;
if(extras == null) {
sUsernameInNewActivity = null;
sPasswordInNewActivity = null;
} else {
sUsernameInNewActivity = extras.getString("username");
sPasswordInNewActivity = extras.getString("password");
}
btw. A lot of bad practice in your code.. :( I have troubles to read it easy..
for example:
you have two variables with different scope and type but exactly the same name (try to find it)
did u want to join something with this code or???
send.putString("key", u);
send.putString("key", p);
how u thought to get them later? together/separately?
Hope u will solve it. Cheers