2011-06-05 212 views
0

我使用意圖捕獲圖像並在活動結果中調用本地相機,試圖爲捕獲的圖像提供標題並將其添加到列表中,但我沒有成功做所以當我將項目添加到列表中時出現錯誤。應用程序從設備關閉,無法找出錯誤。有人可以向我建議將元素添加到列表的正確方法。它是否應該添加到適配器或底層ArrayList中?請幫助我。將條目動態添加到列表中

我的代碼如下:

public class AttachmentsActivity extends ListActivity { 

private AttachmentListAdapter m_adapter; 
private ArrayList<MediaData> 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<MediaData>(); 
    Enumeration<MediaData> 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<MediaData> { 

    private ArrayList<MediaData> 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<MediaData> 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() > 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>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() && 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; 
     } 
    } 
} 
} 

我得到的時候下面被調用的錯誤: m_adapter.add(mediaData); (無線149)和我的堆棧跟蹤是如下:

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) 

在下面的行會出現錯誤holder.content.setText(firstLine.toString());getView()方法AttachmentListAdapter。 請幫助我。提前致謝。

+0

你必須在這裏提供更多的細節。代碼和堆棧跟蹤將有所幫助。 – Haphazard 2011-06-05 13:20:51

+0

您好,我將發佈代碼,但從設備運行時無法獲取整個堆棧跟蹤。在模擬器上,當我調用相機並捕獲圖像時,我得到一個強制關閉錯誤。 – 2011-06-05 19:16:14

+0

命令提示符中的'adb logcat'會給你完整的路徑。 – Haphazard 2011-06-05 21:26:44

回答

1

如果convertView不是null,則不會爲holder賦值。要正確使用這個「持有者」技術,將持有者保存在convertView(作爲標籤)中,並在convertView不爲空的情況下檢索它(在this video中有很好的解釋,請看看它!)。

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); 
      convertView.setTag(holder); 
      linearLayout = (LinearLayout) convertView 
        .findViewById(R.id.linearLayout); 

      linearLayout.addView(holder.content); 

     } else { 
      holder = convertView.getTag(); 
     } 
     firstLine.delete(0, firstLine.length()); 
     firstLine.append(mediaData.getType()).append(" ") 
       .append(mediaData.toString()); 

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

也有其他一些奇怪的事情怎麼回事(例如,爲什麼linearLayout一個成員變量),你應該看看。

+0

Hello Stephan,非常感謝你爲我工作。我仍然沒有完全重構代碼,需要清理。當我動態地將值添加到適配器時,它只顯示最後添加的值,並且以前的條目丟失,同樣當我調試適配器的ArrayList時,只有一個條目。我錯過了什麼?請幫助我。提前致謝。 – 2011-06-07 11:09:47