Force Closes on Opening Activity - java

I am working on an app where you touch the screen and the basketball moves there. I am almost there except it force closes when you open this mini-app from a list of activities to start. After scanning through several times I could not find anything.
This is my Java Class and after is the Logcat:
package com.frostbytedev.addsub;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
public class SurfaceViewExample extends Activity implements OnTouchListener {
OurView v;
Bitmap ball;
float x = 0;
float y = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
v = new OurView(this);
setContentView(v);
v.setOnTouchListener(this);
ball = BitmapFactory.decodeResource(getResources(), R.drawable.bball);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
v.pause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
v.resume();
}
public class OurView extends SurfaceView implements Runnable {
Thread t = null;
SurfaceHolder holder;
boolean isItOkay = false;
public OurView(Context context) {
super(context);
// TODO Auto-generated constructor stub
holder = getHolder();
}
#Override
public void run() {
// TODO Auto-generated method stub
while(isItOkay) {
if(!holder.getSurface().isValid()){
continue;
}
Canvas c = holder.lockCanvas();
c.drawARGB(255, 150, 150, 150);
c.drawBitmap(ball, x-(ball.getWidth()/2), y-(ball.getHeight()/2), null);
holder.unlockCanvasAndPost(c);
}
}
public void pause(){
isItOkay = false;
while(true){
try{
t.join();
} catch(InterruptedException e){
e.printStackTrace();
}
}
}
public void resume() {
isItOkay = true;
t = new Thread(this);
t.start();
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
x = event.getX();
y = event.getY();
return false;
}
}
Logcat:
05-09 19:24:35.730: D/libEGL(8218): loaded /system/lib/egl/libEGL_adreno200.so
05-09 19:24:35.740: D/libEGL(8218): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
05-09 19:24:35.750: D/libEGL(8218): loaded /system/lib/egl/libGLESv2_adreno200.so
05-09 19:24:35.800: D/OpenGLRenderer(8218): Enabling debug mode 0
05-09 19:24:44.658: D/AndroidRuntime(8218): Shutting down VM
05-09 19:24:44.658: W/dalvikvm(8218): threadid=1: thread exiting with uncaught exception (group=0x40a7a930)
05-09 19:24:44.668: E/AndroidRuntime(8218): FATAL EXCEPTION: main
05-09 19:24:44.668: E/AndroidRuntime(8218): java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
05-09 19:24:44.668: E/AndroidRuntime(8218): at com.frostbytedev.addsub.Menu.onListItemClick(Menu.java:25)
05-09 19:24:44.668: E/AndroidRuntime(8218): at android.app.ListActivity$2.onItemClick(ListActivity.java:319)
05-09 19:24:44.668: E/AndroidRuntime(8218): at android.widget.AdapterView.performItemClick(AdapterView.java:298)
05-09 19:24:44.668: E/AndroidRuntime(8218): at android.widget.AbsListView.performItemClick(AbsListView.java:1102)
05-09 19:24:44.668: E/AndroidRuntime(8218): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2751)
05-09 19:24:44.668: E/AndroidRuntime(8218): at android.widget.AbsListView$1.run(AbsListView.java:3426)
05-09 19:24:44.668: E/AndroidRuntime(8218): at android.os.Handler.handleCallback(Handler.java:725)
05-09 19:24:44.668: E/AndroidRuntime(8218): at android.os.Handler.dispatchMessage(Handler.java:92)
05-09 19:24:44.668: E/AndroidRuntime(8218): at android.os.Looper.loop(Looper.java:137)
05-09 19:24:44.668: E/AndroidRuntime(8218): at android.app.ActivityThread.main(ActivityThread.java:5237)
05-09 19:24:44.668: E/AndroidRuntime(8218): at java.lang.reflect.Method.invokeNative(Native Method)
05-09 19:24:44.668: E/AndroidRuntime(8218): at java.lang.reflect.Method.invoke(Method.java:511)
05-09 19:24:44.668: E/AndroidRuntime(8218): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:799)
05-09 19:24:44.668: E/AndroidRuntime(8218): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
05-09 19:24:44.668: E/AndroidRuntime(8218): at dalvik.system.NativeStart.main(Native Method)

Related

Bluetooth Messenger application crashing at start up itself

