Error to settext to a edittext inside switch statement - java

I am attempting to use a settext for an edittext. I have this code because I need to use the afterTextChanged() in multiple edittext. If I use a setText inside a case: the App crashes but it works correcty outside in a onClick of a button.
public Button btn;
public EditText et1, et2, et3;
private int whoHasFocus = 0;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testing2, container, false);
super.onCreate(savedInstanceState);
et1 = (EditText) view.findViewById(R.id.ladoA);
et1.setOnFocusChangeListener(this);
et1.addTextChangedListener(this);
et2 = (EditText) view.findViewById(R.id.ladoB);
et2.setOnFocusChangeListener(this);
et2.addTextChangedListener(this);
et3 = (EditText) view.findViewById(R.id.ladoC);
et3.setOnFocusChangeListener(this);
et3.addTextChangedListener(this);
btn = (Button) view.findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
et1.setText("Works correctly.");
}
});
return view;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
switch (whoHasFocus) {
case 1:
et2.setText("It does not work.");
break;
case 2:
break;
case 3:
break;
}
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
switch (v.getId()) {
case R.id.ladoA:
whoHasFocus = 1;
break;
case R.id.ladoB:
whoHasFocus = 2;
break;
case R.id.ladoC:
whoHasFocus = 3;
break;
}
}
}
Here is the log:
10-01 11:47:19.202 4141-4141/example.test.com.testApp D/OpenGLRenderer﹕ Enabling debug mode 0
10-01 11:47:21.855 4141-4141/example.test.com.testApp D/dalvikvm﹕ GC_FOR_ALLOC freed 234K, 35% free 11382K/17256K, paused 26ms, total 26ms
10-01 11:47:21.885 4141-4141/example.test.com.testApp I/dalvikvm-heap﹕ Grow heap (frag case) to 20.760MB for 6998416-byte allocation
10-01 11:47:21.935 4141-4143/example.test.com.testApp D/dalvikvm﹕ GC_CONCURRENT freed 8K, 25% free 18209K/24092K, paused 2ms+2ms, total 40ms
10-01 11:47:21.935 4141-4141/example.test.com.testApp I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawable
10-01 11:47:21.935 4141-4141/example.test.com.testApp W/dalvikvm﹕ VFY: unable to resolve virtual method 371: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
10-01 11:47:21.935 4141-4141/example.test.com.testApp D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
10-01 11:47:21.935 4141-4141/example.test.com.testApp I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawableForDensity
10-01 11:47:21.935 4141-4141/example.test.com.testApp W/dalvikvm﹕ VFY: unable to resolve virtual method 373: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
10-01 11:47:21.935 4141-4141/example.test.com.testApp D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
10-01 11:47:28.252 4141-4141/example.test.com.testApp I/dalvikvm﹕ threadid=1: stack overflow on call to Landroid/view/View;.invalidate:VZ
10-01 11:47:28.252 4141-4141/example.test.com.testApp I/dalvikvm﹕ method requires 40+20+20=80 bytes, fp is 0x57102338 (56 left)
10-01 11:47:28.252 4141-4141/example.test.com.testApp I/dalvikvm﹕ expanding stack end (0x57102300 to 0x57102000)
10-01 11:47:28.252 4141-4141/example.test.com.testApp I/dalvikvm﹕ Shrank stack (to 0x57102300, curFrame is 0x57107d20)
10-01 11:47:28.252 4141-4141/example.test.com.testApp D/AndroidRuntime﹕ Shutting down VM
10-01 11:47:28.252 4141-4141/example.test.com.testApp W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40e37ac8)
10-01 11:47:28.342 4141-4141/example.test.com.testApp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.StackOverflowError
at android.view.View.invalidate(View.java:10849)
at android.widget.TextView.invalidateRegion(TextView.java:4975)
at android.widget.TextView.invalidateCursor(TextView.java:4966)
at android.widget.TextView.spanChange(TextView.java:8060)
at android.widget.TextView$ChangeWatcher.onSpanAdded(TextView.java:10023)
at android.text.SpannableStringBuilder.sendSpanAdded(SpannableStringBuilder.java:979)
at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:688)
at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:588)
at android.text.Selection.setSelection(Selection.java:116)
at android.text.Selection.setSelection(Selection.java:127)
at android.text.method.ArrowKeyMovementMethod.initialize(ArrowKeyMovementMethod.java:302)
at android.widget.TextView.setText(TextView.java:4092)
at android.widget.TextView.setText(TextView.java:3924)
at android.widget.EditText.setText(EditText.java:104)
at android.widget.TextView.setText(TextView.java:3899)
at example.test.com.testApp.Testing2.afterTextChanged(Testing2.java:62)
at android.widget.TextView.sendAfterTextChanged(TextView.java:7982)
at android.widget.TextView.setText(TextView.java:4111)
at android.widget.TextView.setText(TextView.java:3924)
at android.widget.EditText.setText(EditText.java:104)
at android.widget.TextView.setText(TextView.java:3899)
at example.test.com.testApp.Testing2.afterTextChanged(Testing2.java:62)
at android.widget.TextView.sendAfterTextChanged(TextView.java:7982)
at android.widget.TextView.setText(TextView.java:4111)
at android.widget.TextView.setText(TextView.java:3924)
at android.widget.EditText.setText(EditText.java:104)
at android.widget.TextView.setText(TextView.java:3899)
at example.test.com.testApp.Testing2.afterTextChanged(Testing2.java:62)
at android.widget.TextView.sendAfterTextChanged(TextView.java:7982)
at android.widget.TextView.setText(TextView.java:4111)
at android.widget.TextView.setText(TextView.java:3924)
at android.widget.EditText.setText(EditText.java:104)
at android.widget.TextView.setText(TextView.java:3899)
at example.test.com.testApp.Testing2.afterTextChanged(Testing2.java:62)
at android.widget.TextView.sendAfterTextChanged(TextView.java:7982)
at android.widget.TextView.setText(TextView.java:4111)
at android.widget.TextView.setText(TextView.java:3924)
at android.widget.EditText.setText(EditText.java:104)
at android.widget.TextView.setText(TextView.java:3899)
at example.test.com.testApp.Testing2.afterTextChanged(Testing2.java:62)
at android.widget.TextView.sendAfterTextChanged(TextView.java:7982)
at android.widget.TextView.setText(TextView.java:4111)
at android.widget.TextView.setText(TextView.java:3924)
at android.widget.EditText.setText(EditText.java:104)
at android.widget.TextView.setText(TextView.java:3899)
at example.test.com.testApp.Testing2.afterTextChanged(Testing2.java:62)
at android.widget.TextView.sendAfterTextChanged(TextView.java:7982)
at android.widget.TextView.setText(TextView.java:4111)
at android.widget.TextView.setText(TextView.java:3924)
at android.widget.EditText.setText(EditText.java:104)
at android.widget.TextView.setText(TextView.java:3899)
at example.test.com.testApp.Testing2.afterTextChanged(Testing2.java:62)
at android.widget.TextView.sendAfterTextChanged(TextView.java:7982)
at android.widget.TextView.setText(TextView.java:4111)
at android.widget.TextView.setText(TextView.java:3924)
at android.widget.EditText.setText(EditText.java:104)
at android.widget.TextView.setText(TextView.java:3899)
at example.test.com.testApp.Testing2.afterTextChanged(Testing2.java:62)
at android.widget.TextView.sendAfterTextChanged(TextView.java:7982)
at android.widget.TextView.setText(TextView.java:4111)
at android.widget.TextView.setText(TextView.java:3924)
at android.widget.EditText.setText(EditText.java:104)
at android.widget.TextView.setText(TextView.java:3899)
at example.test.com.testApp

