Adding entries to a list dynamically
<p>I am invoking the native camera using intent to capture images and in the activity result i am trying to provide a caption for the image captured and adding it to a list, but i am not successful in doing so i get an error when i add the item to the list. From the device the application force closes and am not able to figure out the error. Could someone kindly suggest me the correct way of adding the element to the List. Should it be added to the adapter or the underlying ArrayList? Kindly help me with this.</p>

<p>My code is as below:</p>

<pre><code>public class AttachmentsActivity extends ListActivity {

private AttachmentListAdapter m_adapter;
private ArrayList&lt;MediaData&gt; m_orders = null;
StringBuffer nameBuffer;
private String captureDateTime;
private Uri uri;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    m_orders = new ArrayList&lt;MediaData&gt;();
    Enumeration&lt;MediaData&gt; enumeration = DashboardManager.getInstance()
            .getAttachmentList().elements();
    while (enumeration.hasMoreElements()) {
        m_orders.add((MediaData) enumeration.nextElement());
    }

    this.m_adapter = new AttachmentListAdapter(this,
            android.R.layout.simple_list_item_1, m_orders);
    setListAdapter(this.m_adapter);
    this.m_adapter.notifyDataSetChanged();
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
    menu.removeGroup(1);
    if (DashboardManager.getInstance().isEnableCamera()) {
        menu.add(1, 1, Menu.NONE, "Camera");
    }
    if (DashboardManager.getInstance().isEnableAudio()) {
        menu.add(1, 2, Menu.NONE, "Audio");
    }

    return true;
}

private class AttachmentListAdapter extends ArrayAdapter&lt;MediaData&gt; {

    private ArrayList&lt;MediaData&gt; items;
    private LayoutInflater mInflater;
    private Bitmap high;
    private Bitmap medium;
    private Bitmap low;
    private LinearLayout linearLayout;
    private TextView[] textViews;
    private Context context;
    private Vector tableHeaders;
    private int width;
    private StringBuffer firstLine;



    public AttachmentListAdapter(Context context, int textViewResourceId,
            ArrayList&lt;MediaData&gt; items) {
        super(context, textViewResourceId, items);
        this.context = context;
        System.out.println("Inside NotificationListAdapter");
        System.out.println(items);
        this.items = items;
        firstLine = new StringBuffer();
        mInflater = LayoutInflater.from(context);
        Display display = getWindowManager().getDefaultDisplay();

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        MediaData mediaData = items.get(position);
        ViewHolder holder = null;
        if (mediaData != null) {
            if (convertView == null) {
                holder = new ViewHolder();
                // holder.content = (TextView) mInflater.inflate(
                // R.layout.column, null);
                holder.content = new TextView(context);
                holder.content.setGravity(Gravity.CENTER_VERTICAL);
                holder.content.setHeight(25);
                convertView = mInflater.inflate(R.layout.table_row, null);
                linearLayout = (LinearLayout) convertView
                        .findViewById(R.id.linearLayout);

                linearLayout.addView(holder.content);

            }
            firstLine.delete(0, firstLine.length());
            firstLine.append(mediaData.getType()).append(" ")
                    .append(mediaData.toString());

            holder.content.setText(firstLine.toString());
        }

        return linearLayout;
    }

}

static class ViewHolder {
    TextView content;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    switch (item.getItemId()) {

    case 1:
        nameBuffer = new StringBuffer();
        if (DashboardManager.getInstance().getWaterMarkingText().length() &gt; 0) {
            nameBuffer.append(
                    DashboardManager.getInstance().getWaterMarkingText())
                    .append("_");
        }

        captureDateTime = Calander.getSubmitDateTime(new Date());
        nameBuffer
                .append(captureDateTime)
                .append("_")
                .append(MobileBaseService.getInstance()
                        .getApplicationUser().getUserId()).append(".jpg");

        String dirString = "/sdcard/pravaa/";
        File dir = new File(dirString);
        if(!dir.exists()) dir.mkdir();
        File attachment=new File(dirString+nameBuffer.toString());
        uri=Uri.fromFile(attachment);
        System.out.println("URI:" + attachment.toURI());
        int resultCode = 1337;

        startActivityForResult(AttachmentUtility.getCameraIntent(uri),
            resultCode);


    }
    return true;
}



protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
        case 1337:

                     // TODO Auto-generated method stub String
                     String dirString="/sdcard/pravaa/"; //Toast

                      File attachment=new File(dirString+nameBuffer.toString());


                      if(attachment.exists()){ 
                          try { 
                      FileInputStream fis;
                      fis = new FileInputStream(attachment);
                      ByteArrayOutputStream baos = new ByteArrayOutputStream();

                      Bitmap bi = BitmapFactory.decodeStream(fis);
                      bi.compress(CompressFormat.JPEG, 100, baos);
                      byte[]attData = baos.toByteArray();
                      fis.close();
                      if (attData.length&gt;0) {
                                MediaData mediaData = new MediaData();
                                mediaData.setAttachmentUri(uri);
                                mediaData.setType(ApplicationStore.MEDIA_TYPE_IMAGE);
                                mediaData.setData(attData);
                                mediaData.setNewAttachment(true);
                                mediaData.setNote("");
                                mediaData.setTransactionId(MobileBaseService.getInstance().getNextTransactionId());
                                mediaData.setCaptureDataTime(captureDateTime);
                                mediaData.setCaption(mediaData.getCaptureDataTime() + "_" + MobileBaseService.getInstance().getApplicationUser().getUserId());
                                mediaData.setNumber(nameBuffer.toString());

                                if (DashboardManager.getInstance().isEnableGps() &amp;&amp; ApplicationManager.getInstance().isGpsEnabled()) {
                                    mediaData.setGpsEnabled(true);
                                    Location location= ApplicationManager.getInstance().getLocation();

                                    if (location != null) {

                                        mediaData.getGpsData().setLattitude(location.getLatitude());
                                        mediaData.getGpsData().setLongitude(location.getLongitude());
                                        mediaData.getGpsData().setAltidude(location.getAltitude());
                                        mediaData.getGpsData().setAccuracy("Y");
                                        mediaData.getGpsData().setDateTime(Calander.getSubmitDateTime(new Date()));
                                    } else {
                                     //   ApplicationManager.getInstance().Log(Level.TRACE, "Could not obtain GPS for Attachment " + mediaData.getNumber());
                                        mediaData.getGpsData().setLattitude(0);
                                        mediaData.getGpsData().setLongitude(0);
                                        mediaData.getGpsData().setAltidude(0);
                                        mediaData.getGpsData().setAccuracy("N");
                                        mediaData.getGpsData().setDateTime("");
                                    }
                                } else {
                                    mediaData.getGpsData().setLattitude(0);
                                    mediaData.getGpsData().setLongitude(0);
                                    mediaData.getGpsData().setAltidude(0);
                                    mediaData.getGpsData().setAccuracy("N");
                                    mediaData.getGpsData().setDateTime(Calander.getSubmitDateTime(new Date()));
                                }
                                    **//Commenting this line of code does not cause the crash**
                                m_adapter.add(mediaData);


                      }
                      } catch (FileNotFoundException e) {
                     //e.printStackTrace();
                     } catch (IOException e) {

                    // TODO Auto-generated catch block
                    // e.printStackTrace();
                     }catch (Exception e) {

                     }
                     }
            break;
        }
    }
}
}
</code></pre>

<p>I get an error when the following gets called :
m_adapter.add(mediaData); (line no 149) and my stack trace is as below:</p>

<pre><code>E/AndroidRuntime( 1367): java.lang.NullPointerException
E/AndroidRuntime( 1367):        at com.pravaa.dashboard.ui.components.Attachment
sActivity$AttachmentListAdapter.getView(AttachmentsActivity.java:149)
E/AndroidRuntime( 1367):        at android.widget.AbsListView.obtainView(AbsList
View.java:1427)
E/AndroidRuntime( 1367):        at android.widget.ListView.makeAndAddView(ListVi
ew.java:1802)
E/AndroidRuntime( 1367):        at android.widget.ListView.fillSpecific(ListView
.java:1347)
E/AndroidRuntime( 1367):        at android.widget.ListView.layoutChildren(ListVi
ew.java:1633)
E/AndroidRuntime( 1367):        at android.widget.AbsListView.onLayout(AbsListVi
ew.java:1280)
E/AndroidRuntime( 1367):        at android.view.View.layout(View.java:7035)
E/AndroidRuntime( 1367):        at android.widget.FrameLayout.onLayout(FrameLayo
ut.java:333)
E/AndroidRuntime( 1367):        at android.view.View.layout(View.java:7035)
E/AndroidRuntime( 1367):        at android.widget.LinearLayout.setChildFrame(Lin
earLayout.java:1249)
E/AndroidRuntime( 1367):        at android.widget.LinearLayout.layoutVertical(Li
nearLayout.java:1125)
E/AndroidRuntime( 1367):        at android.widget.LinearLayout.onLayout(LinearLa
yout.java:1042)
E/AndroidRuntime( 1367):        at android.view.View.layout(View.java:7035)
E/AndroidRuntime( 1367):        at android.widget.FrameLayout.onLayout(FrameLayo
ut.java:333)
E/AndroidRuntime( 1367):        at android.view.View.layout(View.java:7035)
E/AndroidRuntime( 1367):        at android.view.ViewRoot.performTraversals(ViewR
oot.java:1045)
E/AndroidRuntime( 1367):        at android.view.ViewRoot.handleMessage(ViewRoot.
java:1727)
E/AndroidRuntime( 1367):        at android.os.Handler.dispatchMessage(Handler.ja
va:99)
E/AndroidRuntime( 1367):        at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime( 1367):        at android.app.ActivityThread.main(ActivityThrea
d.java:4633)
E/AndroidRuntime( 1367):        at java.lang.reflect.Method.invokeNative(Native
Method)
E/AndroidRuntime( 1367):        at java.lang.reflect.Method.invoke(Method.java:5
21)
E/AndroidRuntime( 1367):        at com.android.internal.os.ZygoteInit$MethodAndA
rgsCaller.run(ZygoteInit.java:858)
E/AndroidRuntime( 1367):        at com.android.internal.os.ZygoteInit.main(Zygot
eInit.java:616)
E/AndroidRuntime( 1367):        at dalvik.system.NativeStart.main(Native Method)
</code></pre>

<p>The error occurs at the following line <strong>holder.content.setText(firstLine.toString());</strong> in the <strong>getView()</strong> method of <strong>AttachmentListAdapter</strong>. 
Kindly help me with this. Thanks in advance.</p>