I have tried to learn to write an application which is basically a bluetooth messenger. Things had been fine unless I tried to install and run it. It gets installed successfully but crashes down at start up itself. Can you please tell me what is wrong ?
This is the code for the main activity. There are three more activities apart from this.
import java.io.IOException;
import java.util.ArrayList;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
public final static String UUID = "3606f360-e4df-11e0-9572-0800200c9a66";
BluetoothAdapter bluetoothAdapter;
BroadcastReceiver discoverDevicesReceiver;
BroadcastReceiver discoveryFinishedReceiver;
//---store all the discovered devices---
ArrayList<BluetoothDevice> discoveredDevices;
ArrayList<String> discoveredDevicesNames;
//---store all the paired devices---
ArrayList<BluetoothDevice> pairedDevices;
static TextView txtData;
EditText txtMessage;
//---thread for running the server socket---
ServerThread serverThread;
//---thread for connecting to the client socket---
ConnectToServerThread connectToServerThread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//---init the ArrayList objects and bluetooth adapter---
discoveredDevices = new ArrayList<BluetoothDevice>();
discoveredDevicesNames = new ArrayList<String>();
pairedDevices = new ArrayList<BluetoothDevice>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//---for displaying the messages received---
txtData = (TextView) findViewById(R.id.txtData);
txtMessage = (EditText) findViewById(R.id.txtMessage);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
//---make yourself discoverable---
public void MakeDiscoverable(View view)
{
Intent i = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
i.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(i);
}
/*
//---find all the previously paired devices---
private void QueryPairedDevices(){
Set<BluetoothDevice> allPairedDevices =
bluetoothAdapter.getBondedDevices();
//---if there are paired devices---
if (allPairedDevices.size() > 0) {
//---loop through paired devices---
for (BluetoothDevice device : allPairedDevices) {
//---add the name and address to an array adapter
// to show in a ListView---
Log.d("UsingBluetooth", device.getName() + "\n" +
device.getAddress());
pairedDevices.add(device);
}
}
}
*/
//---used to discover other bluetooth devices---
private void DiscoveringDevices() {
if (discoverDevicesReceiver == null) {
discoverDevicesReceiver = new BroadcastReceiver() {
//---fired when a new device is discovered---
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//---a device is discovered---
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//---get the BluetoothDevice object from
// the Intent---
BluetoothDevice device =
intent.getParcelableExtra(
BluetoothDevice.EXTRA_DEVICE);
//---add the name and address to an array
// adapter to show in a ListView---
//---only add if the device is not already
// in the list---
if (!discoveredDevices.contains(device)) {
//---add the device---
discoveredDevices.add(device);
//---add the name of the device; used for
// ListView---
discoveredDevicesNames.add(device.getName());
//---display the items in the ListView---
setListAdapter(new
ArrayAdapter<String>(getBaseContext(),
android.R.layout.simple_list_item_1,
discoveredDevicesNames));
}
}
}
};
}
if (discoveryFinishedReceiver==null) {
discoveryFinishedReceiver = new BroadcastReceiver() {
//---fired when the discovery is done---
#Override
public void onReceive(Context context, Intent intent) {
//---enable the listview when discovery is over; about 12 seconds---
getListView().setEnabled(true);
Toast.makeText(getBaseContext(),
"Discovery completed. Select a device to start chatting.",
Toast.LENGTH_LONG).show();
unregisterReceiver(discoveryFinishedReceiver);
}
};
}
//---register the broadcast receivers---
IntentFilter filter1 = new
IntentFilter(BluetoothDevice.ACTION_FOUND);
IntentFilter filter2 = new
IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discoverDevicesReceiver, filter1);
registerReceiver(discoveryFinishedReceiver, filter2);
//---disable the listview when discover is in progress---
getListView().setEnabled(false);
Toast.makeText(getBaseContext(),
"Discovery in progress...please wait...",
Toast.LENGTH_LONG).show();
bluetoothAdapter.startDiscovery();
}
//---discover other bluetooth devices---
public void DiscoverDevices(View view)
{
//---query for all paired devices---
//QueryPairedDevices();
//---discover other devices---
DiscoveringDevices();
}
#Override
public void onPause() {
super.onPause();
//---cancel discovery of other bluetooth devices
bluetoothAdapter.cancelDiscovery();
//---unregister the broadcast receiver for
// discovering devices---
if (discoverDevicesReceiver != null) {
try {
unregisterReceiver(discoverDevicesReceiver);
} catch(Exception e) {
}
}
//---if you are currently connected to someone...---
if (connectToServerThread!=null) {
try {
//---close the connection---
connectToServerThread.bluetoothSocket.close();
} catch (IOException e) {
Log.d("MainActivity", e.getLocalizedMessage());
}
}
//---stop the thread running---
if (serverThread!=null) serverThread.cancel();
}
//---used for updating the UI on the main activity---
static Handler UIupdater = new Handler() {
#Override
public void handleMessage(Message msg) {
int numOfBytesReceived = msg.arg1;
byte[] buffer = (byte[]) msg.obj;
//---convert the entire byte array to string---
String strReceived = new String(buffer);
//---extract only the actual string received---
strReceived = strReceived.substring(
0, numOfBytesReceived);
//---display the text received on the TextView---
txtData.setText(txtData.getText().toString() +
strReceived);
}
};
#Override
public void onResume() {
super.onResume();
//---start the socket server---
serverThread = new ServerThread(bluetoothAdapter);
serverThread.start();
}
//---when a client is tapped in the ListView---
public void onListItemClick(ListView parent, View v,
int position, long id) {
//---if you are already talking to someone...---
if (connectToServerThread!=null) {
try {
//---close the connection first---
connectToServerThread.bluetoothSocket.close();
} catch (IOException e) {
Log.d("MainActivity", e.getLocalizedMessage());
}
}
//---connect to the selected Bluetooth device---
BluetoothDevice deviceSelected =
discoveredDevices.get(position);
connectToServerThread = new
ConnectToServerThread(deviceSelected, bluetoothAdapter);
connectToServerThread.start();
//---tell the user that he is connected to who---
Toast.makeText(this, "You have connected to " +
discoveredDevices.get(position).getName(),
Toast.LENGTH_SHORT).show();
}
private class WriteTask extends AsyncTask<String, Void, Void> {
protected Void doInBackground(String... args) {
try {
connectToServerThread.commsThread.write(args[0]);
} catch (Exception e) {
Log.d("MainActivity", e.getLocalizedMessage());
}
return null;
}
}
//---send a message to the connected socket client---
public void SendMessage(View view)
{
if (connectToServerThread!=null) {
///=========
//connectToServerThread.commsThread.write(
// txtMessage.getText().toString());
new WriteTask().execute(txtMessage.getText().toString());
///=========
} else {
Toast.makeText(this, "Select a client first",
Toast.LENGTH_SHORT).show();
}
}
}
ServerThread class :
import java.io.IOException;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
public class ServerThread extends Thread {
//---the server socket---
private final BluetoothServerSocket bluetoothServerSocket;
public ServerThread(BluetoothAdapter bluetoothAdapter) {
BluetoothServerSocket tmp = null;
try {
//---UUID must be the same for both the client and
// the server---
tmp =
bluetoothAdapter.listenUsingRfcommWithServiceRecord(
"BluetoothApp", UUID.fromString(MainActivity.UUID));
} catch (IOException e) {
Log.d("ServerThread", e.getLocalizedMessage());
}
bluetoothServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
//---keep listening until exception occurs
// or a socket is returned---
while (true) {
try {
socket = bluetoothServerSocket.accept();
} catch (IOException e) {
Log.d("ServerThread", e.getLocalizedMessage());
break;
}
//---if a connection was accepted---
if (socket != null) {
//---create a separate thread to listen for
// incoming data---
CommsThread commsThread = new CommsThread(socket);
commsThread.run();
}
}
}
public void cancel() {
try {
bluetoothServerSocket.close();
} catch (IOException e) {
Log.d("ServerThread", e.getLocalizedMessage());
}
}
}
LogCat
04-13 18:25:06.684: D/AndroidRuntime(397): Shutting down VM
04-13 18:25:06.684: W/dalvikvm(397): threadid=1: thread exiting with uncaught exception (group=0x40015560)
04-13 18:25:06.704: E/AndroidRuntime(397): FATAL EXCEPTION: main
04-13 18:25:06.704: E/AndroidRuntime(397): java.lang.RuntimeException: Unable to resume activity {net.learn2develop.usingbluetooth/net.learn2develop.usingbluetooth.MainActivity}: java.lang.NullPointerException
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2120)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2135)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1668)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.os.Handler.dispatchMessage(Handler.java:99)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.os.Looper.loop(Looper.java:123)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-13 18:25:06.704: E/AndroidRuntime(397): at java.lang.reflect.Method.invokeNative(Native Method)
04-13 18:25:06.704: E/AndroidRuntime(397): at java.lang.reflect.Method.invoke(Method.java:507)
04-13 18:25:06.704: E/AndroidRuntime(397): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-13 18:25:06.704: E/AndroidRuntime(397): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-13 18:25:06.704: E/AndroidRuntime(397): at dalvik.system.NativeStart.main(Native Method)
04-13 18:25:06.704: E/AndroidRuntime(397): Caused by: java.lang.NullPointerException
04-13 18:25:06.704: E/AndroidRuntime(397): at net.learn2develop.usingbluetooth.ServerThread.<init>(ServerThread.java:21)
04-13 18:25:06.704: E/AndroidRuntime(397): at net.learn2develop.usingbluetooth.MainActivity.onResume(MainActivity.java:235)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.Activity.performResume(Activity.java:3832)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2110)
04-13 18:25:06.704: E/AndroidRuntime(397): ... 12 more
04-13 18:25:08.764: I/Process(397): Sending signal. PID: 397 SIG: 9
04-13 18:25:10.354: D/AndroidRuntime(415): Shutting down VM
04-13 18:25:10.354: W/dalvikvm(415): threadid=1: thread exiting with uncaught exception (group=0x40015560)
04-13 18:25:10.364: E/AndroidRuntime(415): FATAL EXCEPTION: main
04-13 18:25:10.364: E/AndroidRuntime(415): java.lang.RuntimeException: Unable to resume activity {net.learn2develop.usingbluetooth/net.learn2develop.usingbluetooth.MainActivity}: java.lang.NullPointerException
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2120)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2135)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1668)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.os.Handler.dispatchMessage(Handler.java:99)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.os.Looper.loop(Looper.java:123)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-13 18:25:10.364: E/AndroidRuntime(415): at java.lang.reflect.Method.invokeNative(Native Method)
04-13 18:25:10.364: E/AndroidRuntime(415): at java.lang.reflect.Method.invoke(Method.java:507)
04-13 18:25:10.364: E/AndroidRuntime(415): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-13 18:25:10.364: E/AndroidRuntime(415): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-13 18:25:10.364: E/AndroidRuntime(415): at dalvik.system.NativeStart.main(Native Method)
04-13 18:25:10.364: E/AndroidRuntime(415): Caused by: java.lang.NullPointerException
04-13 18:25:10.364: E/AndroidRuntime(415): at net.learn2develop.usingbluetooth.ServerThread.<init>(ServerThread.java:21)
04-13 18:25:10.364: E/AndroidRuntime(415): at net.learn2develop.usingbluetooth.MainActivity.onResume(MainActivity.java:235)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.Activity.performResume(Activity.java:3832)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2110)
04-13 18:25:10.364: E/AndroidRuntime(415): ... 12 more
04-13 18:25:13.304: I/Process(415): Sending signal. PID: 415 SIG: 9
Possible changes you can try which might help you.
In ServerThread.java
public void run() {
....
while(!Thread.currentThread().isInterrupted()){
//do something
}
}
If this works fine, otherwise try:
In MainActivity.java
#Override
public void onCreate() {
....
//Start your thread here
//---start the socket server---
serverThread = new ServerThread(bluetoothAdapter);
serverThread.start();
}
#Override
public void onResume() {
super.onResume();
//handle your thread here - the following maynot be helpful, but logiaclly speaking, //you must handle your threads here
if(serverThread.isAlive())
serverThread.resume();
else
serverThread.interrupt();
}

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 ="