You set the EditText's text inside afterTextChanged, which calls afterTextChanged again. This recursive call creates an infinite loop that leads to stack overflow.

You are setting the text in afterTextChanged, which is causing the same method to be called again, causing an infinite loop. Remove the listener, set the text, then add the listener back.
et2.removeTextChangedListener(this);
et2.setText("this will work");
et2.addTextChangedListener(this);

calling SetText inside OnTextChanged cause infinite loop..
You can set a condition to stop it:
if (et2.getText.equals(originalValue )) {
// do nothing
} else {
et2.setText("xxx");
originalValue = et2.getText();
}

Related

XMPP Smack can not receive the message

I read lots of related posts about how to send and receive message by smack 4.1
and openFire . from my understanding i implemented the following code
I can connect, i can login . but when sending message form user1 to user2 i get nothing.
code:
package passargad.ehsan;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;
import org.jivesoftware.smack.chat.ChatManagerListener;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import java.io.IOException;
public class XMPPservice extends Service {
XMPPTCPConnection connection;
String connectionMessages="";
ConnectionXMPP connectionXMPPAsynch =new ConnectionXMPP();
#Override
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
connectionXMPPAsynch.execute();
}
catch (Exception e)
{
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
class ConnectionXMPP extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... params) {
connection = new XMPPTCPConnection(XMPPTCPConnectionConfiguration.builder()
.setServiceName("192.168.1.6").setUsernameAndPassword("ehsan", "123")
.setPort(9090).setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setCompressionEnabled(false).build());
connection.setUseStreamManagement(true);
connection.addConnectionListener(new ConnectionListener() {
#Override
public void connected(XMPPConnection connection) {
Log.d("connected", "yes connected successfully : ");
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
Log.d("connected","yes authenticated successfully : ");
}
#Override
public void connectionClosed() {
Log.d("connected","yes connectionClosed successfully : ");
}
#Override
public void connectionClosedOnError(Exception e) {
Log.d("connected","yes connectionClosedOnError : ");
connectionMessages="connectionClosedOnError";
publishProgress();
}
#Override
public void reconnectionSuccessful() {
Log.d("connected","yes reconnection successfully : ");
}
#Override
public void reconnectingIn(int seconds) {
Log.d("connected","yes reconnectingIn : ");
}
#Override
public void reconnectionFailed(Exception e) {
Log.d("connected","yes reconnectionFailed : ");
}
});
connect();
chat();
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
if (connectionMessages=="connectionClosedOnError")
{
connect();
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("","onPostExecute");
}
private void connect()
{
try {
connection.connect();
connection.login();
Log.d(""," user id :: " + connection.getUser());
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
}
private void chat()
{
ChatManager chatmanager = ChatManager.getInstanceFor(connection);
Chat newChat = chatmanager.createChat("192.168.1.6" ,new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
Log.d("","message :"+ message.getBody());
}
});
try
{
Message newMessage = new Message();
newMessage.setBody("Howdy!");
newMessage.setFrom("ehsan#192.168.1.6/Smack");
newMessage.setTo("ehsan#192.168.1.6/Smack");
newChat.sendMessage(newMessage);
}
catch (SmackException.NotConnectedException e)
{
e.printStackTrace();
}
chatmanager.addChatListener(
new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally)
{
if (!createdLocally)
chat.addMessageListener(new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
Log.d("","message :"+ message.getBody());
}
});;
}
});
}
}
}
here is the logcat:
02-20 06:45:13.334 1188-1188/passargad.ehsan I/dalvikvm﹕ Could not find method android.view.ViewGroup.onInitializeAccessibilityEvent, referenced from method android.support.v7.widget.LinearLayoutCompat.onInitializeAccessibilityEvent
02-20 06:45:13.334 1188-1188/passargad.ehsan W/dalvikvm﹕ VFY: unable to resolve virtual method 13351: Landroid/view/ViewGroup;.onInitializeAccessibilityEvent (Landroid/view/accessibility/AccessibilityEvent;)V
02-20 06:45:13.334 1188-1188/passargad.ehsan D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0006
02-20 06:45:13.334 1188-1188/passargad.ehsan D/dalvikvm﹕ VFY: dead code 0x0009-0011 in Landroid/support/v7/widget/LinearLayoutCompat;.onInitializeAccessibilityEvent (Landroid/view/accessibility/AccessibilityEvent;)V
02-20 06:45:13.344 1188-1188/passargad.ehsan W/dalvikvm﹕ VFY: unable to find class referenced in signature (Landroid/view/accessibility/AccessibilityNodeInfo;)
02-20 06:45:13.344 1188-1188/passargad.ehsan I/dalvikvm﹕ Could not find method android.view.ViewGroup.onInitializeAccessibilityNodeInfo, referenced from method android.support.v7.widget.LinearLayoutCompat.onInitializeAccessibilityNodeInfo
02-20 06:45:13.344 1188-1188/passargad.ehsan W/dalvikvm﹕ VFY: unable to resolve virtual method 13352: Landroid/view/ViewGroup;.onInitializeAccessibilityNodeInfo (Landroid/view/accessibility/AccessibilityNodeInfo;)V
02-20 06:45:13.344 1188-1188/passargad.ehsan D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0006
02-20 06:45:13.344 1188-1188/passargad.ehsan D/dalvikvm﹕ VFY: dead code 0x0009-0011 in Landroid/support/v7/widget/LinearLayoutCompat;.onInitializeAccessibilityNodeInfo (Landroid/view/accessibility/AccessibilityNodeInfo;)V
02-20 06:45:13.374 1188-1188/passargad.ehsan I/KeyCharacterMap﹕ No keyboard for id -1
02-20 06:45:13.374 1188-1188/passargad.ehsan I/KeyCharacterMap﹕ Using default keymap: /system/usr/keychars/qwerty.kcm.bin
02-20 06:45:13.504 1188-1190/passargad.ehsan D/dalvikvm﹕ GC_CONCURRENT freed 206K, 46% free 3077K/5639K, external 0K/0K, paused 5ms+11ms
02-20 06:45:16.858 1188-1190/passargad.ehsan D/dalvikvm﹕ GC_CONCURRENT freed 263K, 44% free 3317K/5895K, external 0K/0K, paused 5ms+6ms
02-20 06:45:17.088 1188-1190/passargad.ehsan D/dalvikvm﹕ GC_CONCURRENT freed 252K, 43% free 3485K/6087K, external 0K/0K, paused 5ms+6ms
02-20 06:45:17.208 1188-1199/passargad.ehsan I/dalvikvm﹕ Could not find method java.lang.Throwable.addSuppressed, referenced from method de.measite.minidns.Client.query
02-20 06:45:17.208 1188-1199/passargad.ehsan W/dalvikvm﹕ VFY: unable to resolve virtual method 14707: Ljava/lang/Throwable;.addSuppressed (Ljava/lang/Throwable;)V
02-20 06:45:17.208 1188-1199/passargad.ehsan D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x006f
02-20 06:45:17.208 1188-1199/passargad.ehsan I/dalvikvm﹕ Could not find method java.lang.Throwable.addSuppressed, referenced from method de.measite.minidns.Client.query
02-20 06:45:17.208 1188-1199/passargad.ehsan W/dalvikvm﹕ VFY: unable to resolve virtual method 14707: Ljava/lang/Throwable;.addSuppressed (Ljava/lang/Throwable;)V
02-20 06:45:17.218 1188-1199/passargad.ehsan D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x009d
02-20 06:45:17.218 1188-1199/passargad.ehsan I/dalvikvm﹕ Could not find method java.lang.Throwable.addSuppressed, referenced from method de.measite.minidns.Client.query
02-20 06:45:17.218 1188-1199/passargad.ehsan W/dalvikvm﹕ VFY: unable to resolve virtual method 14707: Ljava/lang/Throwable;.addSuppressed (Ljava/lang/Throwable;)V
02-20 06:45:17.218 1188-1199/passargad.ehsan D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x00b4
02-20 06:45:17.218 1188-1199/passargad.ehsan D/dalvikvm﹕ VFY: dead code 0x0072-0072 in Lde/measite/minidns/Client;.query (Lde/measite/minidns/Question;Ljava/lang/String;I)Lde/measite/minidns/DNSMessage;
02-20 06:45:17.218 1188-1199/passargad.ehsan D/dalvikvm﹕ VFY: dead code 0x00a0-00a0 in Lde/measite/minidns/Client;.query (Lde/measite/minidns/Question;Ljava/lang/String;I)Lde/measite/minidns/DNSMessage;
02-20 06:45:17.218 1188-1199/passargad.ehsan D/dalvikvm﹕ VFY: dead code 0x00b7-00b7 in Lde/measite/minidns/Client;.query (Lde/measite/minidns/Question;Ljava/lang/String;I)Lde/measite/minidns/DNSMessage;
02-20 06:45:17.428 1188-1190/passargad.ehsan D/dalvikvm﹕ GC_CONCURRENT freed 273K, 42% free 3647K/6279K, external 0K/0K, paused 4ms+6ms
02-20 06:45:17.688 1188-1190/passargad.ehsan D/dalvikvm﹕ GC_CONCURRENT freed 403K, 44% free 3652K/6407K, external 0K/0K, paused 5ms+5ms
02-20 06:45:17.979 1188-1199/passargad.ehsan D/connected﹕ yes connected successfully :
02-20 06:45:18.519 1188-1190/passargad.ehsan D/dalvikvm﹕ GC_CONCURRENT freed 323K, 42% free 3739K/6407K, external 0K/0K, paused 5ms+6ms
02-20 06:45:18.669 1188-1193/passargad.ehsan I/dalvikvm﹕ Jit: resizing JitTable from 512 to 1024
02-20 06:45:18.779 1188-1193/passargad.ehsan D/dalvikvm﹕ null clazz in OP_INSTANCE_OF, single-stepping
02-20 06:45:19.460 1188-1190/passargad.ehsan D/dalvikvm﹕ GC_CONCURRENT freed 479K, 43% free 3737K/6535K, external 0K/0K, paused 5ms+6ms
02-20 06:45:20.221 1188-1190/passargad.ehsan D/dalvikvm﹕ GC_CONCURRENT freed 486K, 43% free 3742K/6535K, external 0K/0K, paused 5ms+6ms
02-20 06:45:20.371 1188-1199/passargad.ehsan D/connected﹕ yes authenticated successfully :
02-20 06:45:20.391 1188-1199/passargad.ehsan D/﹕ user id :: ehsan#passargad-pc/Smack
02-20 06:45:20.411 1188-1188/passargad.ehsan D/﹕ onPostExecute
thank you in advance!
A quick look through the code, I found a few mistakes:
createChat expects the first argument to be userJid (not host IP)
Chat newChat = chatmanager.createChat("ehsan#<service name>" ,new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
Log.d("","message :"+ message.getBody());
}
});
Enable debugging and check logs
connection = new XMPPTCPConnection(
XMPPTCPConnectionConfiguration.builder()
.setServiceName("192.168.1.6")
.setUsernameAndPassword("ehsan", "123")
.setPort(9090)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setCompressionEnabled(false)
.setDebuggerEnabled(true)
.build());
Change port from 9090 to 5222 (In case you didn't change default configuration; check openfire admin panel)
Prefer using addAsyncStanzaListener to listen for incoming packets.
This example may be useful for you:
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
public class Test {
public static void main(String args[]) throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration("127.0.0.1", 5222);
XMPPConnection connection = new XMPPConnection(config);
connection.connect();
connection.login("userx", "123456");
ChatManager cm = connection.getChatManager();
Chat chat = cm.createChat("tongqian#tsw-PC", null);
/*
* add listener
*/
cm.addChatListener(new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean create) {
chat.addMessageListener(new MessageListener() {
#Override
public void processMessage(Chat chat, Message msg) {
System.out.println(chat.getParticipant() + ":" + msg.getBody());
}
});
}
});
chat.sendMessage("hello");
while(true);
//connection.disconnect();
}
}

