XMPP Smack can not receive the message - java

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();
}
}

Related

Sending time data type from Android to mySQL database

I was trying to send two types of data, Time and Int. The time will be coming from a time picker and the int from a spinner. The problem is whenever I try to send the data to the database by pressing a button, the application will crash (Unfortunately, AppName has stopped working). What I tried to do was send the value from the time picker to a TextView. The string on the TextView will then be sent to the request queue, addURL and data shall be processed by the php script addFeedSched.php
The android app was developed on android studio. The localhosting was done through WAMP server. Handling the data was processed by php scripts. The method used on android was volley
Below are the contents of the java file of the activity and the php scripts that were used as well. Comments were added so to minimize confusion.
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class FeedingSched extends AppCompatActivity {
// Parameters for Time Picker
Button button_picktime;
TextView show_time;
static final int DIALOG_ID=0;
int hour_x, minute_x;
//--
// Parameters for Feed Amount Spinner
Spinner spinner;
// Array Adapter
ArrayAdapter<CharSequence> adapter;
//--
// Parameters for Adding Schedule
Button button_addsched;
//--
// Request Queue Variable
RequestQueue requestQueue;
// Accessing localhost server through php script's directory (note that was just edited here)
String addURL = "http://myIPv4:8080/feedingsched/addFeedSched.php";
// --
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_feeding_sched);
// -- Initialize Spinner Object
spinner = (Spinner) findViewById(R.id.feedamt_spinner);
//Initialize Array Adapter Object
adapter = ArrayAdapter.createFromResource(this,R.array.feed_amt,android.R.layout.simple_spinner_item);
// --
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
// -- Provides a method that invokes a toast when an item is selected
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(),parent.getItemIdAtPosition(position)+" selected", Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Declaring variables from components (buttons, textview, etc)
button_picktime = (Button) findViewById(R.id.picktime_bttn);
show_time = (TextView) findViewById(R.id.timeset_txt);
button_addsched = (Button) findViewById(R.id.addsched_bttn);
showTimePickerDialog();
// -- Request a queue for the updateURL php
button_addsched.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringRequest request = new StringRequest(Request.Method.POST, addURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError{
Map<String,String> parameters = new HashMap<String, String>();
parameters.put("sched_time",show_time.getText().toString());
return parameters;
}
};
requestQueue.add(request);
}
});
}
// Time Picker Initializer
#Override
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_ID) {
return new TimePickerDialog(FeedingSched.this, kTimePickerListener, hour_x, minute_x, false);
} else {
return null;
}
}
// Time Picker Listener
protected TimePickerDialog.OnTimeSetListener kTimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour_x = hourOfDay;
minute_x = minute;
show_time.setText(hour_x + ":" + minute_x + ":00");
}
};
// Showing Time Picker Dialog
public void showTimePickerDialog() {
button_picktime.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DIALOG_ID);
}
}
);
}
}
PHP Scripts that were used
addFeedSched.php
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
if($_SERVER["REQUEST_METHOD"]=="POST"){
require 'connection.php';
inputInterval();
}
function inputInterval(){
global $connect;
$sched_time = $_POST["sched_time"];
$feed_amt = $_POST["feedamt"];
$query = " Insert into feedingsched(time, feedamt) values('".$sched_time."','".$feed_amt."');";
mysqli_query($connect,$query) or die (mysqli_error($connect));
mysqli_close($connect);
}
?>
connection.php
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
define('hostname','localhost');
define('user','root');
define('password','axlrosel123');
define('databaseName','aps');
$connect = mysqli_connect(hostname, user, password, databaseName);
if($connect)
{
echo "Good";
}
else{
echo "Bad";
}
?>
EDIT Here is the logcat message, but it seems to be providing unnecessary details while I was testing the app. The app was also tested on my phone and through connecting it and the local server with the same network.
04-17 13:18:30.940 23265-23265/com.example.axlroseljaro.automatedpoultrysystem I/dalvikvm: Could not find method android.view.Window$Callback.onProvideKeyboardShortcuts, referenced from method android.support.v7.view.WindowCallbackWrapper.onProvideKeyboardShortcuts
04-17 13:18:30.940 23265-23265/com.example.axlroseljaro.automatedpoultrysystem W/dalvikvm: VFY: unable to resolve interface method 20917: Landroid/view/Window$Callback;.onProvideKeyboardShortcuts (Ljava/util/List;Landroid/view/Menu;I)V
04-17 13:18:30.940 23265-23265/com.example.axlroseljaro.automatedpoultrysystem W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
04-17 13:18:30.940 23265-23265/com.example.axlroseljaro.automatedpoultrysystem I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.view.WindowCallbackWrapper.onSearchRequested
04-17 13:18:30.940 23265-23265/com.example.axlroseljaro.automatedpoultrysystem W/dalvikvm: VFY: unable to resolve interface method 20919: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
04-17 13:18:30.940 23265-23265/com.example.axlroseljaro.automatedpoultrysystem I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.view.WindowCallbackWrapper.onWindowStartingActionMode
04-17 13:18:30.940 23265-23265/com.example.axlroseljaro.automatedpoultrysystem W/dalvikvm: VFY: unable to resolve interface method 20923: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
04-17 13:18:30.940 23265-23265/com.example.axlroseljaro.automatedpoultrysystem I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.widget.TintTypedArray.getChangingConfigurations
04-17 13:18:30.940 23265-23265/com.example.axlroseljaro.automatedpoultrysystem W/dalvikvm: VFY: unable to resolve virtual method 496: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
04-17 13:18:30.940 23265-23265/com.example.axlroseljaro.automatedpoultrysystem I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.widget.TintTypedArray.getType
04-17 13:18:30.940 23265-23265/com.example.axlroseljaro.automatedpoultrysystem W/dalvikvm: VFY: unable to resolve virtual method 518: Landroid/content/res/TypedArray;.getType (I)I
04-17 13:18:30.990 23265-23265/com.example.axlroseljaro.automatedpoultrysystem I/dalvikvm-heap: Grow heap (frag case) to 6.933MB for 2362992-byte allocation
04-17 13:18:31.010 23265-23265/com.example.axlroseljaro.automatedpoultrysystem I/dalvikvm: Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawable
04-17 13:18:31.010 23265-23265/com.example.axlroseljaro.automatedpoultrysystem W/dalvikvm: VFY: unable to resolve virtual method 459: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
04-17 13:18:31.010 23265-23265/com.example.axlroseljaro.automatedpoultrysystem I/dalvikvm: Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawableForDensity
04-17 13:18:31.010 23265-23265/com.example.axlroseljaro.automatedpoultrysystem W/dalvikvm: VFY: unable to resolve virtual method 461: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
04-17 13:18:31.020 23265-23265/com.example.axlroseljaro.automatedpoultrysystem I/dalvikvm: Could not find method android.content.Context.getColorStateList, referenced from method android.support.v7.content.res.AppCompatResources.getColorStateList
04-17 13:18:31.020 23265-23265/com.example.axlroseljaro.automatedpoultrysystem W/dalvikvm: VFY: unable to resolve virtual method 308: Landroid/content/Context;.getColorStateList (I)Landroid/content/res/ColorStateList;
04-17 13:18:31.030 23265-23265/com.example.axlroseljaro.automatedpoultrysystem E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
04-17 13:18:31.030 23265-23265/com.example.axlroseljaro.automatedpoultrysystem W/dalvikvm: VFY: unable to resolve instanceof 153 (Landroid/graphics/drawable/RippleDrawable;) in Landroid/support/v7/widget/AppCompatImageHelper;
This is how you initialize it
RequestQueue mRequestQueue;
// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
mRequestQueue = new RequestQueue(cache, network);
For reference, please refer Setting Up a RequestQueue