Camera Application by Callling another class

I am working on a Flashlight project. I wanna do this by using another class.
Here is my mainactivity.java file:
package com.efsunderin.callcamera;
import android.hardware.Camera;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button bFlash;
Button cFlash;
MyCamera bnmcamera;
Camera camera;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bFlash = (Button)findViewById(R.id.btnFlash);
cFlash = (Button)findViewById(R.id.closeFlash);
bFlash.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
bnmcamera.getCamera();
bnmcamera.turnOnFlash();
}
});
cFlash.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
bnmcamera.turnOffFlash();
}
});
}
#Override
protected void onStop() {
super.onStop();
// on stop release the camera
if (camera != null) {
camera.release();
camera = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
In this activity I am calling the class below:
package com.efsunderin.callcamera;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
public class MyCamera {
Camera camera;
Parameters params;
public void getCamera() {
camera.open();
params = camera.getParameters();
camera.startPreview();
}
public void turnOnFlash() {
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
}
public void turnOffFlash() {
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.startPreview();
}
}
But it's not working, the system shutdown the app when I touch the button to turn on flash. What am I doing wrong? Please help. thanks.
Here is logcat *output:*
08-31 08:53:22.157: D/AndroidRuntime(287): CheckJNI is ON
08-31 08:53:22.347: D/AndroidRuntime(287): --- registering native functions ---
08-31 08:53:23.247: D/dalvikvm(218): GC_EXPLICIT freed 406 objects / 23512 bytes in 68ms
08-31 08:53:23.367: D/PackageParser(58): Scanning package: /data/app/vmdl50609.tmp
08-31 08:53:23.586: I/PackageManager(58): Removing non-system package:com.eeecoder.callcamera
08-31 08:53:23.586: I/ActivityManager(58): Force stopping package com.eeecoder.callcamera uid=10049
08-31 08:53:23.777: D/PackageManager(58): Scanning package com.eeecoder.callcamera
08-31 08:53:23.777: I/PackageManager(58): Package com.eeecoder.callcamera codePath changed from /data/app/com.eeecoder.callcamera-1.apk to /data/app/com.eeecoder.callcamera-2.apk; Retaining data and using new
08-31 08:53:23.787: I/PackageManager(58): /data/app/com.eeecoder.callcamera-2.apk changed; unpacking
08-31 08:53:23.807: D/installd(34): DexInv: --- BEGIN '/data/app/com.eeecoder.callcamera-2.apk' ---
08-31 08:53:25.380: D/dalvikvm(294): DexOpt: load 205ms, verify 971ms, opt 42ms
08-31 08:53:25.427: D/installd(34): DexInv: --- END '/data/app/com.eeecoder.callcamera-2.apk' (success) ---
08-31 08:53:25.427: W/PackageManager(58): Code path for pkg : com.eeecoder.callcamera changing from /data/app/com.eeecoder.callcamera-1.apk to /data/app/com.eeecoder.callcamera-2.apk
08-31 08:53:25.427: W/PackageManager(58): Resource path for pkg : com.eeecoder.callcamera changing from /data/app/com.eeecoder.callcamera-1.apk to /data/app/com.eeecoder.callcamera-2.apk
08-31 08:53:25.427: D/PackageManager(58): Activities: com.eeecoder.callcamera.MainActivity
08-31 08:53:25.447: I/ActivityManager(58): Force stopping package com.eeecoder.callcamera uid=10049
08-31 08:53:25.667: I/installd(34): move /data/dalvik-cache/data#app#com.eeecoder.callcamera-2.apk#classes.dex -> /data/dalvik-cache/data#app#com.eeecoder.callcamera-2.apk#classes.dex
08-31 08:53:25.667: D/PackageManager(58): New package installed in /data/app/com.eeecoder.callcamera-2.apk
08-31 08:53:25.897: I/ActivityManager(58): Force stopping package com.eeecoder.callcamera uid=10049
08-31 08:53:26.077: D/dalvikvm(58): GC_EXPLICIT freed 12492 objects / 745576 bytes in 179ms
08-31 08:53:26.277: D/dalvikvm(123): GC_EXPLICIT freed 7018 objects / 337856 bytes in 232ms
08-31 08:53:26.857: W/RecognitionManagerService(58): no available voice recognition services found
08-31 08:53:27.067: D/dalvikvm(150): GC_EXPLICIT freed 3878 objects / 211624 bytes in 638ms
08-31 08:53:27.212: D/dalvikvm(58): GC_EXPLICIT freed 5013 objects / 274168 bytes in 119ms
08-31 08:53:27.217: I/installd(34): unlink /data/dalvik-cache/data#app#com.eeecoder.callcamera-1.apk#classes.dex
08-31 08:53:27.267: D/AndroidRuntime(287): Shutting down VM
08-31 08:53:27.287: D/dalvikvm(287): Debugger has detached; object registry had 1 entries
08-31 08:53:27.307: I/AndroidRuntime(287): NOTE: attach of thread 'Binder Thread #3' failed
08-31 08:53:27.857: D/AndroidRuntime(299): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
08-31 08:53:27.857: D/AndroidRuntime(299): CheckJNI is ON
08-31 08:53:28.127: D/AndroidRuntime(299): --- registering native functions ---
08-31 08:53:29.177: I/ActivityManager(58): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.eeecoder.callcamera/.MainActivity }
08-31 08:53:29.267: D/AndroidRuntime(299): Shutting down VM
08-31 08:53:29.297: D/dalvikvm(299): Debugger has detached; object registry had 1 entries
08-31 08:53:29.337: I/ActivityManager(58): Start proc com.eeecoder.callcamera for activity com.eeecoder.callcamera/.MainActivity: pid=306 uid=10049 gids={1006}
08-31 08:53:29.387: I/dalvikvm(299): JNI: AttachCurrentThread (from ???.???)
08-31 08:53:29.387: I/AndroidRuntime(299): NOTE: attach of thread 'Binder Thread #3' failed
08-31 08:53:30.257: I/ActivityManager(58): Displayed activity com.eeecoder.callcamera/.MainActivity: 989 ms (total 989 ms)
08-31 08:53:35.357: D/dalvikvm(123): GC_EXPLICIT freed 965 objects / 55776 bytes in 68ms
08-31 08:53:40.367: D/dalvikvm(218): GC_EXPLICIT freed 117 objects / 5144 bytes in 72ms
08-31 08:53:45.377: D/dalvikvm(257): GC_EXPLICIT freed 759 objects / 55000 bytes in 80ms
08-31 08:54:31.157: D/SntpClient(58): request time failed: java.net.SocketException: Address family not supported by protocol
Here is error log output when I touch the button it gives these output and stopped by the system :
error log:
08-31 09:55:19.347: E/AndroidRuntime(357): FATAL EXCEPTION: main
08-31 09:55:19.347: E/AndroidRuntime(357): java.lang.NullPointerException
08-31 09:55:19.347: E/AndroidRuntime(357): at com.eeecoder.callcamera.MyCamera.getCamera(MyCamera.java:24)
08-31 09:55:19.347: E/AndroidRuntime(357): at com.eeecoder.callcamera.MainActivity$1.onClick(MainActivity.java:35)
08-31 09:55:19.347: E/AndroidRuntime(357): at android.view.View.performClick(View.java:2408)
08-31 09:55:19.347: E/AndroidRuntime(357): at android.view.View$PerformClick.run(View.java:8816)
08-31 09:55:19.347: E/AndroidRuntime(357): at android.os.Handler.handleCallback(Handler.java:587)
08-31 09:55:19.347: E/AndroidRuntime(357): at android.os.Handler.dispatchMessage(Handler.java:92)
08-31 09:55:19.347: E/AndroidRuntime(357): at android.os.Looper.loop(Looper.java:123)
08-31 09:55:19.347: E/AndroidRuntime(357): at android.app.ActivityThread.main(ActivityThread.java:4627)
08-31 09:55:19.347: E/AndroidRuntime(357): at java.lang.reflect.Method.invokeNative(Native Method)
08-31 09:55:19.347: E/AndroidRuntime(357): at java.lang.reflect.Method.invoke(Method.java:521)
08-31 09:55:19.347: E/AndroidRuntime(357): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-31 09:55:19.347: E/AndroidRuntime(357): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-31 09:55:19.347: E/AndroidRuntime(357): at dalvik.system.NativeStart.main(Native Method)
I initialized required objects, but it still gives NullPointerException, why does it give this error? I don't understand. Please take a look at error log output.
You have not initialized your variables bnmCamera and camera.
MyCamera bnmcamera;
Camera camera;
initialize those variables and then use it.
if you use variables without initializing it will give you NullPointerException.
I think you want to do this:(You have not used camera object anywhere)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bFlash = (Button)findViewById(R.id.btnFlash);
cFlash = (Button)findViewById(R.id.closeFlash);
//initialize bnmcamera
bnmcamera = new MyCamera();
bFlash.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
bnmcamera.getCamera();
bnmcamera.turnOnFlash();
}
});
cFlash.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
bnmcamera.turnOffFlash();
}
});
}
Camera class:
You dont have start camera preview every time. and if you want do do that you have stop preview if it is already started release the camera and then start again.
check this link Camera Preview Demo
EDIT:
try this:
public void getCamera() {
camera = camera.open();
params = camera.getParameters();
camera.startPreview();
}
public void turnOnFlash() {
if(camera != null){
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
}else{
Log.e("CHECK","Camera null");
}
}
do this check in all functions.
You forgot to create object first before calling the method.
here you go:
private MyCamera=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
**MyCamera bnmcamera=new MyCamera();**
bFlash = (Button)findViewById(R.id.btnFlash);
cFlash = (Button)findViewById(R.id.closeFlash);
bFlash.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
bnmcamera.getCamera();
bnmcamera.turnOnFlash();
}
});