How to create an edit button in an Contextmenu in Android Studio

to say it at the beginning - i am not a good programmer.
Im trying to create an contextmenu with an delete and edit function but im kinda having trouble with the edit function. As soon as the user is pushing the edit button in the contextmenu, he should be able to change the name of the Button i long pressed to open the contextmenu.
#Override
public boolean onContextItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.Bearbeiten:
EditText editText = (EditText) findViewById(R.id.editText);
buttonActOne.setText(editText.getText());
return true;
Of course the programm keeps crashing as soon as the user pushes the edit button and im kinda running out of ideas how i could do it else.
I really hope somebody has an good answer for me.
Edit:
Ok, first of all thanks for the answers till now. Im posting my complete MainActivity.java
package com.example.michl.myapplication5;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textViewIntro;
public Button buttonActOne;
public Button buttonActTwo;
public Button buttonActThree;
public Button buttonActFour;
public Button buttonActFive;
public Button buttonActSix;
public Button buttonActSeven;
public Button buttonActEight;
public Button buttonActNine;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewIntro = (TextView) findViewById(R.id.textViewIntro);
Button ButtonActOne = (Button) findViewById(R.id.buttonActOne);
ButtonActOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Seite_zwei.class));
Button ButtonActOne = (Button)findViewById(R.id.buttonActOne);
registerForContextMenu(ButtonActOne);
}
});
Button ButtonActTwo = (Button) findViewById(R.id.buttonActTwo);
ButtonActTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Seite_drei.class));
Button ButtonActTwo = (Button)findViewById(R.id.buttonActTwo);
registerForContextMenu(ButtonActTwo);
}
});
Button ButtonActThree = (Button) findViewById(R.id.buttonActThree);
ButtonActThree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Seite_vier.class));
Button ButtonActThree = (Button)findViewById(R.id.buttonActThree);
registerForContextMenu(ButtonActThree);
}
});
Button ButtonActFour = (Button) findViewById(R.id.buttonActFour);
ButtonActFour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Seite_fuenf.class));
Button ButtonActFour = (Button)findViewById(R.id.buttonActFour);
registerForContextMenu(ButtonActFour);
}
});
Button ButtonActFive = (Button) findViewById(R.id.buttonActFive);
ButtonActFive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Seite_sechs.class));
Button ButtonActFive = (Button)findViewById(R.id.buttonActFive);
registerForContextMenu(ButtonActFive);
}
});
Button ButtonActSix = (Button) findViewById(R.id.buttonActSix);
ButtonActSix.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Seite_sieben.class));
Button ButtonActSix = (Button)findViewById(R.id.buttonActSix);
registerForContextMenu(ButtonActSix);
}
});
Button ButtonActSeven = (Button) findViewById(R.id.buttonActSeven);
ButtonActSeven.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Seite_acht.class));
Button ButtonActSeven = (Button)findViewById(R.id.buttonActSeven);
registerForContextMenu(ButtonActSeven);
}
});
Button ButtonActEight = (Button) findViewById(R.id.buttonActEight);
ButtonActEight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Seite_neun.class));
Button ButtonActEight = (Button)findViewById(R.id.buttonActEight);
registerForContextMenu(ButtonActEight);
}
});
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.menu_main, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.Bearbeiten:
EditText editText = (EditText) findViewById(R.id.editText);
buttonActOne.setText(editText.getText());
return true;
case R.id.Löschen:
return true;
default:
}
return super.onContextItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, 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);
}
}
And here is my logcat log when i start the programm and try to edit something.
08-28 13:52:06.135 26482-26482/com.example.michl.myapplication5 D/dalvikvm﹕ Late-enabling CheckJNI
08-28 13:52:06.150 26482-26488/com.example.michl.myapplication5 E/jdwp﹕ Failed sending reply to debugger: Broken pipe
08-28 13:52:06.150 26482-26488/com.example.michl.myapplication5 D/dalvikvm﹕ Debugger has detached; object registry had 1 entries
08-28 13:52:06.290 26482-26482/com.example.michl.myapplication5 D/libEGL﹕ loaded /system/lib/egl/libEGL_mali.so
08-28 13:52:06.295 26482-26482/com.example.michl.myapplication5 D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_mali.so
08-28 13:52:06.295 26482-26482/com.example.michl.myapplication5 D/libEGL﹕ loaded /system/lib/egl/libGLESv2_mali.so
08-28 13:52:06.300 26482-26482/com.example.michl.myapplication5 D/﹕ Device driver API match
Device driver API version: 10
User space API version: 10
08-28 13:52:06.300 26482-26482/com.example.michl.myapplication5 D/﹕ mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Thu Oct 25 08:43:05 KST 2012
08-28 13:52:06.315 26482-26482/com.example.michl.myapplication5 D/OpenGLRenderer﹕ Enabling debug mode 0
08-28 13:52:17.355 26482-26482/com.example.michl.myapplication5 I/dalvikvm﹕ Could not find method android.view.ViewGroup.onRtlPropertiesChanged, referenced from method android.support.v7.widget.Toolbar.onRtlPropertiesChanged
08-28 13:52:17.355 26482-26482/com.example.michl.myapplication5 W/dalvikvm﹕ VFY: unable to resolve virtual method 13334: Landroid/view/ViewGroup;.onRtlPropertiesChanged (I)V
08-28 13:52:17.355 26482-26482/com.example.michl.myapplication5 D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0007
08-28 13:52:17.360 26482-26482/com.example.michl.myapplication5 I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
08-28 13:52:17.360 26482-26485/com.example.michl.myapplication5 D/dalvikvm﹕ GC_CONCURRENT freed 188K, 14% free 9612K/11143K, paused 12ms+18ms, total 49ms
08-28 13:52:17.360 26482-26482/com.example.michl.myapplication5 W/dalvikvm﹕ VFY: unable to resolve virtual method 412: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
08-28 13:52:17.360 26482-26482/com.example.michl.myapplication5 D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
08-28 13:52:17.360 26482-26482/com.example.michl.myapplication5 I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
08-28 13:52:17.360 26482-26482/com.example.michl.myapplication5 W/dalvikvm﹕ VFY: unable to resolve virtual method 434: Landroid/content/res/TypedArray;.getType (I)I
08-28 13:52:17.360 26482-26482/com.example.michl.myapplication5 D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
08-28 13:52:17.465 26482-26482/com.example.michl.myapplication5 E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
08-28 13:52:17.465 26482-26482/com.example.michl.myapplication5 E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
08-28 13:52:18.345 26482-26482/com.example.michl.myapplication5 E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
08-28 13:52:18.345 26482-26482/com.example.michl.myapplication5 E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
08-28 13:52:19.605 26482-26482/com.example.michl.myapplication5 D/AbsListView﹕ Get MotionRecognitionManager
08-28 13:52:19.635 26482-26482/com.example.michl.myapplication5 W/ResourceType﹕ Failure getting entry for 0x010802c1 (t=7 e=705) in package 0 (error -75)
08-28 13:52:20.935 26482-26482/com.example.michl.myapplication5 D/AndroidRuntime﹕ Shutting down VM
08-28 13:52:20.935 26482-26482/com.example.michl.myapplication5 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4191e2a0)
08-28 13:52:20.955 26482-26482/com.example.michl.myapplication5 E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.michl.myapplication5.MainActivity.onContextItemSelected(MainActivity.java:161)
at android.app.Activity.onMenuItemSelected(Activity.java:2647)
at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:3921)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:193)
at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:934)
at android.widget.AdapterView.performItemClick(AdapterView.java:301)
at android.widget.AbsListView.performItemClick(AbsListView.java:1280)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3071)
at android.widget.AbsListView$1.run(AbsListView.java:3973)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4921)
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:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
at dalvik.system.NativeStart.main(Native Method)
08-28 13:52:31.590 26482-26482/com.examp
le.michl.myapplication5 I/Process﹕ Sending signal. PID: 26482 SIG: 9
Declare your button on the onCreate method of the Activity!
Button buttonActOne = findViewById(R.id.buttonActOneId);
Then add the listener to it:
buttonActOne.setOnClickListener(this);
The setOnClickListener implements the interface View.OnClickListener, so the #override method it has to be onClick(View v), then in the switch you can use the v.getId();
In resume:
public class YourActivityName extends Activity implements View.OnClickListener {
private Button buttonActOne;
#Override
public void onCreate(Bundle b) {
//set your layout
buttonActOne = findViewById(R.id.buttonActOneId); //put the id defined in your xml layout
}
#Override
public void onClick(View view) {
if (View.getId(R.id.Bearbeiten)) {
EditText editText = (EditText) findViewById(R.id.editText);
buttonActOne.setText(editText.getText());
}
}
}

