Android: java.lang.nullPointerException at custom ListView adapter - android-listview

I'm trying to make a custom view for my ListView, but the app crash when try to open it. I read a lot of pages but don't find the solution. Please help me!
This is my custom Adapter:
public class AdaptadorCatalogo extends BaseAdapter {
protected Activity activity;
protected ArrayList<LineaCatalogo> items;
public AdaptadorCatalogo(Activity activity, ArrayList<LineaCatalogo> items) {
this.activity = activity;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position){
return 0;
}
#Override
public View getView(int position, View contentView, ViewGroup parent) {
View vi=contentView;
if(contentView == null) {
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.listitem_catalogo, null);
}
LineaCatalogo item = items.get(position);
TextView primeraLinea = (TextView) vi.findViewById(R.id.lblPrimeraLinea);
primeraLinea.setText(item.getPrimeraLinea());
TextView segundaLinea = (TextView) vi.findViewById(R.id.lblSegundaLinea);
segundaLinea.setText(item.getSegundaLinea());
TextView magnitud = (TextView) vi.findViewById(R.id.lblMagnitud);
magnitud.setText(item.getMagnitud());
return vi;
}
}
This is my xml:
<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"
tools:context=".listaSismos" >
<RelativeLayout
android:id="#+id/general"
style="#style/AppCentral"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="50dp" >
<TextView
android:id="#+id/titulo_catalogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="#string/esperando_info" />
<ListView
android:id="#+id/listaDatos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginBottom="50dp"
android:layout_marginTop="50dp"
android:layout_marginLeft="30dp" />
</RelativeLayout>
</RelativeLayout>
This is my Activity:
public class listaSismos extends Activity {
private TextView tituloCatalogo;
private ListView listaDatos;
private String opcion;
private String codigoUsuario;
private String latitud;
private String longitud;
private String idioma;
private int difHoraria;
private ArrayList<LineaCatalogo> Catalogo;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_sismos);
tituloCatalogo = (TextView)findViewById(R.id.titulo_catalogo);
listaDatos = (ListView)findViewById(R.id.listaDatos);
Bundle bundle = getIntent().getExtras();
opcion = bundle.getString("lista");
codigoUsuario = bundle.getString("codigoUsuario");
latitud = bundle.getString("latitud");
longitud = bundle.getString("longitud");
idioma = getResources().getConfiguration().locale.toString();
TimeZone defaultTZ = TimeZone.getDefault();
difHoraria = defaultTZ.getRawOffset() / 1000;
ListarCatalogo conexion = new ListarCatalogo();
conexion.execute();
}
#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;
}
private class ListarCatalogo extends AsyncTask<String,Integer,Boolean> {
private int contador;
protected Boolean doInBackground(String... params) {
boolean resul = true;
HttpClient httpClient = new DefaultHttpClient();
HttpGet del =
new HttpGet(my_app_server_url);
del.setHeader("content-type", "application/json");
try
{
HttpResponse resp = httpClient.execute(del);
String respStr = EntityUtils.toString(resp.getEntity());
JSONArray respJSON = new JSONArray(respStr);
ArrayList<LineaCatalogo> Catalogo = new ArrayList<LineaCatalogo>();
contador = respJSON.length();
for(int cont=0; cont<contador; cont++)
{
JSONObject obj = respJSON.getJSONObject(cont);
String tituloS = obj.getString("P");
String subtituloS = obj.getString("S");
String magnitudS = obj.getString("M");
Catalogo.add(new LineaCatalogo(tituloS, subtituloS, magnitudS));
}
}
catch(Exception ex)
{
resul = false;
}
return resul;
}
protected void onPostExecute(Boolean result) {
tituloCatalogo.setText(R.string.titulo_catalogo);
if (result)
{
//Rellenamos la lista con los resultados
AdaptadorCatalogo adaptador = new AdaptadorCatalogo(listaSismos.this, Catalogo);
listaDatos.setAdapter(adaptador);
tituloCatalogo.setText("OK");
} else {
tituloCatalogo.setText(R.string.no_datos);
}
}
}
}
If i comment the line "listaDatos.setAdapter(adaptador);", the app runs ok. If not, i get this LogCat:
12-06 09:34:32.443: W/dalvikvm(903): threadid=1: thread exiting with uncaught exception (group=0x41465700)
12-06 09:34:32.559: E/AndroidRuntime(903): FATAL EXCEPTION: main
12-06 09:34:32.559: E/AndroidRuntime(903): java.lang.NullPointerException
12-06 09:34:32.559: E/AndroidRuntime(903): at com.tapsistemas.avcanquake.AdaptadorCatalogo.getCount(AdaptadorCatalogo.java:23)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.widget.ListView.setAdapter(ListView.java:463)
12-06 09:34:32.559: E/AndroidRuntime(903): at com.tapsistemas.avcanquake.listaSismos$ListarCatalogo.onPostExecute(listaSismos.java:124)
12-06 09:34:32.559: E/AndroidRuntime(903): at com.tapsistemas.avcanquake.listaSismos$ListarCatalogo.onPostExecute(listaSismos.java:1)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.os.AsyncTask.finish(AsyncTask.java:631)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.os.Handler.dispatchMessage(Handler.java:99)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.os.Looper.loop(Looper.java:137)
12-06 09:34:32.559: E/AndroidRuntime(903): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-06 09:34:32.559: E/AndroidRuntime(903): at java.lang.reflect.Method.invokeNative(Native Method)
12-06 09:34:32.559: E/AndroidRuntime(903): at java.lang.reflect.Method.invoke(Method.java:525)
12-06 09:34:32.559: E/AndroidRuntime(903): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-06 09:34:32.559: E/AndroidRuntime(903): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-06 09:34:32.559: E/AndroidRuntime(903): at dalvik.system.NativeStart.main(Native Method)
I still working a week looking for the solution, but i can't do it. Please, help me. And sorry by my poor english, i'm spanish from Canary Islands.