Android music player prepare method failed

I have been trying to play an MP3 file. It just won't work.
I did manage to play it and add all sorts of functionalities to it with the very same/similar code a few days ago. Just tried to make it all over again and now these errors...
Can someone point out the error also why does this happen.
Just to clarify I used different formats of URI, none of them work. Thought maybe its the prepare method.
package com.player.phoneagent.gui;
import java.io.IOException;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class AndroidClientActivity extends Activity {
/** Called when the activity is first created. */
private MediaPlayer mp;
String path = "android.resource://com.player.phoneagent/raw/test";
ImageButton btn_prev;
ImageButton btn_play;
ImageButton btn_pause;
ImageButton btn_next;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_prev = (ImageButton) findViewById(R.id.ImageButton01);
btn_pause = (ImageButton) findViewById(R.id.ImageButton02);
btn_play = (ImageButton) findViewById(R.id.ImageButton03);
btn_next = (ImageButton) findViewById(R.id.ImageButton04);
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
btn_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mp.setDataSource(path);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
});
}
}
08-01 07:06:00.142: W/KeyCharacterMap(407): No keyboard for id 0
08-01 07:06:00.142: W/KeyCharacterMap(407): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
08-01 07:06:05.821: D/dalvikvm(407): GC_EXPLICIT freed 21K, 53% free 2568K/5379K, external 3207K/3962K, paused 55ms
08-01 07:06:20.311: D/dalvikvm(444): GC_EXTERNAL_ALLOC freed 52K, 53% free 2552K/5379K, external 1969K/2137K, paused 58ms
08-01 07:06:43.171: E/MediaPlayer(444): error (1, -2147483648)
08-01 07:06:43.171: W/System.err(444): java.io.IOException: Prepare failed.: status=0x1
08-01 07:06:43.171: W/System.err(444): at android.media.MediaPlayer.prepare(Native Method)
08-01 07:06:43.171: W/System.err(444): at com.player.phoneagent.gui.AndroidClientActivity$1.onClick(AndroidClientActivity.java:60)
08-01 07:06:43.171: W/System.err(444): at android.view.View.performClick(View.java:2485)
08-01 07:06:43.171: W/System.err(444): at android.view.View$PerformClick.run(View.java:9080)
08-01 07:06:43.181: W/System.err(444): at android.os.Handler.handleCallback(Handler.java:587)
08-01 07:06:43.181: W/System.err(444): at android.os.Handler.dispatchMessage(Handler.java:92)
08-01 07:06:43.181: W/System.err(444): at android.os.Looper.loop(Looper.java:123)
08-01 07:06:43.181: W/System.err(444): at android.app.ActivityThread.main(ActivityThread.java:3683)
08-01 07:06:43.181: W/System.err(444): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 07:06:43.181: W/System.err(444): at java.lang.reflect.Method.invoke(Method.java:507)
08-01 07:06:43.181: W/System.err(444): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-01 07:06:43.181: W/System.err(444): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-01 07:06:43.181: W/System.err(444): at dalvik.system.NativeStart.main(Native Method)
08-01 07:06:43.181: E/MediaPlayer(444): start called in state 0
08-01 07:06:43.181: E/MediaPlayer(444): error (-38, 0)
08-01 07:06:43.181: E/MediaPlayer(444): Error (-38,0)
I always had problems trying to use "raw" folder... I suggest putting the sound file in "assets" and using the methods here to set / prepare / and play:
http://droidapp.co.uk/2011/06/08/android-dev-playing-a-mp3-from-assets/
Just do something like:
MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mp = MediaPlayer.create(this, R.raw.yourSongFileName);
btn_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.stop();
mp.release();
mp = null;
mp = MediaPlayer.create(this, R.raw.yourSongFileName);
mp.start();
//Other stuff below.
See if that works.

