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

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

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

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

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

Unable to start activity with intent

I'm studying Android development. I have a problem in LogCat, it seems like it is unable to start settings activity:
05-06 09:40:37.323: E/AndroidRuntime(945): FATAL EXCEPTION: main
05-06 09:40:37.323: E/AndroidRuntime(945): Process: com.androiddevbook.onyourbike_chapter4, PID: 945
05-06 09:40:37.323: E/AndroidRuntime(945): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androiddevbook.onyourbike_chapter4/com.androiddevbook.onyourbike_chapter5.activities.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.ActivityThread.access$800(ActivityThread.java:144)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.os.Handler.dispatchMessage(Handler.java:102)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.os.Looper.loop(Looper.java:135)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.ActivityThread.main(ActivityThread.java:5221)
05-06 09:40:37.323: E/AndroidRuntime(945): at java.lang.reflect.Method.invoke(Native Method)
05-06 09:40:37.323: E/AndroidRuntime(945): at java.lang.reflect.Method.invoke(Method.java:372)
05-06 09:40:37.323: E/AndroidRuntime(945): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
05-06 09:40:37.323: E/AndroidRuntime(945): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-06 09:40:37.323: E/AndroidRuntime(945): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
05-06 09:40:37.323: E/AndroidRuntime(945): at com.androiddevbook.onyourbike_chapter5.activities.SettingsActivity.setupActionBar(SettingsActivity.java:48)
05-06 09:40:37.323: E/AndroidRuntime(945): at com.androiddevbook.onyourbike_chapter5.activities.SettingsActivity.onCreate(SettingsActivity.java:40)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.Activity.performCreate(Activity.java:5933)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
05-06 09:40:37.323: E/AndroidRuntime(945): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
05-06 09:40:37.323: E/AndroidRuntime(945): ... 10 more
Here is class where make intent with function clickedSettings for calling SettingsActivity.class Activity ( in runtime when is clicked Settings on the actionBar on top of the screen) :
package com.androiddevbook.onyourbike_chapter5.activities;
import com.androiddevbook.onyourbike_chapter4.BuildConfig;
import com.androiddevbook.onyourbike_chapter4.R;
import com.androiddevbook.onyourbike_chapter5.model.TimerState;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.os.Vibrator;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class TimerActivity extends ActionBarActivity {
private static String CLASS_NAME;
protected TextView counter;
protected Button start;
protected Button stop;
protected Handler handler;
protected UpdateTimer updateTimer;
private static long UPDATE_EVERY = 200;
protected Vibrator vibrate;
protected long lastSeconds;
private TimerState timer;
public TimerActivity(){
CLASS_NAME = getClass().getName();
timer = new TimerState();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
counter = (TextView) findViewById(R.id.timer);
start = (Button) findViewById(R.id.start_button);
stop = (Button) findViewById(R.id.stop_button);
Log.d(CLASS_NAME, "Setting text.");
if (BuildConfig.DEBUG){
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().penaltyDeath().build());
}
timer.reset();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.d(CLASS_NAME, "Showing menu.");
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
Log.d(CLASS_NAME, "SETTINGS PRESSED.");
System.out.println("Settings pressed.");
clickedSettings(null);
return true;
}
return super.onOptionsItemSelected(item);
}
public void clickedStart(View view){
Log.d(CLASS_NAME, "Clicked start button.");
timer.start();
enableButtons();
handler = new Handler();
updateTimer = new UpdateTimer();
handler.postDelayed(updateTimer, UPDATE_EVERY);
}
public void clickedStop(View view){
Log.d(CLASS_NAME, "Clicked stop button.");
timer.stop();
enableButtons();
handler.removeCallbacks(updateTimer);
updateTimer = null;
handler = null;
}
public void enableButtons(){
Log.d(CLASS_NAME, "Set buttons enabled/disabled.");
start.setEnabled(!timer.isRunning());
stop.setEnabled(timer.isRunning());
}
public class UpdateTimer implements Runnable {
public void run(){
Log.d(CLASS_NAME, "run");
setTimeDisplay();
if ( handler != null){
handler.postDelayed(this, UPDATE_EVERY);
}
if ( timer.isRunning() ){
vibrateCheck();
}
}
}
public void onStart(){
super.onStart();
Log.d(CLASS_NAME, "onStart");
if ( timer.isRunning() ){
handler = new Handler();
updateTimer = new UpdateTimer();
handler.postDelayed(updateTimer, UPDATE_EVERY);
}
vibrate = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if (vibrate == null){
Log.w(CLASS_NAME, "No vibrate service exists.");
}
}
public void onPause(){
super.onPause();
Log.d(CLASS_NAME, "onPause");
}
public void onResume(){
super.onResume();
Log.d(CLASS_NAME, "onResume");
}
public void onStop(){
super.onStop();
Log.d(CLASS_NAME, "onSop");
if ( timer.isRunning() ){
handler.removeCallbacks(updateTimer);
handler = null;
updateTimer = null;
}
}
public void onDestroy(){
super.onDestroy();
Log.d(CLASS_NAME, "onDestroy");
}
public void onRestart(){
super.onRestart();
Log.d(CLASS_NAME, "onRestart");
}
protected void vibrateCheck(){
long diff = timer.elapsedTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
seconds = seconds % 60;
minutes = minutes % 60;
Log.d(CLASS_NAME, "vibrateCheck");
if ( vibrate != null && seconds == 0 && seconds != lastSeconds){
long[] once = { 0, 100 };
long[] twice= { 0, 100, 400, 100};
long[] thrice = { 0, 100, 400, 100, 400, 100 };
// every hour
if ( minutes == 0){
Log.d(CLASS_NAME, "Vibrate 3 times");
vibrate.vibrate(thrice, -1);
}
// every 15 minutes
else if ( minutes % 15 == 0 ){
Log.d(CLASS_NAME, "Vibrate 2 times");
vibrate.vibrate(twice, -1);
}
// every 1 minute
else if ( minutes == 1 ){
Log.d(CLASS_NAME, "Vibrate 1 time");
vibrate.vibrate(once, -1);
}
}
lastSeconds = seconds;
}
public void clickedSettings(View view){
Log.d(CLASS_NAME, "clickedSettings.");
Intent settingsIntent = new Intent(this, SettingsActivity.class);
startActivity(settingsIntent);
}
public void setTimeDisplay(){
Log.d(CLASS_NAME, "setTimeDisplay");
counter.setText(timer.display());
}
}
And here is SettingsActivity class, where keep options for vibrate:
package com.androiddevbook.onyourbike_chapter5.activities;
import com.androiddevbook.onyourbike.chapter5.helpers.Toaster;
import com.androiddevbook.onyourbike_chapter4.R;
import com.androiddevbook.onyourbike_chapter5.OnYourBike;
import com.androiddevbook.onyourbike_chapter5.model.Settings;
import android.support.v7.app.ActionBarActivity;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
public class SettingsActivity extends ActionBarActivity {
private CheckBox vibrate;
private String CLASS_NAME = "dada";
public SettingsActivity(){
Log.d(CLASS_NAME, "SettingsActivity.class....");
CLASS_NAME = getClass().getName();
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
vibrate = (CheckBox)
findViewById(R.id.vibrate_checkbox);
Settings settings = ((OnYourBike)getApplication()).getSettings();
vibrate.setChecked(settings.isVibrateOn(this));
setupActionBar();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.settings, 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();
if (id == R.id.home) {
goHome();
return true;
}
return super.onOptionsItemSelected(item);
}
private void goHome() {
Log.d(CLASS_NAME, "gotoHome");
Intent timer =
new Intent(this, TimerActivity.class);
timer.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(timer);
}
public void onStop(){
super.onStop();
Settings settings = ((OnYourBike)getApplication()).getSettings();
settings.setVibrate(this, vibrate.isChecked());
}
public void vibrateChanged(View view){
Toaster toast = new Toaster(getApplicationContext());
if(vibrate.isChecked())
toast.make(R.string.vibrate_on);
else
toast.make(R.string.vibrate_off);
}
public void goBack(View view){
finish();
}
}
And finnaly, spec about my virtual telephone:
CPU/ABI: ARM (armeabi-v7a)
Target: Android 5.0.1 ( API level 21)
As you Extends ActionBarActivity so you need to get ActionBar using
ActionBar actionBar = getSupportActionBar();
According to the error log:
05-06 09:40:37.323: E/AndroidRuntime(945): Process: com.androiddevbook.onyourbike_chapter4, PID: 945
05-06 09:40:37.323: E/AndroidRuntime(945): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androiddevbook.onyourbike_chapter4/com.androiddevbook.onyourbike_chapter5.activities.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
ActionBar actionBar = getActionBar(); line returns a null object.
Reasons:
ActionBarActivity subclasses FragmentActivity which is a support component, change code to ActionBar actionBar = getSupportActionBar();
You might be using a theme like ...Light.NoActionBar, so this due to this also there is no ActionBar present for activities, change theme to a theme that support ActionBar.
Another thing to note, this isn't the reason of this issue but, is that ActionBarActivity is deprecated, use AppCompatActivity from now on.
Your error log says it all:
05-06 09:40:37.323: E/AndroidRuntime(945): Process: com.androiddevbook.onyourbike_chapter4, PID: 945
05-06 09:40:37.323: E/AndroidRuntime(945): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androiddevbook.onyourbike_chapter4/com.androiddevbook.onyourbike_chapter5.activities.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
You are calling a method on a null object:
actionBar.setDisplayHomeAsUpEnabled(true);
So make sure you do a null check or you might need to use getSupportActionBar
change your setupActionBar method like this:
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
}