Declare and initialize like
private ArrayList<LineaCatalogo> Catalogo= new ArrayList<LineaCatalogo>();
#Override
public void onCreate(Bundle savedInstanceState){
Remove
ArrayList<LineaCatalogo> Catalogo = new ArrayList<LineaCatalogo>();
// becomes local to doInbackground as it is declared and initialized there.
in doInbackground.
In your case Catalogo was null.

You redefine your list with
ArrayList<LineaCatalogo> Catalogo = new ArrayList<LineaCatalogo>();
in the doInBacground
use just
Catalogo = new ArrayList<LineaCatalogo>();

Related

Cannot play music using MusicService in Fragment

I have a fragment that gives me the listView of all songs that that I have stored on my phone. When I click on a particular song in my list, I should be able to play it using a MusicService.
This fragment (menu2_Fragment) is initialized in an ActionBarActivity when a particular drawer item is selected. See following code:
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch(position){
case 0:
objFragment = new menu1_Fragment();
getSupportActionBar().setTitle("Scan for Users");
break;
case 1:
objFragment = new menu2_Fragment();
getSupportActionBar().setTitle("Your Music");
// objFragment = new MyMusicFragment();
break;
case 2:
objFragment = new menu3_Fragment();
getSupportActionBar().setTitle("Popular Music");
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
This is the Fragment code:
package com.example.cs446.soundscope;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.MediaController;
import com.example.cs446.soundscope.Adapter.SongAdapter;
import com.example.cs446.soundscope.data.Song;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* Created by val on 27/02/15.
*/
public class menu2_Fragment extends Fragment implements MediaController.MediaPlayerControl{
View rootview;
private ArrayList<Song> songList;
private ListView songView;
private MusicService musicSrv;
private Intent playIntent;
private boolean musicBound=false;
private MusicController controller;
private boolean paused=false;
private boolean playbackPaused=false;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
rootview = inflater.inflate(R.layout.activity_main,container, false);
songView = (ListView)rootview.findViewById(R.id.song_list);
songList = new ArrayList<Song>();
getSongList();
//sort all of the songList by title
Collections.sort(songList, new Comparator<Song>() {
//function that does the sorting
#Override
public int compare(Song lhs, Song rhs) {
return lhs.getTitle().compareTo(rhs.getTitle());
}
});
SongAdapter songAdt = new SongAdapter(getActivity(),songList);
songView.setAdapter(songAdt);
setController();
//startActivity(new Intent(this, MainActivity.class));
return rootview;
}
//get the song information for your filesystem
public void getSongList(){
//use the contentResolver to retrieve the uri for the music file
//a cursor instance is created with the contentResolver
ContentResolver musicResolver = this.getActivity().getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
//store the songs into the song list array list
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
public void songPicked(View view){
musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
musicSrv.playSong();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
//set the controller up
private void setController(){
controller = new MusicController(getActivity());
controller.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
playNext();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
playPrev();
}
});
controller.setMediaPlayer(this);
controller.setAnchorView(getActivity().findViewById(R.id.song_list));
controller.setEnabled(true);
}
#Override
public void onStart() {
super.onStart();
if(playIntent==null){
playIntent = new Intent(getActivity(), MusicService.class);
this.getActivity().bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
this.getActivity().startService(playIntent);
}
}
#Override
public void onPause(){
super.onPause();
paused=true;
}
#Override
public void onResume(){
super.onResume();
if(paused){
setController();
paused=false;
}
}
#Override
public void onStop() {
controller.hide();
super.onStop();
}
//connect to the service
private ServiceConnection musicConnection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MusicBinder binder = (MusicService.MusicBinder)service;
//get service
musicSrv = binder.getService();
//pass list
musicSrv.setList(songList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
//play next
private void playNext(){
musicSrv.playNext();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
//play previous
private void playPrev(){
musicSrv.playPrev();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
#Override
public void onDestroy() {
this.getActivity().stopService(playIntent);
musicSrv=null;
super.onDestroy();
}
#Override
public void start() {
musicSrv.go();
}
#Override
public void pause() {
playbackPaused=true;
musicSrv.pausePlayer();
}
#Override
public int getDuration() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getDur();
else return 0;
}
#Override
public int getCurrentPosition() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getPosn();
else return 0;
}
#Override
public void seekTo(int pos) {
musicSrv.seek(pos);
}
#Override
public boolean isPlaying() {
if(musicSrv!=null && musicBound)
return musicSrv.isPng();
return false;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
}
When I click on an item in the ListView, instead of playing the song my app crashes and I receive the following error message:
03-02 00:46:29.142 6485-6485/com.example.cs446.soundscope E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.cs446.soundscope, PID: 6485
java.lang.IllegalStateException: Could not find a method songPicked(View) in the activity class com.example.cs446.soundscope.ListNearbyUsers for onClick handler on view class android.widget.LinearLayout
at android.view.View$1.onClick(View.java:3994)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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: songPicked [class android.view.View]
at java.lang.Class.getMethod(Class.java:664)
at java.lang.Class.getMethod(Class.java:643)
at android.view.View$1.onClick(View.java:3987)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            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)
The playing music functionality works fine when it's not implemented inside a Fragment, but instead implemented inside an Activity. Has anyone seen an error like this before?
It means that you didn't declare andoid:onClick="songPicked" in your fragment layout.
And I know you are coming from tutsplus :)

