This is the MainActivity file. When I run it in the emulator and phone, logcat displays a crash due to a NullPointerException. I've read a lot about not letting the user or another activity pass "null" value to my method but could not get around this.
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//I used a listview with id= "filelist" in layout
ListView lv;
ArrayList<String> FilesInFolder;
FilesInFolder = GetFiles(Environment.getExternalStorageDirectory().getPath()+ "/sdcard/");
lv = (ListView)findViewById(R.id.filelist);
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, FilesInFolder);
lv.setAdapter(listAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Clicking on items
}
});
}
public ArrayList<String> GetFiles(String DirectoryPath) {
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0)
return null;
else {
for (int i=0; i<files.length; i++)
MyFiles.add(files[i].getName());
}
return MyFiles;
}
}
This is the logcat:
07-02 01:09:40.500 4407-4407/com.amenhotep.filelister W/dalvikvm: threadid=1: calling UncaughtExceptionHandler
07-02 01:09:40.501 4407-4407/com.amenhotep.filelister E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.amenhotep.filelister, PID: 4407
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.amenhotep.filelister/com.amenhotep.filelister.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2389)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.amenhotep.filelister.MainActivity.GetFiles(MainActivity.java:44)
at com.amenhotep.filelister.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5343)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
the problem is in your sdcard path, use this code to get path of sdcard
String DIR_SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath();
and there is no need to add "/sdcard/" to it, also change your GetFiles method, and remove mkdirs() because sdcard exists before.
look at this example
File sdcard_files_and_folders[] = new File(DIR_SDCARD).listFiles();
for (File fileOrFolder: sdcard_files_and_folders) {
// do any thing that you want, add them to list or...
Log.i("FILE", fileOrFolder.toString());
}
Related
My app keeps crashing since I started using a TextWatcher...
As you can see below i made a TextWatcher to 3 EditText fields...
And i made a button which listens to the 3 EditText..
If they are empty the button become disabled.
When the fields are filled the button should become enabled..
package com.example.magazijnapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.MenuPopupWindow;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.sql.Array;
public class MainActivity extends AppCompatActivity {
Spinner spinnermagazijn;
Button knop;
private EditText EditTextregisternummerbalk;
private EditText EditTextticketnummerbalk;
private EditText EditTextartikelnummerbalk;
private Button knopconfirm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditTextregisternummerbalk = findViewById(R.id.registernummerbalk);
EditTextticketnummerbalk = findViewById(R.id.ticketnummerbalk);
EditTextartikelnummerbalk = findViewById(R.id.artikelnummerbalk);
knopconfirm = findViewById(R.id.knop);
EditTextregisternummerbalk.addTextChangedListener(invulTextWatcher);
EditTextticketnummerbalk.addTextChangedListener(invulTextWatcher);
EditTextartikelnummerbalk.addTextChangedListener(invulTextWatcher);
}
private TextWatcher invulTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String registernummerinput = EditTextregisternummerbalk.getText().toString().trim();
String ticketnummerinput = EditTextticketnummerbalk.getText().toString().trim();
String artikelnummerinput = EditTextartikelnummerbalk.getText().toString().trim();
knopconfirm.setEnabled(!registernummerinput.isEmpty() && !ticketnummerinput.isEmpty() &&! artikelnummerinput.isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
}
};
{
spinnermagazijn = findViewById(R.id.spinnermagazijn);
knop = findViewById(R.id.knop);
populatespinnermagazijn();
// Dit is het stukje voor de Knop afboeken waarmee je een melding genereerd, String aanpassen voor ander resultaat.
knop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, (R.string.succes), Toast.LENGTH_SHORT) .show();
}
});
}
// Dit gedeelte is voor de spinner.
private void populatespinnermagazijn() {
ArrayAdapter<String> magazijnenAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.steunpunten));
magazijnenAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnermagazijn.setAdapter(magazijnenAdapter);
}
}
And this is my logcat...
03-19 21:04:06.293 21151-21151/? E/libprocessgroup: failed to make and chown /acct/uid_10060: Read-only file system
03-19 21:04:06.293 21151-21151/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
03-19 21:04:06.293 21151-21151/? I/art: Not late-enabling -Xcheck:jni (already on)
03-19 21:04:06.313 21151-21161/? I/art: Debugger is no longer active
03-19 21:04:06.351 21151-21151/? D/AndroidRuntime: Shutting down VM
03-19 21:04:06.354 21151-21151/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.magazijnapp, PID: 21151
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.magazijnapp/com.example.magazijnapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:149)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
at android.content.Context.obtainStyledAttributes(Context.java:437)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.magazijnapp.MainActivity.<init>(MainActivity.java:73)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
03-19 21:04:07.996 21151-21151/? I/Process: Sending signal. PID: 21151 SIG: 9
There are two findViewById(R.id.knop);
remove this line:
knop = findViewById(R.id.knop);
and change :
knopconfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, (R.string.succes), Toast.LENGTH_SHORT) .show();
}
});
You are saying your app is crashing since you started using TextWatcher. So why don't you stop using it?
you can achieve the same thing without using TextWatcher by doing this.
knop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String registernummerinput = EditTextregisternummerbalk.getText().toString().trim();
String ticketnummerinput = EditTextticketnummerbalk.getText().toString().trim();
String artikelnummerinput = EditTextartikelnummerbalk.getText().toString().trim();
if((!registernummerinput.isEmpty() && !ticketnummerinput.isEmpty() &&! artikelnummerinput.isEmpty())) {
Toast.makeText(MainActivity.this, (R.string.succes), Toast.LENGTH_SHORT) .show();
}
}
});
you will not need any TextWathcer just modify the listner
I am new on android and working on my android app's login activity for which em using php mysql with volley library. But every time I run my app on emulator it shows the message Unfortunately, app has stopped. Here the login activity code is:
package com.example.u.locationtracker;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
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 com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText pass1, email1;
private Button login;
private TextView link_reg;
private ProgressBar loading;
private String URL_LOGIN= "http://192.168.1.1/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email1= (EditText) findViewById(R.id.etemail1);
pass1= (EditText) findViewById(R.id.etpassl);
loading= (ProgressBar) findViewById(R.id.loading1);
link_reg= (TextView) findViewById(R.id.signup);
login= (Button) findViewById(R.id.btnlogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail= email1.getText().toString().trim();
String mpass= pass1.getText().toString().trim();
if(!mEmail.isEmpty() || !mpass.isEmpty()){
Login(mEmail, mpass);
}else{
email1.setError("Please Enter Email...!");
pass1.setError("Please Enter Password...!");
}
}
});
link_reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent it= new Intent(MainActivity.this, Register.class);
startActivity(it);
}
});
}
private void Login(final String email, final String pass) {
loading.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
StringRequest stringRequest= new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject= new JSONObject(response);
String success= jsonObject.getString("Success");
JSONArray jsonArray= jsonObject.getJSONArray("Login");
if(success.equals("1")){
for (int i= 0; i < jsonArray.length(); i++){
JSONObject object= jsonArray.getJSONObject(i);
Toast t= Toast.makeText(MainActivity.this,
"Login Successful", Toast.LENGTH_LONG);
t.show();
loading.setVisibility(View.GONE);
}
}
}catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t1= Toast.makeText(MainActivity.this,
"Error" + e.toString(),
Toast.LENGTH_LONG);
t1.show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t2= Toast.makeText(MainActivity.this,
"Error" + error.toString(),
Toast.LENGTH_LONG);
t2.show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params= new HashMap<>();
params.put("Email", email);
params.put("Password", pass);
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
According to logcat the problem is:
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
here the php code:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$email= $_POST['email1'];
$pass= $_POST['pass1'];
require_once 'connect.php';
$select= "SELECT * FROM user_table WHERE Email= '$email' ";
$r= mysqli_query($conn, $select);
$result= array();
$result['login']= array();
if (mysqli_num_rows($r)=== 1) {
$row= mysqli_fetch_assoc($r);
if ( password_verify($pass, $row['Pass']) ) {
$index['Name']= $row['Name'];
$index['Email']= $row['Email'];
array_push($result['login'], $index);
$result['success']= "1";
$result['message']= "Success";
echo json_encode($result);
mysql_close($conn);
}else{
$result['success']= "0";
$result['message']= "Error";
echo json_encode($result);
mysql_close($conn);
}
}
}
?>
Here is the Logcat:
02-03 21:03:21.626 2006-2012/? E/jdwp: Failed writing handshake bytes: Broken pipe (-1 of 14)
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper', referenced from method android.support.v4.view.ViewCompat.addOnUnhandledKeyEventListener
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.dispatchApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.onApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.View$OnUnhandledKeyEventListener', referenced from method android.support.v4.view.ViewCompat.removeOnUnhandledKeyEventListener
02-03 21:03:21.836 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$1', referenced from method android.support.v4.view.ViewCompat.setOnApplyWindowInsetsListener
02-03 21:03:22.756 2006-2006/com.example.u.locationtracker E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
02-03 21:03:27.786 2006-2006/com.example.u.locationtracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.u.locationtracker, PID: 2006
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.u.locationtracker/com.example.u.locationtracker.MainActivity}: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2193)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f07005d a=-1 r=0x7f07005d}
at android.content.res.Resources.loadDrawable(Resources.java:2068)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.widget.ImageView.<init>(ImageView.java:129)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:72)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:68)
at android.support.v7.app.AppCompatViewInflater.createImageView(AppCompatViewInflater.java:182)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
at android.support.v7.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1266)
at android.support.v7.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1316)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:684)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
The problem seems to lie in this line:
setContentView(R.layout.activity_main);
Are you sure, the layout exists and doesn't have compile errors?
A full stacktrace would be more helpful
I am trying to permanently save some of the visited places by the user. So, when ever i run my project in android studio i get the error
"Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.util.ArrayList"
Here is my code:
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
static ArrayList<String> places= new ArrayList<>();
static ArrayList<LatLng> locations = new ArrayList<>();
static ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.lucifer.memorableplaces", Context.MODE_PRIVATE);
ArrayList<String> latitudes = new ArrayList<>();
ArrayList<String> longitudes = new ArrayList<>();
places.clear();
latitudes.clear();
longitudes.clear();
locations.clear();
try {
places = (ArrayList<String>)ObjectSerializer.deserialize(sharedPreferences.getString("places", ObjectSerializer.serialize(new ArrayList<String>())));
latitudes = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("latitudes", ObjectSerializer.serialize(new ArrayList<String>())));
longitudes = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("longitudes", ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
}
if (places.size() > 0 && latitudes.size() > 0 && longitudes.size() > 0) {
if (places.size() == latitudes.size() && latitudes.size() == longitudes.size()) {
for (int i = 0; i < latitudes.size(); i++) {
locations.add(new LatLng(Double.parseDouble(latitudes.get(i)), Double.parseDouble(longitudes.get(i))));
}
}
} else {
places.add("Add a new place...");
locations.add(new LatLng(0, 0));
}
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, places);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), MapsActivity.class);
intent.putExtra("placeNumber", i);
startActivity(intent);
}
});
}
}
and i get the following error:
Process: com.example.lucifer.memorableplaces, PID: 15910
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lucifer.memorableplaces/com.example.lucifer.memorableplaces.MainActivity}: java.lang.ClassCastException: java.lang.Class cannot be cast to java.util.ArrayList
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2378)
at android.app.ActivityThread.access$800(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5433)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.util.ArrayList
at com.example.lucifer.memorableplaces.MainActivity.onCreate(MainActivity.java:46)
at android.app.Activity.performCreate(Activity.java:5301)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2291)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2378)
at android.app.ActivityThread.access$800(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5433)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
The error is at
places = (ArrayList)ObjectSerializer.deserialize(sharedPreferences.getString("places", ObjectSerializer.serialize(new ArrayList())));
I finally got the answer, the error was caused because i was casting a class to arrayList. so i just changed my class to arrayList first then i casted it back to arrayList which solved my problem.
This way. Here i coded MainActivity.class
sharedPreferences.edit().putString("places",ObjectSerializer.serialize(MainActivity.class)).apply();
Whereas it has to be MainActivity.places in following Way
sharedPreferences.edit().putString("places",ObjectSerializer.serialize(MainActivity.places)).apply();
So, here i was actually casting a class to arrayList which gave me this error. Hope any beginner will prevent this mistake from this Question.
Thanks You All...
Errors and Chat Activity Dialog looks like this.
04-09 09:03:23.509 2722-2722/com.pz.mediatonmessanger E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.pz.mediatonmessanger, PID: 2722
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.pz.mediatonmessanger/com.pz.mediatonmessanger.ChatDialogActivity}: java.lang.InstantiationException: class com.pz.mediatonmessanger.ChatDialogActivity has no zero argument constructor
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.InstantiationException: class com.pz.mediatonmessanger.ChatDialogActivity has no zero argument constructor
at java.lang.Class.newInstance(Class.java:1563)
at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NoSuchMethodException: <init> []
at java.lang.Class.getConstructor(Class.java:531)
at java.lang.Class.getDeclaredConstructor(Class.java:510)
at java.lang.Class.newInstance(Class.java:1561)
at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Code
package com.pz.mediatonmessanger;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import com.pz.mediatonmessanger.Adapter.ChatDialogsAdapter;
import com.quickblox.auth.QBAuth;
import com.quickblox.auth.session.BaseService;
import com.quickblox.auth.session.QBSession;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.QBRestChatService;
import com.quickblox.chat.model.QBChatDialog;
import com.quickblox.core.QBEntityCallback;
import com.quickblox.core.exception.BaseServiceException;
import com.quickblox.core.exception.QBResponseException;
import com.quickblox.core.request.QBRequestBuilder;
import com.quickblox.core.request.QBRequestGetBuilder;
import com.quickblox.users.model.QBUser;
import java.util.ArrayList;
public class ChatDialogActivity extends AppCompatActivity {
FloatingActionButton floatingActionButton;
ListView lstChatDialogs;
public ChatDialogActivity(FloatingActionButton floatingActionButton) {
this.floatingActionButton = floatingActionButton;
}
public ChatDialogActivity(ListView lstChatDialogs) {
this.lstChatDialogs = lstChatDialogs;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_dialog);
createSessionForChat();
lstChatDialogs = (ListView)findViewById(R.id.lstChatDialogs);
loadChatDialogs();
floatingActionButton = (FloatingActionButton) findViewById(R.id.chatdialog_adduser);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChatDialogActivity.this, ListUsersActivity.class );
startActivity(intent);
}
});
}
private void loadChatDialogs() {
QBRequestGetBuilder requestBuilder = new QBRequestGetBuilder();
requestBuilder.setLimit(100);
QBRestChatService.getChatDialogs(null,requestBuilder).performAsync(new QBEntityCallback<ArrayList<QBChatDialog>>() {
#Override
public void onSuccess(ArrayList<QBChatDialog> qbChatDialogs, Bundle bundle) {
//Kod
ChatDialogsAdapter adapter = new ChatDialogsAdapter(getBaseContext(),qbChatDialogs);
lstChatDialogs.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onError(QBResponseException e) {
Log.e("Błąd",e.getMessage());
}
});
}
private void createSessionForChat() {
final ProgressDialog mDialog = new ProgressDialog(ChatDialogActivity.this);
mDialog.setMessage("Ładowanie...");
mDialog.setCanceledOnTouchOutside(false);
mDialog.show();
String user,password;
user = getIntent().getStringExtra("user");
password = getIntent().getStringExtra("password");
final QBUser qbUser = new QBUser(user,password);
QBAuth.createSession(qbUser).performAsync(new QBEntityCallback<QBSession>() {
#Override
public void onSuccess(QBSession qbSession, Bundle bundle) {
qbUser.setId(qbSession.getUserId());
try {
qbUser.setPassword(BaseService.getBaseService().getToken());
} catch (BaseServiceException e) {
e.printStackTrace();
}
QBChatService.getInstance().login(qbUser, new QBEntityCallback() {
#Override
public void onSuccess(Object o, Bundle bundle) {
mDialog.dismiss();
}
#Override
public void onError(QBResponseException e) {
Log.e("Błąd",""+e.getMessage());
}
});
}
#Override
public void onError(QBResponseException e) {
}
});
}
}
Activities don't have a constructor in Android, you can't create them as you do with other classes. They are instantiated by the system, all you need to do is to start them with context.startActivity(intent).
Remove all the constructors from this Activity and get a reference to the views with findViewById and you should be fine
I have this activity - including the needed code in order to load the admob banner ads.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.gs.britishjokes.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class AllJokes extends Activity {
public static ArrayAdapter<String> adapter;
public static ListView listView;
private AdView adView;
/* Your ad unit id. Replace with your actual ad unit id. */
private static final String AD_UNIT_ID = "ca-app-pub-codehere/code";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_jokes);
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(AD_UNIT_ID);
// Add the AdView to the view hierarchy. The view will have no size
// until the ad is loaded.
ListView layout = (ListView) findViewById(R.id.allJokesList);
layout.addView(adView);
// Create an ad request. Check logcat output for the hashed device ID to
// get test ads on a physical device.
AdRequest adRequest = new AdRequest.Builder()
// .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
// .addTestDevice("INSERT_YOUR_HASHED_DEVICE_ID_HERE")
.build();
// Start loading the ad in the background.
adView.loadAd(adRequest);
final GlobalsHolder globals = (GlobalsHolder)getApplication();
// if(globals.isLoaded == false){ SETJOKESNAMELIST MAI SE POLZVA OT DRUGO ACTIVITY!!!! ZATOVA IZLIZA PRAZNO SLED PROVERKATA!
new loadJson().execute();
// }
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
adapter.clear();
adapter.addAll(globals.getMyStringArray());
listView = (ListView) findViewById(R.id.allJokesList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
globals.setClickedJokeName((String) ((TextView) view).getText());
openJokeBody(view);
globals.setClickedPosition(position);
// When clicked, shows a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
#Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
/** Called before the activity is destroyed. */
#Override
public void onDestroy() {
// Destroy the AdView.
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.all_jokes, menu);
return true;
}
public class loadJson extends AsyncTask<Void, Integer, String[]>{
private ProgressDialog Dialog = new ProgressDialog(AllJokes.this);
#Override
protected void onPreExecute()
{
Dialog.setMessage("Fetching the latest jokes!");
Dialog.show();
}
#Override
protected String[] doInBackground(Void... params) {
/*Getting the joke names JSON string response from the server*/
URL u;
StringBuffer buffer = new StringBuffer();
StringBuffer buffer2 = new StringBuffer();
try {
u = new URL("https://site.com/android/Jokes/showJokes.php?JokeCat=allJokes");
URLConnection conn = u.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
buffer.append(inputLine);
in.close();
}catch(Exception e){
e.printStackTrace();
}
try {
u = new URL("https://site.com/android/Jokes/showJokesBody.php?JokeCat=allJokes");
URLConnection conn = u.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
buffer2.append(inputLine);
in.close();
}catch(Exception e){
e.printStackTrace();
}
// return buffer.toString(); ako se naloji da vurna - da pogledna tva return4e
return new String[]{buffer.toString(), buffer2.toString()};
}
#SuppressLint("NewApi")
protected void onPostExecute(String[] buffer) {
final GlobalsHolder globals = (GlobalsHolder)getApplication();
JSONArray jsonArray = new JSONArray();
JSONArray jsonArray1 = new JSONArray();
try {
jsonArray = new JSONArray(buffer[0]);
jsonArray1 = new JSONArray(buffer[1]);
} catch (JSONException e) {
e.printStackTrace();
}
/*Looping trough the results and adding them to a list*/
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list1 = new ArrayList<String>();
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
try {
list.add(jsonArray.get(i).toString());
globals.setJokeNamesList(list);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
if (jsonArray != null) {
int len = jsonArray1.length();
for (int i=0;i<len;i++){
try {
list1.add(jsonArray1.get(i).toString());
globals.setList(list1);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
/* Redrwawing the view */
adapter.clear();
adapter.addAll(list);
Dialog.dismiss();
globals.setLoaded(true);
}
}
/*This method opens the new activity - TopJokesBody when a joke name from the list is clicked*/
public void openJokeBody(View view) {
Intent intent = new Intent(this, AllJokesBody.class);
startActivity(intent);
}
}
It is my 1st try and I already stucked. Logcat is throwing tons of exceptions and to be honest I can't understand what I'm doing wrong.
Here the exceptions are:
03-29 13:55:37.713: E/AndroidRuntime(1750): FATAL EXCEPTION: main
03-29 13:55:37.713: E/AndroidRuntime(1750): Process: com.gs.britishjokes, PID: 1750
03-29 13:55:37.713: E/AndroidRuntime(1750): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gs.britishjokes/com.gelasoft.britishjokes.AllJokes}: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.os.Handler.dispatchMessage(Handler.java:102)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.os.Looper.loop(Looper.java:136)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-29 13:55:37.713: E/AndroidRuntime(1750): at java.lang.reflect.Method.invokeNative(Native Method)
03-29 13:55:37.713: E/AndroidRuntime(1750): at java.lang.reflect.Method.invoke(Method.java:515)
03-29 13:55:37.713: E/AndroidRuntime(1750): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-29 13:55:37.713: E/AndroidRuntime(1750): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-29 13:55:37.713: E/AndroidRuntime(1750): at dalvik.system.NativeStart.main(Native Method)
03-29 13:55:37.713: E/AndroidRuntime(1750): Caused by: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.widget.AdapterView.addView(AdapterView.java:452)
03-29 13:55:37.713: E/AndroidRuntime(1750): at com.gelasoft.britishjokes.AllJokes.onCreate(AllJokes.java:55)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.Activity.performCreate(Activity.java:5231)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-29 13:55:37.713: E/AndroidRuntime(1750): ... 11 more
I'm sure that I miss something inside of the xml layout file, but I'm not able to spot it as a total beginner.
Ps. here the layout is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".AllJokes" >
<ListView
android:id="#+id/allJokesList"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</RelativeLayout>
Should I declare something in it? Please, give me a clue!
Caused by: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
you cant add a view to adapterview
your issue is with
ListView layout = (ListView) findViewById(R.id.allJokesList);
layout.addView(adView);
You need to add the adView inside the adapter
http://googleadsdeveloper.blogspot.co.il/2012/03/embedding-admob-ads-within-listview-on.html
Don't try to add an AdView as an element in a ListView. It is a recipe for pain as it will be entirely different to your other items with different needs.
Add it as it's own element either above or below your ListView.
Instead create a LinearLayout either above or below your ListView
<LinearLayout android:id="#+id/adViewContainer
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
and then change this part of your onCreate to
// Add the AdView to the view hierarchy. The view will have no size
// until the ad is loaded.
final ViewGroup adViewContainer = (ViewGroup) findViewById(R.id.adViewContainer);
adViewContainer.addView(adView);