Error to settext to a edittext inside switch statement

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();
}

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());
}
}
}

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.

Lower version app not running in the Higher version in android

I have made my application using android SDK 2.2 version and now when I am running my app on android SDK 4.0.3 it's not running.
I have given the min and the max sdk in the manifest file.
I am new in android and want to run my app for the lower and higher versions both. Can anybody tell me how can I do this. Any help is appreciated.
Code for splash class
package com.Cricket_trivia.in;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
public class SplashScreen extends Activity {
protected int _splashTime = 5000;
private Thread splashTread;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
final SplashScreen sPlashScreen = this;
// thread for displaying the SplashScreen
splashTread = new Thread() {
#Override
public void run() {
try {
synchronized(this){
wait(_splashTime);
}
} catch(InterruptedException e) {}
finally {
finish();
Intent i = new Intent();
i.setClass(sPlashScreen, K_trivia_cricketActivity.class);
startActivity(i);
stop();
}
}
};
splashTread.start();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
synchronized(splashTread){
splashTread.notifyAll();
}
}
return true;
}
}
EDIT: My logcat
06-07 10:24:18.710: I/dalvikvm(1461): threadid=3: reacting to signal 3
06-07 10:24:18.760: I/dalvikvm(1461): Wrote stack traces to '/data/anr/traces.txt'
06-07 10:24:18.890: D/dalvikvm(1461): GC_FOR_ALLOC freed 45K, 4% free 6541K/6787K, paused 74ms
06-07 10:24:18.900: I/dalvikvm-heap(1461): Grow heap (frag case) to 7.333MB for 921616-byte allocation
06-07 10:24:19.010: I/dalvikvm(1461): threadid=3: reacting to signal 3
06-07 10:24:19.100: I/dalvikvm(1461): Wrote stack traces to '/data/anr/traces.txt'
06-07 10:24:19.140: D/dalvikvm(1461): GC_CONCURRENT freed <1K, 5% free 7440K/7751K, paused 5ms+5ms
06-07 10:24:19.240: D/dalvikvm(1461): GC_FOR_ALLOC freed 0K, 5% free 7440K/7751K, paused 97ms
06-07 10:24:19.240: I/dalvikvm-heap(1461): Grow heap (frag case) to 7.723MB for 409936-byte allocation
06-07 10:24:19.320: D/dalvikvm(1461): GC_FOR_ALLOC freed 0K, 5% free 7841K/8199K, paused 61ms
06-07 10:24:19.589: D/gralloc_goldfish(1461): Emulator without GPU emulation detected.
06-07 10:24:19.669: I/dalvikvm(1461): threadid=3: reacting to signal 3
06-07 10:24:19.779: I/dalvikvm(1461): Wrote stack traces to '/data/anr/traces.txt'
06-07 10:24:24.600: W/dalvikvm(1461): threadid=11: thread exiting with uncaught exception (group=0x409c01f8)
06-07 10:24:24.600: E/AndroidRuntime(1461): FATAL EXCEPTION: Thread-78
06-07 10:24:24.600: E/AndroidRuntime(1461): java.lang.UnsupportedOperationException
06-07 10:24:24.600: E/AndroidRuntime(1461): at java.lang.Thread.stop(Thread.java:1076)
06-07 10:24:24.600: E/AndroidRuntime(1461): at java.lang.Thread.stop(Thread.java:1063)
06-07 10:24:24.600: E/AndroidRuntime(1461): at com.Cricket_trivia.in.SplashScreen$1.run(SplashScreen.java:40)
06-07 10:24:26.209: D/dalvikvm(1461): GC_FOR_ALLOC freed 1037K, 15% free 7022K/8199K, paused 62ms
06-07 10:24:26.209: I/dalvikvm-heap(1461): Grow heap (frag case) to 7.509MB for 614416-byte allocation
06-07 10:24:26.440: D/dalvikvm(1461): GC_CONCURRENT freed <1K, 8% free 7621K/8199K, paused 4ms+5ms
06-07 10:24:26.610: I/dalvikvm(1461): threadid=3: reacting to signal 3
06-07 10:24:26.640: I/dalvikvm(1461): Wrote stack traces to '/data/anr/traces.txt'
The reason why your app is crashing on 4.0.3 but not 2.2 is most likely because you are performing an expensive operation on the UI thread. Blocking the UI thread is very bad practice... don't do it!! Previous versions of Android (i.e. pre-ICS versions) didn't care when you did this and let your app run as is. In 4.0 and above, however, the OS checks against this and crashes your app if you ever perform a potentially expensive operation on the UI thread (such as a network connection, etc.).
You have provided basically no information on what the problem is in your question, so that's all I can really do to help you out.
Edit:
Does something like this work?
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Intent i = new Intent();
i.setClass(sPlashScreen, K_trivia_cricketActivity.class);
startActivity(i);
}
return true;
}
Don't you threads because it is creating the problem in the higher version. Use the code below to show the splash screen.
package com.Cricket_trivia.in;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.MotionEvent;
public class SplashScreen extends Activity {
protected int _splashTime = 5000;
private Thread splashTread;
MyCount counter = new MyCount(4000, 4000);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
counter.start();
}
public class MyCount extends CountDownTimer
{
public MyCount(long csecond, long countDownInterval)
{
super(csecond, countDownInterval);
}
#Override
public void onFinish() {
finish();
Intent intent = new Intent();
intent.setClass(SplashScreen.this, K_trivia_cricketActivity.class);
startActivity(intent);
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}
}
I think it will work for you

Categories