Null pointer exception customer adapter

good morning i tried to parse rss and show the result in custom listview but i had a problem with my custom adapter that i created to show a thumbail image with a textview i get usually null pointer excpetion in every execution in genymotion simulator.
this the code of the three files of code :
main activity
public class MainActivity extends Activity {
ArrayList<HashMap<String, String>> name;
ListView maListRSS;
Bitmap img;
ArrayList<News> News_data ;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
maListRSS = (ListView) findViewById(R.id.list);
name = new ArrayList<HashMap<String, String>>();
News_data = new ArrayList<News>();
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setMessage("جاري التحميل....");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.show();
}
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
URL url = null;
try {
url = new URL("http://ahsaber.org/?feed=rss2");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
org.w3c.dom.Document doc = null;
try {
doc = db.parse(new InputSource(url.openStream()));
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("title");
Element nameElement = (Element) nameList.item(0);
nameList = ((Node) nameElement).getChildNodes();
NodeList websiteList =fstElmnt.getElementsByTagName("link");
Element websiteElement = (Element) websiteList.item(0);
websiteList = ((Node) websiteElement).getChildNodes();
NodeList descriptionList =fstElmnt.getElementsByTagName("description");
Element descriptionElement = (Element) descriptionList.item(0);
descriptionList = ((Node) descriptionElement).getChildNodes();
NodeList encodedList =fstElmnt.getElementsByTagName("content:encoded");
Element EnocodeElement = (Element) encodedList.item(0);
encodedList = ((Node) EnocodeElement).getChildNodes();
int start =EnocodeElement.getTextContent().indexOf("http://ahsaber.org");
int end =EnocodeElement.getTextContent().indexOf(".jpg");
HashMap<String, String> map = new HashMap<String, String>();
map.put("title", ((Node) nameList.item(0)).getNodeValue());
map.put("tel", ((Node) websiteList.item(0)).getNodeValue());
map.put("des", ((Node) descriptionList.item(0)).getNodeValue());
if (end>start)
{
map.put("imageURL",EnocodeElement.getTextContent().substring(start,end)+".jpg");
System.out.println(EnocodeElement.getTextContent().substring(start,end));
try {
URL lien = new URL(EnocodeElement.getTextContent().substring(start,end)+".jpg");
HttpURLConnection connection = null;
connection = (HttpURLConnection) lien.openConnection();
InputStream is = null;
is = connection.getInputStream();
img = BitmapFactory.decodeStream(is);
News N=new News(img,((Node) nameList.item(0)).getNodeValue());
News_data.add(N);
name.add(map);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
protected void onPostExecute(Void result) {
mProgressDialog.dismiss();
NewsAdapter adapter = new NewsAdapter(MainActivity.this,
R.layout.listviewrow, News_data);
adapter.notifyDataSetChanged();
maListRSS.setAdapter(adapter);
}
};
task.execute((Void[]) null);
}
}
this the custom adapter class :
public class NewsAdapter extends ArrayAdapter<News> {
Context context;
int layoutResourceId;
ArrayList<News> data =new ArrayList<News>() ;
public NewsAdapter(Context asyncTask, int layoutResourceId, ArrayList<News> news_data) {
super(asyncTask, layoutResourceId, news_data);
this.layoutResourceId = layoutResourceId;
this.context = asyncTask;
for (int i=0;i<news_data.size();i++)
{
data.add(news_data.get(i));
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
NewsHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new NewsHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.newsimage);
holder.txtTitle = (TextView)row.findViewById(R.id.newstitle);
row.setTag(holder);
}
else
{
holder = (NewsHolder)row.getTag();
}
News N= data.get(position);
holder.txtTitle.setText(N.title);
holder.imgIcon.setImageBitmap(N.icon);
return row;
}
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
static class NewsHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
the news class :
public class News {
public Bitmap icon;
public String title;
public News() {
// TODO Auto-generated constructor stub
super();
}
public News(Bitmap icon, String title) {
super();
this.icon = icon;
this.title = title;
}
}
so this is the logcat :
01-08 10:02:11.584: E/AndroidRuntime(967): FATAL EXCEPTION: main
01-08 10:02:11.584: E/AndroidRuntime(967): java.lang.NullPointerException
01-08 10:02:11.584: E/AndroidRuntime(967): at com.example.albir.MainActivity$1.onPostExecute(MainActivity.java:139)
01-08 10:02:11.584: E/AndroidRuntime(967): at com.example.albir.MainActivity$1.onPostExecute(MainActivity.java:1)
01-08 10:02:11.584: E/AndroidRuntime(967): at android.os.AsyncTask.finish(AsyncTask.java:631)
01-08 10:02:11.584: E/AndroidRuntime(967): at android.os.AsyncTask.access$600(AsyncTask.java:177)
01-08 10:02:11.584: E/AndroidRuntime(967): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
01-08 10:02:11.584: E/AndroidRuntime(967): at android.os.Handler.dispatchMessage(Handler.java:99)
01-08 10:02:11.584: E/AndroidRuntime(967): at android.os.Looper.loop(Looper.java:137)
01-08 10:02:11.584: E/AndroidRuntime(967): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-08 10:02:11.584: E/AndroidRuntime(967): at java.lang.reflect.Method.invokeNative(Native Method)
01-08 10:02:11.584: E/AndroidRuntime(967): at java.lang.reflect.Method.invoke(Method.java:511)
01-08 10:02:11.584: E/AndroidRuntime(967): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-08 10:02:11.584: E/AndroidRuntime(967): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-08 10:02:11.584: E/AndroidRuntime(967): at dalvik.system.NativeStart.main(Native Method)

"java.lang.NullPointerException" Error when trying to insert data to sqlite (Android)

I face the error :
1566-1566/com.example.rom.romproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.rom.romproject, PID: 1566
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3823)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
            at android.view.View.performClick(View.java:4438)
            at android.view.View$PerformClick.run(View.java:18422)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            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: java.lang.NullPointerException