app crashing after clicking button x times

hi guys i have a problem. when i run my app, one activity crash after i press the buttons x times. sometimes it works, sometimes not. please help. don't know what to do.strong text
08-08 09:19:57.087: E/AndroidRuntime(2772): FATAL EXCEPTION: main
08-08 09:19:57.087: E/AndroidRuntime(2772): Process: org.nolodigas, PID: 2772
08-08 09:19:57.087: E/AndroidRuntime(2772): java.lang.IllegalStateException: Could not execute method of the activity
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.view.View$1.onClick(View.java:3823)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.view.View.performClick(View.java:4438)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.view.View$PerformClick.run(View.java:18422)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.os.Handler.handleCallback(Handler.java:733)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.os.Handler.dispatchMessage(Handler.java:95)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.os.Looper.loop(Looper.java:136)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-08 09:19:57.087: E/AndroidRuntime(2772): at java.lang.reflect.Method.invokeNative(Native Method)
08-08 09:19:57.087: E/AndroidRuntime(2772): at java.lang.reflect.Method.invoke(Method.java:515)
08-08 09:19:57.087: E/AndroidRuntime(2772): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-08 09:19:57.087: E/AndroidRuntime(2772): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-08 09:19:57.087: E/AndroidRuntime(2772): at dalvik.system.NativeStart.main(Native Method)
08-08 09:19:57.087: E/AndroidRuntime(2772): Caused by: java.lang.reflect.InvocationTargetException
08-08 09:19:57.087: E/AndroidRuntime(2772): at java.lang.reflect.Method.invokeNative(Native Method)
08-08 09:19:57.087: E/AndroidRuntime(2772): at java.lang.reflect.Method.invoke(Method.java:515)
08-08 09:19:57.087: E/AndroidRuntime(2772): at android.view.View$1.onClick(View.java:3818)
08-08 09:19:57.087: E/AndroidRuntime(2772): ... 11 more
08-08 09:19:57.087: E/AndroidRuntime(2772): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=121; index=123
08-08 09:19:57.087: E/AndroidRuntime(2772): at org.nolodigas.Jugar.okButton(Jugar.java:104)
08-08 09:19:57.087: E/AndroidRuntime(2772): ... 14 more
there is my logcat. i can't find the error . here is my java code
public class Jugar extends Activity implements ViewSwitcher.ViewFactory,
View.OnClickListener {
private TextSwitcher mSwitcher;
TextView textViewTime;
ImageView img;
int cont=0;
private int mCounter = 0;
private int[] a = {
R.drawable.casa,R.drawable.cantar,R.drawable.agua,R.drawable.anciana,R.drawable.arbol,R.drawable.mochila,R.drawable.auto,R.drawable.azucar,R.drawable.libro,R.drawable.empresa,R.drawable.control,R.drawable.computadora,R.drawable.boca,
R.drawable.boliche,R.drawable.campo,R.drawable.cantar,R.drawable.cargador,R.drawable.casa,R.drawable.casamiento,R.drawable.cerveza,R.drawable.cocina,R.drawable.concierto,R.drawable.control,R.drawable.cuaderno,R.drawable.cuerpo,R.drawable.deporte,R.drawable.dj,
R.drawable.doctor,R.drawable.droga,R.drawable.edificio,R.drawable.empresa,R.drawable.escritor,R.drawable.famoso,R.drawable.ganso,R.drawable.gato,R.drawable.gente,R.drawable.ginobili,R.drawable.grande,R.drawable.hospital,R.drawable.hotel,
R.drawable.huerfano,R.drawable.ingeniero,R.drawable.jugo,R.drawable.libreria,R.drawable.libro,R.drawable.mesa,R.drawable.mochila,R.drawable.museo,R.drawable.musica,R.drawable.naranja,R.drawable.nieve,R.drawable.ovni,R.drawable.paris,
R.drawable.pasto,R.drawable.pelo,R.drawable.pelota,R.drawable.pendrive,R.drawable.periodista,R.drawable.perro,R.drawable.piramide,R.drawable.pistola,R.drawable.planeta,R.drawable.playa,R.drawable.sirena,R.drawable.abogado,R.drawable.esqui,R.drawable.funda,R.drawable.disco,
R.drawable.pornografia,R.drawable.profesor,R.drawable.puerta,R.drawable.radio,R.drawable.rio,R.drawable.roma,R.drawable.ropa,R.drawable.sillon,R.drawable.superheroe,R.drawable.taza,R.drawable.luz,R.drawable.lapiz,R.drawable.ron,R.drawable.fernet,R.drawable.bariloche,R.drawable.garage,R.drawable.alarma,
R.drawable.tela,R.drawable.televisor,R.drawable.unia,R.drawable.ventana,R.drawable.ventilador,R.drawable.viajar,R.drawable.zapatillas,R.drawable.pelea,R.drawable.panda,R.drawable.cable,R.drawable.tinelli,R.drawable.manzana,R.drawable.ftutilla,R.drawable.leche,R.drawable.fotocopia,
R.drawable.mono,R.drawable.piano,R.drawable.guitarra,R.drawable.bateria,R.drawable.camara,R.drawable.bombon,R.drawable.tren,R.drawable.pintura,R.drawable.aldea,R.drawable.grito,R.drawable.bandera,R.drawable.messi,R.drawable.aguero,R.drawable.legrand,R.drawable.zuckerberg,R.drawable.billetera,R.drawable.guepardo,R.drawable.elefante,R.drawable.calle,R.drawable.gimnasio,R.drawable.argentina,
};
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.jugar);
mSwitcher = (TextSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
textViewTime = (TextView) findViewById(R.id.texto1);
textViewTime.setText("01:00");
Button nextButton = (Button) findViewById(R.id.next);
nextButton.setOnClickListener(this);
updateCounter();
}
private void updateCounter() {
mSwitcher.setText(String.valueOf(mCounter));
}
public View makeView() {
TextView t = new TextView(this);
t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
t.setTextSize(36);
return t;
}
protected void setOrientation() {
int current = getRequestedOrientation();
// only switch the orientation if not in portrait
if ( current != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ) {
setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
public void lanzarJugar(View v) {
}
#Override
public void onClick(View v) {
mCounter=0;
mSwitcher.setText(String.valueOf(mCounter));
final CounterClass timer = new CounterClass(60000, 1000);
timer.start();
ImageView img= (ImageView) findViewById(R.id.imageView1);
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
img.setImageDrawable(d);
}
public void noButton(View v){
ImageView img= (ImageView) findViewById(R.id.imageView1);
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
img.setImageDrawable(d);
}
public void okButton(View v) {
ImageView img= (ImageView) findViewById(R.id.imageView1);
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
img.setImageDrawable(d);
mCounter++;
updateCounter();
cont++;
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint({ "NewApi", "DefaultLocale" })
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#SuppressLint("NewApi")
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long millis = millisUntilFinished;
String ms = String.format("%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
System.out.println(ms);
textViewTime.setText(ms);
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
textViewTime.setText("Tiempo!");
}
}
}
In the code line below, you are generating a random number and picking an Resource Integer. But the index you are trying to get from array doesn't exist. So you are getting IndexOutOfBounds exception.
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
Error is in okButton method here:
int rando = (int) (Math.random() * 125);
Drawable d = getResources().getDrawable(a[rando]);
rando is returning a value out bounds of a array.
Your array contains only 121 elements. Hence, whenever the random number generated is within 0-120 range, the app functions properly. But whenever the number falls between 121-124, it crashes due to IndexOutOfBounds exception. Either add more items to the array or use the following code:
int rando = (int) (Math.random() * 121);
Drawable d = getResources().getDrawable(a[rando]);

Android Application Crashes when Creating custom class object

I'm working on my first android app and I'm having trouble creating an object of a class I have programmed in java using the onCreate function of an activity. The activity starts great when I do not instantiate the object, but when I attempt to create the object the app crashes when switching to the activity. The onCreate function looks like this...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entry);
// Show the Up button in the action bar.
setupActionBar();
ForceTable testTable = new ForceTable();
Double factor = testTable.returnValue(forceTypes.newtons, forceTypes.newtons);
}
ForceTable is the class I have programmed, its code looks this...
public class ForceTable {
private double[][] forceTable;
protected enum forceTypes {newtons(0), pounds(1), kilopond(2);
public int num;
private forceTypes(int num)
{
this.num = num;
}
};
protected final class values{
private final static double zeroZero = 1.00;
private final static double zeroOne = 4.44872162;
private final static double zeroTwo = 9.80665;
private final static double oneZero = .224808943;
private final static double oneOne = 1.00;
private final static double oneTwo = 2.20462262;
private final static double twoZero = .10197164;
private final static double twoOne = .45359237;
private final static double twoTwo = 1.00;
}
public ForceTable()
{
this.makeTable();
}
private void makeTable()
{
forceTable[0][0] = values.zeroZero;
forceTable[0][1] = values.zeroOne;
forceTable[0][2] = values.zeroTwo;
forceTable[1][0] = values.oneZero;
forceTable[1][1] = values.oneOne;
forceTable[1][2] = values.oneTwo;
forceTable[2][0] = values.twoZero;
forceTable[2][1] = values.twoOne;
forceTable[2][2] = values.twoTwo;
}
public double returnValue(forceTypes ifYouHave, forceTypes thenYouHave){
double factor = forceTable[thenYouHave.num][ifYouHave.num];
return factor;
}
}
It's been a very long time since I have programmed in Java, and since the activity starts fine without instantiating it must be my Java code for ForceTable. Anybody notice something wrong? There's a good chance it's something easy that I'm not brushed up on...
Here is the logcat
08-08 18:08:13.206: E/(9801): : Can't open file for reading
08-08 18:08:13.206: E/(9801): : Can't open file for reading
08-08 18:10:34.045: W/dalvikvm(9801): threadid=1: thread exiting with uncaught exception (group=0x4136b438)
08-08 18:10:34.045: E/AndroidRuntime(9801): FATAL EXCEPTION: main
08-08 18:10:34.045: E/AndroidRuntime(9801): java.lang.RuntimeException: Unable to start activity ComponentInfo{khandy.application.convertible/khandy.application.convertible.EntryActivity}: java.lang.NullPointerException
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.ActivityThread.access$700(ActivityThread.java:143)
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.os.Handler.dispatchMessage(Handler.java:99)
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.os.Looper.loop(Looper.java:137)
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.ActivityThread.main(ActivityThread.java:4950)
08-08 18:10:34.045: E/AndroidRuntime(9801): at java.lang.reflect.Method.invokeNative(Native Method)
08-08 18:10:34.045: E/AndroidRuntime(9801): at java.lang.reflect.Method.invoke(Method.java:511)
08-08 18:10:34.045: E/AndroidRuntime(9801): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
08-08 18:10:34.045: E/AndroidRuntime(9801): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
08-08 18:10:34.045: E/AndroidRuntime(9801): at dalvik.system.NativeStart.main(Native Method)
08-08 18:10:34.045: E/AndroidRuntime(9801): Caused by: java.lang.NullPointerException
08-08 18:10:34.045: E/AndroidRuntime(9801): at khandy.application.convertible.ForceTable.makeTable(ForceTable.java:34)
08-08 18:10:34.045: E/AndroidRuntime(9801): at khandy.application.convertible.ForceTable.(ForceTable.java:29)
08-08 18:10:34.045: E/AndroidRuntime(9801): at khandy.application.convertible.EntryActivity.onCreate(EntryActivity.java:21)
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.Activity.performCreate(Activity.java:5179)
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
08-08 18:10:34.045: E/AndroidRuntime(9801): ... 11 more
You probably get a NullPointerException at this line
forceTable[0][0] = values.zeroZero;
because you try to access the array without creating it first. Before accessing it, create it like that
forceTable = new double[][];
forceTable[0][0] = values.zeroZero;
And please ALWAYS post the logcat output! It just makes it so much easier to find the problem.
I think the problem is when your makeTable function is called. can you allocate space for your forceTable array.. I mean do a new for double[][] forceTable;
You are missing
privatetable = new double[n] [m] ;
You can put it in the constructor of the second class!