Android radio streaming app crashes when you press pause or stop at the moment you haven't clicked play

When i start my app and press stop or pause the android app will crash. It works fine if you press play first and then stop or pause. I searched on google and stackoverflow but i couldn't find much about it. I think the problem is because of a NullPointerException but since i'm new too java it doesn't tell me much about the problem
The code:
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class myMain extends Activity implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener, OnClickListener {
private String TAG = getClass().getSimpleName();
private MediaPlayer mp= null;
private Button play;
private Button pause;
private Button stop;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
play = (Button) findViewById(R.id.play);
pause = (Button) findViewById(R.id.pause);
stop = (Button) findViewById(R.id.stop);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
play();
}
});
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
stop();
}
});
}
private void play() {
Uri myUri = Uri.parse("url");
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
Log.d(TAG, "LoadClip Done");
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
mp.start();
}
private void pause() {
mp.pause();
}
private void stop() {
mp.stop();
}
#Override
public void onDestroy() {
super.onDestroy();
stop();
}
public void onCompletion(MediaPlayer mp) {
stop();
}
public boolean onError(MediaPlayer mp, int what, int extra) {
StringBuilder sb = new StringBuilder();
sb.append("Media Player Error: ");
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
}
sb.append(" (" + what + ") ");
sb.append(extra);
Log.e(TAG, sb.toString());
return true;
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.d(TAG, "PlayerService onBufferingUpdate : " + percent + "%");
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
The errors:
02-11 20:45:43.837: D/AndroidRuntime(338): Shutting down VM
02-11 20:45:43.837: W/dalvikvm(338): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-11 20:45:43.857: E/AndroidRuntime(338): FATAL EXCEPTION: main
02-11 20:45:43.857: E/AndroidRuntime(338): java.lang.NullPointerException
02-11 20:45:43.857: E/AndroidRuntime(338): at wadio.media.internetradio.myMain.stop(myMain.java:95)
02-11 20:45:43.857: E/AndroidRuntime(338): at wadio.media.internetradio.myMain.access$2(myMain.java:94)
02-11 20:45:43.857: E/AndroidRuntime(338): at wadio.media.internetradio.myMain$3.onClick(myMain.java:55)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.view.View.performClick(View.java:2485)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.view.View$PerformClick.run(View.java:9080)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.os.Handler.handleCallback(Handler.java:587)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.os.Handler.dispatchMessage(Handler.java:92)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.os.Looper.loop(Looper.java:123)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-11 20:45:43.857: E/AndroidRuntime(338): at java.lang.reflect.Method.invokeNative(Native Method)
02-11 20:45:43.857: E/AndroidRuntime(338): at java.lang.reflect.Method.invoke(Method.java:507)
02-11 20:45:43.857: E/AndroidRuntime(338): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-11 20:45:43.857: E/AndroidRuntime(338): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-11 20:45:43.857: E/AndroidRuntime(338): at dalvik.system.NativeStart.main(Native Method)
In your stop() method you access the mp variable. However, the mp variable is null until you press play (and the play() method is called). So when you try to access the null variable a NullPointerException is thrown.
A very simple way to stop the NullPointerException is to do something like this:
private void pause() {
if(mp!=null) mp.pause();
}
private void stop() {
if(mp!=null) mp.stop();
}
Of course this solution doesn't account for cases where pause or stop is called twice. Take a look at the MediaPlayer documentation for more info on state management.

Categories