at com.example.rom.romproject.ContactView.contactFavorite(ContactView.java:37)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at android.view.View$1.onClick(View.java:3818)
            at android.view.View.performClick(View.java:4438)
            at android.view.View$PerformClick.run(View.java:18422)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            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)
This happens when im clicking on a button i created.
The button purpose is to insert Data into my sql table.
The SQL class :
public class sqlDatabaseAdapter
{
sqlHelper helper;
public sqlDatabaseAdapter(Context context)
{
helper = new sqlHelper(context);
}
public long insertData(String name, String phone)
{
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues content = new ContentValues();
content.put(sqlHelper.NAME, name);
content.put(sqlHelper.PHONE, phone);
return db.insert(helper.TABLE_NAME, null, content);
}
static class sqlHelper extends SQLiteOpenHelper
{
static final String DATABASE_NAME = "ContactDB";
static final String TABLE_NAME = "Favorites";
static final int DB_VERSION = 1;
static final String UID = "_id";
static final String NAME = "Name";
static final String PHONE = "Phone";
static final String CREATE_TABLE = "CREATE TABLE "+ TABLE_NAME +" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+PHONE+" VARCHAR(255));";
static final String DROP_TABLE = "DROP TABLE IF EXISTS"+TABLE_NAME;
private Context context;
public sqlHelper(Context context)
{
super(context, DATABASE_NAME, null, DB_VERSION);
this.context = context;
Message.Message(context, "Constructor Called");
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(CREATE_TABLE);
Message.Message(context, "onCreate Called");
} catch( SQLException e)
{
Message.Message(context, "" + e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
try {
db.execSQL(DROP_TABLE);
onCreate(db);
Message.Message(context, "OnUpgrade Called");
} catch(SQLException e)
{
Message.Message(context, "" + e);
}
}
}
}
Now, im not rly sure at the source of the problem , so i will post both of my activites.
Btw : the info im trying to insert to the SQL is a contact name and phone
(that i get from the main activity list view).
Main Activity ( List view of phone contacts ) :
public class MainActivity extends ListActivity {
ListView l;
Cursor cursor;
SimpleCursorAdapter listAdapter;
sqlDatabaseAdapter helper;
#Override
public int getSelectedItemPosition()
{
return super.getSelectedItemPosition();
}
#Override
public long getSelectedItemId()
{
return super.getSelectedItemId();
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
startManagingCursor(cursor);
String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID};
int[] to = {android.R.id.text1,android.R.id.text2};
listAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,cursor,from,to);
setListAdapter(listAdapter);
l = getListView();
l.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
helper = new sqlDatabaseAdapter(this);
helper.helper.getWritableDatabase();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
TextView _tempName= (TextView)v.findViewById(android.R.id.text1);
String _temp = _tempName.getText().toString();
TextView _tempPhone = (TextView)v.findViewById(android.R.id.text2);
String _temp2 = _tempPhone.getText().toString();
Intent intent = new Intent(this, ContactView.class);
intent.putExtra("contactName", _temp);
intent.putExtra("contactPhone", _temp2);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The second activity (where the button is ) :
public class ContactView extends ActionBarActivity {
Button _Call;
Button _Favorite;
FavoriteContact contact = new FavoriteContact();
sqlDatabaseAdapter helper;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_view);
_Call = (Button)findViewById(R.id.bCall);
_Favorite = (Button)findViewById(R.id.bFavorite);
contact.setName(getIntent().getExtras().getString("contactName"));
contact.setPhone(getIntent().getExtras().getString("contactPhone"));
setTitle(contact.getName());
}
public void contactFavorite(View view)
{
long id = 0L;
id = helper.insertData(contact.getName(), contact.getPhone());
/*
if( id < 0)
{
Message.Message(this, "Unsuccessful");
}
else
{
Message.Message(this, "Successfully inserted to favorite contacts ");
}
*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_contact_view, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Contact class i created and FavoriteContact class :
(favoritecontact extends Contact)
public class Contact
{
private String Name = null;
private String Phone = null;
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
public class FavoriteContact extends Contact
{
private Boolean isFavorite;
public Boolean getIsFavorite() {
return isFavorite;
}
public void setIsFavorite(Boolean isFavorite) {
this.isFavorite = isFavorite;
}
}
i think i gave everything i need...
sorry for my bad english and its my first time posting here so i dont rly know how it works :D
thanks for every bit of help .
The variable helper is never initialized in ContactView.

Google Glass Camera: setPreviewCallback

I have an operating android app that utilizes preview callbacks, to process the image after every frame from the preview (the preview is paused for a minute while the calculations take place). It works great! But, now I am trying to get Google Glass to do the same thing: activate Preview, activate preview callback, activating the calculations.
This issue likely has to do with how Camera is defined:
Camera mCamera = null;
but, I cannot define it as Camera.open(); with Google Glass because it fails. Thus when i get to defining the callback, I'm told it may produce a NullPointerException, and indeed I get the following error string:
Process: com.ead.glasscam.app, PID: 14231
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ead.glasscam.app/com.ead.glasscam.app.MainActivity}:
java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2235)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2285)
at android.app.ActivityThread.access$800(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1236)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5061)
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:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.ead.glasscam.app.MainActivity.onCreate(MainActivity.java:100)
at android.app.Activity.performCreate(Activity.java:5236)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1089)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2285)
            at android.app.ActivityThread.access$800(ActivityThread.java:138)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1236)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:149)
            at android.app.ActivityThread.main(ActivityThread.java:5061)
            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:794)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
            at dalvik.system.NativeStart.main(Native Method)
So, the code:
// Attach a callback for preview
mPreviewCallback camCallback = new mPreviewCallback();
mCamera.setPreviewCallback(camCallback);
What is mPreviewCallback?:
public class mPreviewCallback implements Camera.PreviewCallback {
public void onPreviewFrame(byte[] data, final Camera camera){
Log.i("CAMERA", "Triggered Preview Frame");
}
}
I really don't understand how to do this simple process on Android, with Google Glass. Thank you for reading.
Checkout this example from jaredsburrows, it uses the camera preview on Glass and I used it in a project once (It Works! ;) )
https://github.com/jaredsburrows/OpenQuartz/tree/master/example-apps/OG_CameraApp
public class CameraView extends SurfaceView implements SurfaceHolder.Callback
{
private SurfaceHolder surfaceHolder = null;
private Camera camera = null;
#SuppressWarnings("deprecation")
public CameraView(Context context)
{
super(context);
surfaceHolder = this.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
/*
* (non-Javadoc)
* #see android.view.SurfaceHolder.Callback#surfaceCreated(android.view.SurfaceHolder)
*/
#Override
public void surfaceCreated(SurfaceHolder holder)
{
camera = Camera.open();
// Set the Hotfix for Google Glass
this.setCameraParameters(camera);
// Show the Camera display
try
{
camera.setPreviewDisplay(holder);
}
catch (Exception e)
{
this.releaseCamera();
}
}
/*
* (non-Javadoc)
* #see android.view.SurfaceHolder.Callback#surfaceChanged(android.view.SurfaceHolder, int, int, int)
*/
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
// Start the preview for surfaceChanged
if (camera != null)
{
camera.startPreview();
}
}
/*
* (non-Javadoc)
* #see android.view.SurfaceHolder.Callback#surfaceDestroyed(android.view.SurfaceHolder)
*/
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
// Do not hold the camera during surfaceDestroyed - view should be gone
this.releaseCamera();
}
/**
* Important HotFix for Google Glass (post-XE11) update
* #param camera Object
*/
public void setCameraParameters(Camera camera)
{
if (camera != null)
{
Parameters parameters = camera.getParameters();
parameters.setPreviewFpsRange(30000, 30000);
camera.setParameters(parameters);
}
}
/**
* Release the camera from use
*/
public void releaseCamera()
{
if (camera != null)
{
camera.release();
camera = null;
}
}
}