Cursor is Null in Service Class - But Returns Value in Standalone Activity Class

My classmates and I are stuck on an issue with android application we are building.
We've successfully built an Android app which contains an activity which searches our browser histories / bookmarks for specific urls and launches another activity (successfully) if a match is found as an example of an adult content warning implementation.
This is functioning fine.
Now we are implementing a service class to continually execute every few seconds - in order to execute the search of our recent history using our new service class - but we're experiencing a few issues.
Our problem is when we attempt to add the "Nanny" source code from Nanny.java to the service class so the "Nanny" script will search the history continuously, instead of just once - the "Nanny" application continually force closes - due to a null pointer exception at the initialization of our cursor: if (cursor.moveToFirst()) {
Which is a bit strange because the NullPointerException does not occur when the exact same script is executed outside the service class in a test file we have (Main.java)
Our working Main.java and our working service class [which successfully displays a toast every few seconds] as well as our [failed] combination of the two - are shown below:
Empty Service Class:
public class Service_class extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}
Working Nanny.java
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Browser;
import android.widget.TextView;
public class Nanny extends Activity {
String Dirty1 = "www.playboy.com";
String Dirty2 = "www.penthouse.com";
String Dirty3 = "www.pornhub.com";
String Dirty4 = "www.playboy.com";
String Dirty5 = "www.playboy.com";
String Dirty6 = "www.playboy.com";
String Dirty7 = "www.playboy.com";
String Dirty8 = "www.playboy.com";
String Dirty9 = "www.playboy.com";
String Dirty10 = "www.playboy.com";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nanny);
TextView tv = (TextView) findViewById(R.id.hello);
String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
Cursor cursor = managedQuery(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null);
String urls = "";
if (cursor.moveToFirst()) {
String url1 = null;
String url2 = null;
do {
String url = cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.URL));
if (url.toLowerCase().contains(Dirty1)) {
} else if (url.toLowerCase().contains(Dirty2)) {
} else if (url.toLowerCase().contains(Dirty3)) {
} else if (url.toLowerCase().contains(Dirty4)) {
} else if (url.toLowerCase().contains(Dirty5)) {
} else if (url.toLowerCase().contains(Dirty6)) {
} else if (url.toLowerCase().contains(Dirty7)) {
} else if (url.toLowerCase().contains(Dirty8)) {
} else if (url.toLowerCase().contains(Dirty9)) {
} else if (url.toLowerCase().contains(Dirty10)) {
//if (url.toLowerCase().contains(Filthy)) {
urls = urls
+ cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.TITLE)) + " : "
+ url + "\n";
Intent intent = new Intent(Nanny.this, Warning.class);
Nanny.this.startActivity(intent);
}
} while (cursor.moveToNext());
tv.setText(urls);
}}}
Unsuccessful method we've attempted to implement (adding the functioning nanny script to the service class) which causes the NullPointerException: if (cursor.moveToFirst()) {
public class Service_class extends Service {
String Dirty1 = "www.playboy.com";
String Dirty2 = "www.penthouse.com";
String Dirty3 = "www.pornhub.com";
String Dirty4 = "www.playboy.com";
String Dirty5 = "www.playboy.com";
String Dirty6 = "www.playboy.com";
String Dirty7 = "www.playboy.com";
String Dirty8 = "www.playboy.com";
String Dirty9 = "www.playboy.com";
String Dirty10 = "www.playboy.com";
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
//setContentView(R.layout.main3);
// TextView tv = (TextView) findViewById(R.id.hello);
String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
Cursor cursor = managedQuery(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null);
String urls = "";
if (cursor.moveToFirst()) {
String url1 = null;
String url2 = null;
do {
String url = cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.URL));
if (url.toLowerCase().contains(Dirty1)) {
} else if (url.toLowerCase().contains(Dirty2)) {
} else if (url.toLowerCase().contains(Dirty3)) {
} else if (url.toLowerCase().contains(Dirty4)) {
} else if (url.toLowerCase().contains(Dirty5)) {
} else if (url.toLowerCase().contains(Dirty6)) {
} else if (url.toLowerCase().contains(Dirty7)) {
} else if (url.toLowerCase().contains(Dirty8)) {
} else if (url.toLowerCase().contains(Dirty9)) {
} else if (url.toLowerCase().contains(Dirty10)) {
urls = urls
+ cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.TITLE)) + " : "
+ url + "\n";
Intent warning_intent = new Intent(Service_class.this, Warning.class);
Service_class.this.startActivity(intent);
}
} while (cursor.moveToNext());
// tv.setText(urls);
return START_STICKY;
}
return startId;}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
private void setContentView(int main3) {
// TODO Auto-generated method stub
}
private TextView findViewById(int hello) {
// TODO Auto-generated method stub
return null;
}
private Cursor managedQuery(Uri bookmarksUri, String[] projection,
Object object, Object object2, Object object3) {
// TODO Auto-generated method stub
return null;
}}
LOGCAT (When using combined implementation shown above)
Fails on Line 53: if (cursor.moveToFirst()) {
04-15 18:26:24.761: D/dalvikvm(7466): Late-enabling CheckJNI
04-15 18:26:25.651: D/dalvikvm(7466): GC_FOR_ALLOC freed 82K, 4% free 7379K/7608K, paused 13ms, total 13ms
04-15 18:26:25.651: I/dalvikvm-heap(7466): Grow heap (frag case) to 10.861MB for 3686416-byte allocation
04-15 18:26:25.661: D/dalvikvm(7466): GC_FOR_ALLOC freed 1K, 3% free 10977K/11212K, paused 13ms, total 13ms
04-15 18:26:25.681: D/dalvikvm(7466): GC_CONCURRENT freed <1K, 3% free 10977K/11212K, paused 3ms+2ms, total 17ms
04-15 18:26:25.901: D/dalvikvm(7466): GC_FOR_ALLOC freed <1K, 3% free 10977K/11212K, paused 11ms, total 11ms
04-15 18:26:25.911: I/dalvikvm-heap(7466): Grow heap (frag case) to 17.086MB for 6529744-byte allocation
04-15 18:26:25.931: D/dalvikvm(7466): GC_FOR_ALLOC freed 0K, 2% free 17354K/17592K, paused 13ms, total 13ms
04-15 18:26:25.941: D/dalvikvm(7466): GC_CONCURRENT freed <1K, 2% free 17354K/17592K, paused 3ms+2ms, total 16ms
04-15 18:26:26.051: D/libEGL(7466): loaded /system/lib/egl/libEGL_tegra.so
04-15 18:26:26.061: D/libEGL(7466): loaded /system/lib/egl/libGLESv1_CM_tegra.so
04-15 18:26:26.071: D/libEGL(7466): loaded /system/lib/egl/libGLESv2_tegra.so
04-15 18:26:26.091: D/OpenGLRenderer(7466): Enabling debug mode 0
04-15 18:26:31.181: D/AndroidRuntime(7466): Shutting down VM
04-15 18:26:31.181: W/dalvikvm(7466): threadid=1: thread exiting with uncaught exception (group=0x40f4f930)
04-15 18:26:31.181: E/AndroidRuntime(7466): FATAL EXCEPTION: main
04-15 18:26:31.181: E/AndroidRuntime(7466): java.lang.RuntimeException: Unable to start service com.ut.appdemo.Service_class#41698e90 with Intent { cmp=com.ut.appdemo/.Service_class }: java.lang.NullPointerException
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2673)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread.access$1900(ActivityThread.java:141)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1331)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.os.Handler.dispatchMessage(Handler.java:99)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.os.Looper.loop(Looper.java:137)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-15 18:26:31.181: E/AndroidRuntime(7466): at java.lang.reflect.Method.invokeNative(Native Method)
04-15 18:26:31.181: E/AndroidRuntime(7466): at java.lang.reflect.Method.invoke(Method.java:511)
04-15 18:26:31.181: E/AndroidRuntime(7466): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-15 18:26:31.181: E/AndroidRuntime(7466): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-15 18:26:31.181: E/AndroidRuntime(7466): at dalvik.system.NativeStart.main(Native Method)
04-15 18:26:31.181: E/AndroidRuntime(7466): Caused by: java.lang.NullPointerException
04-15 18:26:31.181: E/AndroidRuntime(7466): at com.ut.appdemo.Service_class.onStartCommand(Service_class.java:53)
04-15 18:26:31.181: E/AndroidRuntime(7466): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2656)
04-15 18:26:31.181: E/AndroidRuntime(7466): ... 10 more
You are setting the cursor to null...
you use this method to instantiate the cursor:
Cursor cursor = managedQuery(android.provider.Browser.BOOKMARKS_URI,projection, null, null, null);
and then you define managedQuery() method like this:
private Cursor managedQuery(Uri bookmarksUri, String[] projection, Object object, Object object2, Object object3) {
// TODO Auto-generated method stub
return null;
}}
essentially what your code says is:
Cursor cursor = null;
curser.doSomething();
this will always result in a nullPointer. I strongly suggest you go back and study java fundamentals before diving in to android, you are just asking for headaches if you are trying to accomplish something in android with such a lack of understanding of java.

Categories