How to add adMob Banner into getView using the latest SDK - com.google.android.gms.ads

I'm trying to add adMob Banner ads into the getView method used for my ListView in one of my fragments. I'm using the latest adMob SDK (com.google.android.gms.ads.).
I'm only finding examples which use the older versions of the Google SDK. If anyone has a link to example of a current version of Google admob please let me know.
FYI - I took Tim's suggestion. I found a complete sample of code from http://jmsliu.com/1482/adding-admob-banner-in-android-listview-header.html.
Its a different one that I first showed you but is set up with 3 Activities. After several hours of testing I thought I would show you my code and the error I'm currently getting, and the original code. I added "Log.i" throughout the program to determine which line causes the abend. It appears that the ads is returning null. Also, note that the original version of code (after the error section) has special "keytwordSet" logic. I was unable to get rid of the syntax errors so I removed it from my version.
AdRequest adRequest = new AdRequest();
Set keywordsSet = new HashSet();
keywordsSet.add("game");
keywordsSet.add("dating");
keywordsSet.add("money");
keywordsSet.add("girl");
adRequest.addKeywords(keywordsSet);
adView.loadAd(adRequest);
New Code:
PostItemAdapter.java
Adapter Class which configs and returns the View for ListView
*/
package com.jms.admobinlistview;
import java.util.HashSet;
import java.util.Set;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.mediation.admob.AdMobExtras;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class PostItemAdapter extends ArrayAdapter {
private LayoutInflater inflater;
private PostData[] datas;
private Activity mainActivity;
private AdView adView;
public PostItemAdapter(Context context, int textViewResourceId,
PostData[] objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
mainActivity = (Activity) context;
inflater = mainActivity.getLayoutInflater();
datas = objects;
}
static class ViewHolder {
TextView postTitleView;
TextView postDateView;
ImageView postThumbView;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (position == 0) {
if (convertView == null || !(convertView instanceof AdView)) {
if (adView == null) {
Log.i("1", "msg1");
AdView adView = new AdView(mainActivity);
Log.i("2", "msg2");
adView.setAdUnitId("ca-app-pub-4409647944042499/8301167762");
Log.i("3", "msg3");
adView.setAdSize(AdSize.BANNER);
Log.i("4", "msg4");
// Convert the default layout parameters so that they play > nice with
// ListView.
float density = mainActivity.getResources().getDisplayMetrics>
().density;
int height = Math.round(AdSize.BANNER.getHeight() * density);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
AbsListView.LayoutParams.FILL_PARENT,
height);
adView.setLayoutParams(params);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("TEST_DEVICE_ID")
.build();
Log.i("5", "msg5");
adView.loadAd(adRequest);
Log.i("6", "msg6");
}
Log.i("7", "msg7");
convertView = adView;
Log.i("8", "msg8");
}
} else {
Log.i("8", "msg8");
if (convertView == null || convertView instanceof AdView) {
Log.i("9", "msg9");
convertView = inflater.inflate(R.layout.postitem, null);
Log.i("10", "msg10");
viewHolder = new ViewHolder();
Log.i("11", "msg11");
viewHolder.postThumbView = (ImageView) convertView
.findViewById(R.id.postThumb);
Log.i("12", "msg12");
viewHolder.postTitleView = (TextView) convertView
.findViewById(R.id.postTitleLabel);
Log.i("13", "msg13");
viewHolder.postDateView = (TextView) convertView
.findViewById(R.id.postDateLabel);
Log.i("14", "msg14");
convertView.setTag(viewHolder);
Log.i("15", "msg15");
} else {
Log.i("16", "msg16");
viewHolder = (ViewHolder) convertView.getTag();
Log.i("17", "msg17");
}
Log.i("18", "msg18");
if (datas[position].postThumbUrl == null) {
Log.i("19", "msg19");
viewHolder.postThumbView
.setImageResource(R.drawable.postthumb_loading);
}
Log.i("20", "msg20");
viewHolder.postTitleView.setText(datas[position].postTitle);
viewHolder.postDateView.setText(datas[position].postDate);
}
Log.i("21", "msg21");
return convertView;
}
}
Error:
03-16 21:34:10.509: I/1(415): msg1
03-16 21:34:10.530: I/2(415): msg2
03-16 21:34:10.530: I/3(415): msg3
03-16 21:34:10.530: I/4(415): msg4
03-16 21:34:10.582: I/5(415): msg5
03-16 21:34:10.609: D/dalvikvm(415): DexOpt: couldn't find field
Landroid/content/res/Configuration;.smallestScreenWidthDp
03-16 21:34:10.609: W/dalvikvm(415): VFY: unable to resolve instance field 36
03-16 21:34:10.609: D/dalvikvm(415): VFY: replacing opcode 0x52 at 0x0012
03-16 21:34:10.623: D/dalvikvm(415): VFY: dead code 0x0014-0018 in
Lcom/google/android/gms/common/GooglePlayServicesUtil;.b (Landroid/content/res/Resources;)Z
03-16 21:34:10.649: W/GooglePlayServicesUtil(415): Google Play Store is missing.
03-16 21:34:10.730: D/dalvikvm(415): DexOpt: --- BEGIN 'ads256706667.jar' (bootstrap=0) ---
03-16 21:34:10.919: D/dalvikvm(415): DexOpt: --- END 'ads256706667.jar' (success) ---
03-16 21:34:10.919: D/dalvikvm(415): DEX
prep '/data/data/com.jms.admobinlistview/cache/ads256706667.jar': unzip in 2ms, rewrite 193ms
03-16 21:34:11.019: I/Ads(415): Use AdRequest.Builder.addTestDevice
("B3EEABB8EE11C2BE770B684D95219ECB") to get test ads on this device.
03-16 21:34:11.059: I/Ads(415): Starting ad request.
03-16 21:34:11.179: D/dalvikvm(415): GC_EXTERNAL_ALLOC freed 269K, 52% free 2677K/5575K,
external 2032K/2137K, paused 74ms
03-16 21:34:11.499: I/6(415): msg6
03-16 21:34:11.499: I/7(415): msg7
03-16 21:34:11.499: I/8(415): msg8
03-16 21:34:11.509: I/21(415): msg21
03-16 21:34:11.509: D/AndroidRuntime(415): Shutting down VM
03-16 21:34:11.509: W/dalvikvm(415): threadid=1: thread exiting with uncaught exception
(group=0x40015560)
03-16 21:34:11.589: E/AndroidRuntime(415): FATAL EXCEPTION: main
03-16 21:34:11.589: E/AndroidRuntime(415): java.lang.NullPointerException
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.AbsListView.obtainView
(AbsListView.java:1432)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.ListView.makeAndAddView
(ListView.java:1745)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.ListView.fillDown
(ListView.java:670)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.ListView.fillFromTop
(ListView.java:727)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.ListView.layoutChildren
(ListView.java:1598)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.AbsListView.onLayout
(AbsListView.java:1260)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.view.View.layout(View.java:7175)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.LinearLayout.setChildFrame
(LinearLayout.java:1254)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.LinearLayout.layoutVertical
(LinearLayout.java:1130)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.LinearLayout.onLayout
(LinearLayout.java:1047)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.view.View.layout(View.java:7175)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.FrameLayout.onLayout
(FrameLayout.java:338)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.view.View.layout(View.java:7175)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.LinearLayout.setChildFrame
(LinearLayout.java:1254)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.LinearLayout.layoutVertical
(LinearLayout.java:1130)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.LinearLayout.onLayout
(LinearLayout.java:1047)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.view.View.layout(View.java:7175)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.widget.FrameLayout.onLayout
(FrameLayout.java:338)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.view.View.layout(View.java:7175)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.view.ViewRoot.performTraversals
(ViewRoot.java:1140)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.view.ViewRoot.handleMessage
(ViewRoot.java:1859)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.os.Handler.dispatchMessage
(Handler.java:99)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.os.Looper.loop(Looper.java:123)
03-16 21:34:11.589: E/AndroidRuntime(415): at android.app.ActivityThread.main
(ActivityThread.java:3683)
03-16 21:34:11.589: E/AndroidRuntime(415): at java.lang.reflect.Method.invokeNative(Native
Method)
03-16 21:34:11.589: E/AndroidRuntime(415): at java.lang.reflect.Method.invoke(Method.java:507)
03-16 21:34:11.589: E/AndroidRuntime(415): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-16 21:34:11.589: E/AndroidRuntime(415): at com.android.internal.os.ZygoteInit.main
(ZygoteInit.java:597)
03-16 21:34:11.589: E/AndroidRuntime(415): at dalvik.system.NativeStart.main(Native Method)
03-16 21:34:17.879: I/Process(415): Sending signal. PID: 415 SIG: 9
Original Code with previous version of adMob:
/**
* PostItemAdapter.java
*
* Adapter Class which configs and returns the View for ListView
*
*/
package com.jms.admobinlistview;
import java.util.HashSet;
import java.util.Set;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
public class PostItemAdapter extends ArrayAdapter {
private LayoutInflater inflater;
private PostData[] datas;
private Activity mainActivity;
private AdView adView;
public PostItemAdapter(Context context, int textViewResourceId,
PostData[] objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
mainActivity = (Activity) context;
inflater = mainActivity.getLayoutInflater();
datas = objects;
}
static class ViewHolder {
TextView postTitleView;
TextView postDateView;
ImageView postThumbView;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (position == 0) {
if (convertView == null || !(convertView instanceof AdView)) {
if (adView == null) {
adView = new AdView(mainActivity, AdSize.SMART_BANNER,
"a151bd35eeb068d");
AdRequest adRequest = new AdRequest();
Set<String> keywordsSet = new HashSet<String>();
keywordsSet.add("game");
keywordsSet.add("dating");
keywordsSet.add("money");
keywordsSet.add("girl");
adRequest.addKeywords(keywordsSet);
adView.loadAd(adRequest);
}
convertView = adView;
}
} else {
if (convertView == null || convertView instanceof AdView) {
convertView = inflater.inflate(R.layout.postitem, null);
viewHolder = new ViewHolder();
viewHolder.postThumbView = (ImageView) convertView
.findViewById(R.id.postThumb);
viewHolder.postTitleView = (TextView) convertView
.findViewById(R.id.postTitleLabel);
viewHolder.postDateView = (TextView) convertView
.findViewById(R.id.postDateLabel);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if (datas[position].postThumbUrl == null) {
viewHolder.postThumbView
.setImageResource(R.drawable.postthumb_loading);
}
viewHolder.postTitleView.setText(datas[position].postTitle);
viewHolder.postDateView.setText(datas[position].postDate);
}
return convertView;
}
}
===============================================================================
Tim, thanks for getting back to me. The following is my code and error message that I'm getting. I tried several things and I keep getting the same type of errors. Can you please clarify your explanation you gave? Is purview really preview?
package com.robertrichardson.bxxxyxxxxzxxxxLite;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.MenuInflater;
import android.app.Activity;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdRequest.Builder;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.doubleclick.PublisherAdRequest;
import com.google.android.gms.ads.doubleclick.PublisherAdView;
import com.google.android.gms.drive.query.internal.InFilter;
import com.robertrichardson.bxxxyxxxxzxxxxLite.R.string;
/*
* BxxxxListFragment Class: Sets up and displays all Bxxxx Activity on the list.
*/
public class BxxxxListFragment extends SherlockListFragment {
private ArrayList<Bxxxx> mBxxxx;
private boolean mSubtitleVisible;
private LayoutInflater inflater;
private Activity mainActivity;
private static final String AD_UNIT_ID = "ca-app-pub-4409647944042499/8301167762";
public static final String TAG = "BxxxxListFragment";
// private AdView adView;
private AdView adView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
* New ads Logic
*/
setHasOptionsMenu(true);
getSherlockActivity().setTitle(R.string.app_name);
mBxxxx = BxxxxLab.get(getSherlockActivity()).getBxxxx();
BxxxxAdapter adapter = new BxxxxAdapter(mBxxxx);
setListAdapter(adapter);
setRetainInstance(true);
mSubtitleVisible = false;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setEmptyText(getResources().getString(string.new_bxxxx_attack_empty_desc));
registerForContextMenu(getListView());
setHasOptionsMenu(true);
}
#TargetApi(11)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View v = super.onCreateView(inflater, parent, savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (mSubtitleVisible) {
getSherlockActivity().getSupportActionBar().setSubtitle(R.string.subtitle);
}
}
ListView listView = (ListView)v.findViewById(android.R.id.list);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
// Use floating point context menus on Froyer and Gingerbread
registerForContextMenu(listView);
} else {
// Use contextual action bar on Honeycomb and higher
listView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
public boolean onActionItemClicked(
android.view.ActionMode arg0, android.view.MenuItem arg1) {
// TODO Auto-generated method stub
return false;
}
public boolean onCreateActionMode(android.view.ActionMode mode,
android.view.Menu menu) {
// TODO Auto-generated method stub
return false;
}
public void onDestroyActionMode(android.view.ActionMode mode) {
// TODO Auto-generated method stub
}
public boolean onPrepareActionMode(
android.view.ActionMode mode, android.view.Menu menu) {
// TODO Auto-generated method stub
return false;
}
public void onItemCheckedStateChanged(
android.view.ActionMode mode, int position, long id,
boolean checked) {
// TODO Auto-generated method stub
}
// ActionMode.Callback methods
});
}
return v;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Bxxxx c = ((BxxxxAdapter)getListAdapter()).getItem(position);
// Start Bxxxx Activity
Intent i = new Intent(getSherlockActivity(), BxxxxPagerActivity.class);
i.putExtra(BxxxxFragment.EXTRA_BULLIED_ID, c.getId());
startActivityForResult(i, 0);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {>
((BxxxxAdapter)getListAdapter()).notifyDataSetChanged();
}
#Override
public void onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_bxxxx_list, menu);
}
#TargetApi(11)
#Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item)
{
switch (item.getItemId()) {
case R.id.settings:
Intent i=new Intent(getSherlockActivity(), Preferences.class);
startActivity(i);
return(true);
case R.id.about:
i=new Intent(getSherlockActivity(),BxxxxContentActivity.class);
i.putExtra(BxxxxContentActivity.EXTRA_FILE,
"file:///android_asset/misc/about.html");
startActivity(i);
return(true);
case R.id.help:
i=new Intent(getSherlockActivity(),BxxxxContentActivity.class);
i.putExtra(BxxxxContentActivity.EXTRA_FILE,
"file:///android_asset/misc/help.html");
startActivity(i);
return(true);
case R.id.disclaimer:
i=new Intent(getSherlockActivity(),BxxxxContentActivity.class);
i.putExtra(BxxxxContentActivity.EXTRA_FILE,
"file:///android_asset/misc/disclaimer.html");
startActivity(i);
return(true);
case R.id.menu_item_new_bxxxx:
Bxxxx bxxxx = new Bxxxx();
BxxxxLab.get(getSherlockActivity()).addBxxxx(bxxxx);
i = new Intent(getSherlockActivity(), BxxxxPagerActivity.class);
i.putExtra(BxxxxFragment.EXTRA_BULLIED_ID, bxxxx.getId());
startActivityForResult(i,0);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu,View v, ContextMenuInfo menuInfo) {
getActivity().getMenuInflater().inflate(R.menu.bxxxx_list_item_context, menu);
}
#Override
public boolean onContextItemSelected(android.view.MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
int position = info.position;
BxxxxAdapter adapter = (BxxxxAdapter)getListAdapter();
Bxxxx bxxxx = adapter.getItem(position);
switch (item.getItemId()) {
case R.id.menu_item_delete_bxxxx:
BxxxxLab.get(getActivity()).deleteBxxxx(bxxxx);
adapter.notifyDataSetChanged();
return true;
}
return super.onContextItemSelected(item);
}
private class BxxxxAdapter extends ArrayAdapter<Bxxxx> {
public BxxxxAdapter(ArrayList<Bxxxx> bxxxx) {
super(getSherlockActivity(), android.R.layout.simple_list_item_1, bxxxx);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
/*
* New ads Logic
*/
Log.i("1", "msg1");
if (position == 0)
{
if (convertView == null || !(convertView instanceof AdView)) {
if (adView == null) {
Log.i("2", "msg2");
adView = new AdView(mainActivity); <=== Abends on this line
Log.i("3", "msg3");
adView.setAdUnitId("ca-app-pub-4409647944042499/8301167762");
Log.i("4", "msg4");
adView.setAdSize(AdSize.BANNER);
Log.i("5", "msg5");
// Convert the default layout parameters so that they play nice with
// ListView.
float density = mainActivity.getResources().getDisplayMetrics().density;
int height = Math.round(AdSize.BANNER.getHeight() * density);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
AbsListView.LayoutParams.FILL_PARENT,
height);
adView.setLayoutParams(params);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("TEST_DEVICE_ID")
.build();
adView.loadAd(adRequest);
}
convertView = adView;
return convertView;
}
return convertView;
} else {
if (convertView == null || convertView instanceof AdView) {
// If we weren't given a view, inflate one
if (convertView == null) {
convertView = getSherlockActivity().getLayoutInflater()
.inflate(R.layout.list_item_bxxxx, null);
}
// Enter the view of this Bxxxx Attack
Bxxxx c = getItem(position);
TextView titleTextView =
(TextView)convertView.findViewById(R.id.bxxxx_list_item_titleTextView);
titleTextView.setText(c.getTitle());
TextView dateTextView =
(TextView)convertView.findViewById(R.id.bxxxx_list_item_dateTextView);
dateTextView.setText(DateFormat.format("EEEE, MMM dd, yyyy hh : mm a", c.getDate()).toString());
CheckBox resolvedCheckBox =
(CheckBox)convertView.findViewById(R.id.bxxxx_list_item_resolvedCheckBox);
resolvedCheckBox.setChecked(c.isResolved());
return convertView;
}
return convertView;
}
}
}
#Override
public void onResume() {
super.onResume();
((BxxxxAdapter)getListAdapter()).notifyDataSetChanged();
}
}
03-18 06:52:29.785: D/dalvikvm(932): VFY: replacing opcode 0x6f at 0x0006
03-18 06:52:30.085: I/1(932): msg1
03-18 06:52:30.085: I/2(932): msg2
03-18 06:52:30.085: D/AndroidRuntime(932): Shutting down VM
03-18 06:52:30.095: W/dalvikvm(932): threadid=1: thread exiting with uncaught exception (group=0x40015560)
03-18 06:52:30.135: E/AndroidRuntime(932): FATAL EXCEPTION: main
03-18 06:52:30.135: E/AndroidRuntime(932): java.lang.NullPointerException
03-18 06:52:30.135: E/AndroidRuntime(932): at android.view.ViewConfiguration.get(ViewConfiguration.java:228)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.view.View.(View.java:1878)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.view.ViewGroup.(ViewGroup.java:281)
03-18 06:52:30.135: E/AndroidRuntime(932): at com.google.android.gms.ads.AdView.(Unknown Source)
03-18 06:52:30.135: E/AndroidRuntime(932): at com.robertrichardson.bxxxyxxxxzxxxLite.BxxxxListFragment$BxxxxAdapter.getView(BxxxxListFragment.java:251)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.AbsListView.obtainView(AbsListView.java:1430)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.ListView.makeAndAddView(ListView.java:1745)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.ListView.fillDown(ListView.java:670)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.ListView.fillFromTop(ListView.java:727)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.ListView.layoutChildren(ListView.java:1598)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.AbsListView.onLayout(AbsListView.java:1260)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.view.View.layout(View.java:7175)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.view.View.layout(View.java:7175)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.view.View.layout(View.java:7175)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.view.View.layout(View.java:7175)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.view.View.layout(View.java:7175)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.view.View.layout(View.java:7175)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1254)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1130)
03-18 06:52:30.135: E/AndroidRuntime(932): at android.widget.LinearLayout.onLayout(LinearLayout.java:1047)
It looks like you are hiding the class variable 'adView' in the new code by declaring a local variable of the same name. Due to the scope, you're setting convertView to the global adView, which is always null. Just change "AdView adView =" to "adView ="

Categories