Problems with XmlPullParser code inside an AsyncTask (Activated By Button Click)

SO I have a program that I have been working on for a while. However, I am stuck on method that uses XmlPullParser, the method is called getAllXml(). It is inside of the doInBackGround() method of an AsyncTask. The AsyncTask is a subclass of an Activity called FormActivity. When I run the code.
Here is what the code is supposed to do. After the user selects "CloverField" from a previous activity. An xml file called cloverfield_in.xml is called by setContentView(). The user then presses a button on this same xml file. Clicking this button executes the AsyncTask called MadLIbAsyncTask. Within this AsyncTask this are only two methods, the doInBackground() and the onPostExecute(). (I don't know if I need onPreExecute()...within which I would have have a progress bar....but without this method I figure the program shouldn't crash the way it does).
Within the doInBackground() method, I am calling the method called getAllXml(). This method uses XmlPullParser to search through the current xml (cloverfield_in.xml) and capture text from a single TextView. The code for getAllXml() is as follows.
public void getAllXml() throws XmlPullParserException, IOException{
Activity activity = this;
Resources res = activity.getResources();
XmlResourceParser xpp = res.getXml(R.layout.cloverfield_in);
int eventtype = xpp.getEventType();
while (eventtype != XmlPullParser.END_DOCUMENT){
if (eventtype == XmlPullParser.START_DOCUMENT){
}
else if (eventtype == XmlPullParser.START_TAG){
if (xpp.getName() == "TextView"){
while (eventtype != XmlPullParser.END_TAG){
if (eventtype == XmlPullParser.TEXT){
stringViews[0] = xpp.getText();
}else {}
eventtype = xpp.next();
}
}else {}
}
else if (eventtype == XmlPullParser.END_TAG){
}
else if (eventtype == XmlPullParser.TEXT){
}
eventtype = xpp.next();
}
}
When in the process of debugging, my program often returns a NullPointerException or a RunTimeException. I believe within this code is where the problem resides. I tested the AsyncTask without the existence of the getAllXml() method and everything works fine. Eventually the program is supposed to take the text gathered from the cloverfield_in.xml file and display it in a new file called cloverfield_out.xml.
For a complete review of everything, here is the entire code for FormActivity.class.
package com.muirconsult.mymadlibs;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Layout;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
public class FormActivity extends Activity{
String [] textFields;
String Choice;
int thisLayout;
View thatLayout ;
String[] stringViews;
ViewGroup anskey;
Activity activity = this;
String test;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent objIntent = getIntent();
Choice = objIntent.getStringExtra("selection");
if (Choice.equals("Cloverfield")) {
setContentView(R.layout.cloverfield_in);
thisLayout = (R.layout.cloverfield_in);
thatLayout = (View)findViewById(R.layout.cloverfield_out);
}
if (Choice.equals("Fargo")) {
setContentView(R.layout.fargo_in);
}
if(Choice.equals("Ying Yang In This Thang (Ying Yang Twins)")){
setContentView(R.layout.ying_yang_twins_in_this_thang_in);
}
}
public void getAllXml() throws XmlPullParserException, IOException{
Activity activity = this;
Resources res = activity.getResources();
XmlResourceParser xpp = res.getXml(R.layout.cloverfield_in);
int eventtype = xpp.getEventType();
while (eventtype != XmlPullParser.END_DOCUMENT){
if (eventtype == XmlPullParser.START_DOCUMENT){
}
else if (eventtype == XmlPullParser.START_TAG){
if (xpp.getName() == "TextView"){
while (eventtype != XmlPullParser.END_TAG){
if (eventtype == XmlPullParser.TEXT){
stringViews[0] = xpp.getText();
}else {}
eventtype = xpp.next();
}
}else {}
}
else if (eventtype == XmlPullParser.END_TAG){
}
else if (eventtype == XmlPullParser.TEXT){
}
eventtype = xpp.next();
}
}
class MadLibAsyncTask extends AsyncTask<Void, Void, Void>{
String testString;
int thisLayout;
protected Void doInBackground(Void... params) {
try{
getAllXml();
}catch (XmlPullParserException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute (Void result){
String str = "let's go to the park";
String newstr;
setContentView(R.layout.cloverfield_out);
TextView outview = (TextView)findViewById(R.id.outview);
str = (String) outview.getText();
newstr = str.replaceFirst("film",stringViews[0]);
outview.setText(newstr);
}
}
public void onClick(View view) {
MadLibAsyncTask mad = new MadLibAsyncTask();
mad.execute();
}
}
Also, most importantly...the logcat looks as such:
08-10 23:04:50.064: W/dalvikvm(1415): threadid=1: thread exiting with uncaught exception >>> (group=0x40a71930)
08-10 23:04:50.145: E/AndroidRuntime(1415): FATAL EXCEPTION: main
08-10 23:04:50.145: E/AndroidRuntime(1415): java.lang.NullPointerException
08-10 23:04:50.145: E/AndroidRuntime(1415): at java.util.regex.Matcher.appendEvaluated>(Matcher.java:130)
08-10 23:04:50.145: E/AndroidRuntime(1415): at java.util.regex.Matcher.appendReplacement(Matcher.java:110)
08-10 23:04:50.145: E/AndroidRuntime(1415): at java.util.regex.Matcher.replaceFirst(Matcher.java:299)
08-10 23:04:50.145: E/AndroidRuntime(1415): at java.lang.String.replaceFirst(String.java:1793)
08-10 23:04:50.145: E/AndroidRuntime(1415): at com.muirconsult.mymadlibs.FormActivity$MadLibAsyncTask.onPostExecute(FormActivity.java:116)
08-10 23:04:50.145: E/AndroidRuntime(1415): at com.muirconsult.mymadlibs.FormActivity$MadLibAsyncTask.onPostExecute(FormActivity.java:1)
08-10 23:04:50.145: E/AndroidRuntime(1415): at android.os.AsyncTask.finish(AsyncTask.java:631)
08-10 23:04:50.145: E/AndroidRuntime(1415): at android.os.AsyncTask.access$600>\ (AsyncTask.java:177)
08-10 23:04:50.145: E/AndroidRuntime(1415): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
08-10 23:04:50.145: E/AndroidRuntime(1415): at android.os.Handler.dispatchMessage(Handler.java:99)
08-10 23:04:50.145: E/AndroidRuntime(1415): at android.os.Looper.loop(Looper.java:137)
08-10 23:04:50.145: E/AndroidRuntime(1415): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-10 23:04:50.145: E/AndroidRuntime(1415): at java.lang.reflect.Method.invokeNative(Native Method)
08-10 23:04:50.145: E/AndroidRuntime(1415): at java.lang.reflect.Method.invoke(Method.java:511)
08-10 23:04:50.145: E/AndroidRuntime(1415): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-10 23:04:50.145: E/AndroidRuntime(1415): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-10 23:04:50.145: E/AndroidRuntime(1415): at dalvik.system.NativeStart.main(Native Method)