2016-03-29 34 views
2

Ich bin neu bei Android, ich habe meine Tab Activity-Aktivität mit Hilfe eines Freundes und mehrerer Tutorials implementiert, die ich online gefunden habe. Wenn ich jedoch versuche, zur nächsten Registerkarte zu navigieren, wird ein Fehler ausgelöst. Ich habe es durchgesehen und kann nicht verstehen, was hier vorgeht oder was ich falsch mache.App stürzt beim Navigieren zu Fragment ab

Dies ist der Fehler in meinem Android-Monitor angezeigt:

03-29 19:20:55.958 1544-1544/com.xxxxxx.eventmanager E/Trace: error opening trace file: No such file or directory (2) 
03-29 19:36:25.011 1544-19421/com.xxxxxx.eventmanager E/CursorWindow: Failed to read row 0, column -1 from a CursorWindow which has 199 rows, 18 columns. 
03-29 19:36:25.031 1544-19421/com.xxxxxx.eventmanager E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #3 
    java.lang.RuntimeException: An error occured while executing doInBackground() 
     at android.os.AsyncTask$3.done(AsyncTask.java:299) 
     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 
     at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 
     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 
     at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
     at java.lang.Thread.run(Thread.java:856) 
    Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it. 
     at android.database.CursorWindow.nativeGetString(Native Method) 
     at android.database.CursorWindow.getString(CursorWindow.java:434) 
     at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51) 
     at com.xxxxxx.eventmanager.models.InvoiceModel.get(InvoiceModel.java:129) 
     at com.xxxxxx.eventmanager.fragments.EventPurchasesFragment$InvoiceAsync.doInBackground(EventPurchasesFragment.java:132) 
     at com.xxxxxx.eventmanager.fragments.EventPurchasesFragment$InvoiceAsync.doInBackground(EventPurchasesFragment.java:106) 
     at android.os.AsyncTask$2.call(AsyncTask.java:287) 
     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 
     at java.util.concurrent.FutureTask.run(FutureTask.java:137)  
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)  
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)  
     at java.lang.Thread.run(Thread.java:856)  
03-29 19:36:25.981 1544-1544/com.xxxxxx.eventmanager E/WindowManager: Activity com.xxxxxx.eventmanager.EventDetailsActivity has leaked window com.android.internal.policy.impl.P[email protected] that was originally added here 
    android.view.WindowLeaked: Activity com.xxxxxx.eventmanager.EventDetailsActivity has leaked window [email protected] that was originally added here 
     at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374) 
     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292) 
     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224) 
     at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149) 
     at android.view.Window$LocalWindowManager.addView(Window.java:547) 
     at android.app.Dialog.show(Dialog.java:277) 
     at com.xxxxxx.eventmanager.fragments.EventPurchasesFragment$InvoiceAsync.onPreExecute(EventPurchasesFragment.java:122) 
     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586) 
     at com.xxxxxx.eventmanager.fragments.EventPurchasesFragment.onStart(EventPurchasesFragment.java:69) 
     at android.support.v4.app.Fragment.performStart(Fragment.java:2000) 
     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1102) 
     at android.support.v4.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:926) 
     at android.support.v4.app.FragmentManagerImpl.startPendingDeferredFragments(FragmentManager.java:1276) 
     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1634) 
     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570) 
     at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:164) 
     at android.support.v4.view.ViewPager.populate(ViewPager.java:1177) 
     at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:608) 
     at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:570) 
     at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:551) 
     at com.xxxxxx.eventmanager.EventDetailsActivity$1.onTabSelected(EventDetailsActivity.java:57) 
     at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1024) 
     at android.support.design.widget.TabLayout.selectTab(TabLayout.java:994) 
     at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1262) 
     at android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:1360) 
     at android.view.View$PerformClick.run(View.java:16966) 
     at android.os.Handler.handleCallback(Handler.java:615) 
     at android.os.Handler.dispatchMessage(Handler.java:92) 
     at android.os.Looper.loop(Looper.java:137) 
     at android.app.ActivityThread.main(ActivityThread.java:4745) 
     at java.lang.reflect.Method.invokeNative(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:511) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
     at dalvik.system.NativeStart.main(Native Method) 

Diese Aktivität mein Fragments ist:

package com.xxxxxx.eventmanager.fragments; 

import android.app.AlarmManager; 
import android.app.PendingIntent; 
import android.app.ProgressDialog; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.content.SharedPreferences; 
import android.os.AsyncTask; 
import android.os.Build; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.AdapterView; 
import android.widget.ListView; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.xxxxxx.eventmanager.EventDetailsActivity; 
import com.xxxxxx.eventmanager.R; 
import com.xxxxxx.eventmanager.adapters.InvoiceBaseAdapter; 
import com.xxxxxx.eventmanager.models.InvoiceModel; 
import com.xxxxxx.eventmanager.objects.Invoice; 

import java.util.ArrayList; 
import java.util.List; 

/** 
* Created by djoks on 22/03/2016. 
*/ 
public class EventPurchasesFragment extends Fragment { 

    // Shared Preferences 
    SharedPreferences settings; 
    Context context; 
    View view; 

    InvoiceModel im; 

    //Array Adapter that will hold our ArrayList and display the items on the ListView 
    InvoiceBaseAdapter adapter; 
    List<Invoice> il; 
    ListView invoiceListView; 

    Invoice io; 

    InvoiceBroadcastReceiver receiver; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     view = inflater.inflate(R.layout.fragment_event_purchases, container, false); 

     this.context = container.getContext(); 
     this.im = new InvoiceModel(context); 
     this.io = new Invoice(); 

     return view; 
    } 

    @Override 
    public void onStart() { 
     super.onStart(); 

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 
      new InvoiceAsync().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null); 
     }else{ 
      new InvoiceAsync().execute(); 
     } 

     invoiceListView = (ListView) view.findViewById(R.id.invoiceListView); 
     invoiceListView.setFocusable(false); 
     invoiceListView.setClickable(true); 
     invoiceListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
       /*TextView eventIdView = (TextView) view.findViewById(R.id.eventIdView); 
       int eventId = Integer.parseInt(eventIdView.getText().toString()); 

       Intent i = new Intent(context, EventDetailsActivity.class); 
       i.putExtra("eventId", eventId); 
       startActivity(i);*/ 
      } 
     }); 
    } 

    @Override 
    public void onResume() { 
     super.onResume(); 

     IntentFilter filter = new IntentFilter("com.xxxxxx.eventmanager.UPDATE_INVOICE_DATASOURCE"); 
     receiver = new InvoiceBroadcastReceiver(); 
     context.registerReceiver(receiver, filter); 
    } 

    @Override 
    public void onPause() { 
     super.onPause(); 

     context.unregisterReceiver(receiver); 
    } 

    private class InvoiceAsync extends AsyncTask<Void, Void, ArrayList<Invoice>> { 
     ProgressDialog pd; 
     InvoiceModel im; 
     String msg = ""; 

     @Override 
     protected void onPreExecute() { 
      // TODO Auto-generated method stub 
      super.onPreExecute(); 

      if (pd == null) { 
       pd = new ProgressDialog(context); 
       pd.setMessage("Loading Invoices"); 
       pd.setIndeterminate(true); 
       pd.setCancelable(true); 
       pd.setCanceledOnTouchOutside(false); 
       pd.show(); 
      } 

     } 

     @Override 
     protected ArrayList<Invoice> doInBackground(Void... params) { 
      // TODO Auto-generated method stub 

      InvoiceModel im = new InvoiceModel(context); 
      return im.get(); 
     } 

     @Override 
     protected void onPostExecute(ArrayList<Invoice> result) { 
      // TODO Auto-generated method stub 
      super.onPostExecute(result); 

      if(pd.isShowing()){ 
       pd.dismiss(); 
      } 

      if(result !=null && result.size() > 0){ 
       adapter = new InvoiceBaseAdapter(context, result); 
       invoiceListView.setAdapter(adapter); 
       invoiceListView.setTextFilterEnabled(true); 
       adapter.notifyDataSetChanged(); 
      } else { 
       Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); 
      } 
     } 


    } 

    private class InvoiceBroadcastReceiver extends BroadcastReceiver { 

     @Override 
     public void onReceive(Context context, Intent intent) { 
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 
       new InvoiceAsync().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null); 
      }else{ 
       new InvoiceAsync().execute(); 
      } 
     } 
    } 
} 

Das ist mein Modell ist, wo ich SQLiteDatabase Transaktionen handhaben:

package com.xxxxxx.eventmanager.models; 

import android.content.ContentValues; 
import android.content.Context; 
import android.content.SharedPreferences; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 

import com.xxxxxx.eventmanager.database.LocalDBDataSource; 
import com.xxxxxx.eventmanager.objects.Event; 
import com.xxxxxx.eventmanager.objects.Invoice; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.util.ArrayList; 

/** 
* Created by djoks on 28/03/2016. 
*/ 
public class InvoiceModel { 

    Context context; 
    SQLiteDatabase db; 
    SharedPreferences settings; 
    AppModel app; 

    public InvoiceModel(Context c) { 
     super(); 
     this.context = c; 
     this.settings = c.getSharedPreferences("App", context.MODE_PRIVATE); 
     this.app = new AppModel(c); 
    } 

    private void insert(Invoice i) { 
     ContentValues cv = new ContentValues(); 
     cv.put("invoice_id", i.getInvoiceId()); 
     cv.put("type", i.getType()); 
     cv.put("vendor_id", i.getVendorId()); 
     cv.put("vendor_name", i.getVendorName()); 
     cv.put("reference_code", i.getReferenceCode()); 
     cv.put("total_no_of_tickets", i.getTotalNoOfTickets()); 
     cv.put("total_tickets_amount", i.getTotalTicketsAmount()); 
     cv.put("total_extras_amount", i.getTotalExtrasAmount()); 
     cv.put("total_amount_billed", i.getTotalAmountBilled()); 
     cv.put("total_charges_applied", i.getTotalChargesApplied()); 
     cv.put("total_discounts_applied", i.getTotalDiscountsApplied()); 
     cv.put("customer", i.getCustomerDetails().toString()); 
     cv.put("tickets", i.getTicketsPurchased().toString()); 
     cv.put("extras", i.getExtrasPurchased().toString()); 
     cv.put("created_at", i.getCreatedAt()); 
     cv.put("updated_at", i.getUpdatedAt()); 
     cv.put("deleted_at", i.getDeletedAt()); 
     db.insert("invoices", null, cv); 
    } 

    private void update(Invoice i){ 
     String whereClause = "invoice_id = ?"; 
     String[] whereParams = {String.valueOf(i.getInvoiceId())}; 

     ContentValues cv = new ContentValues(); 
     cv.put("invoice_id", i.getInvoiceId()); 
     cv.put("type", i.getType()); 
     cv.put("vendor_id", i.getVendorId()); 
     cv.put("vendor_name", i.getVendorName()); 
     cv.put("reference_code", i.getReferenceCode()); 
     cv.put("total_no_of_tickets", i.getTotalNoOfTickets()); 
     cv.put("total_tickets_amount", i.getTotalTicketsAmount()); 
     cv.put("total_extras_amount", i.getTotalExtrasAmount()); 
     cv.put("total_amount_billed", i.getTotalAmountBilled()); 
     cv.put("total_charges_applied", i.getTotalChargesApplied()); 
     cv.put("total_discounts_applied", i.getTotalDiscountsApplied()); 
     cv.put("customer", i.getCustomerDetails().toString()); 
     cv.put("tickets", i.getTicketsPurchased().toString()); 
     cv.put("extras", i.getExtrasPurchased().toString()); 
     cv.put("created_at", i.getCreatedAt()); 
     cv.put("updated_at", i.getUpdatedAt()); 
     cv.put("deleted_at", i.getDeletedAt()); 
     db.update("invoices", cv, whereClause, whereParams); 
    } 

    public void save(Invoice i) { 

     db = LocalDBDataSource.getHelper(context).getWritableDatabase(); 

     String whereClause = "invoice_id = ?"; 
     String[] whereParams = {String.valueOf(i.getInvoiceId())}; 
     String[] columns = {"*"}; 

     Cursor c = null; 
     try{ 
      c = db.query("invoices", columns, whereClause, whereParams, null, null, null); 
      if(c.getCount() > 0) 
      { 
       update(i); 
      } else{ 
       insert(i); 
      } 

     } finally { 
      if(c != null && !c.isClosed()){ 
       c.close(); 
      } 

      if(db != null && db.isOpen()){ 
       db.close(); 
      } 

     } 

    } 

    public ArrayList<Invoice> get() { 
     db = LocalDBDataSource.getHelper(context).getWritableDatabase(); 
     Cursor c = null; 
     String[] columns = {"*"}; 

     ArrayList<Invoice> invoices = new ArrayList<Invoice>(); 

     try{ 
      c = db.query(false, "invoices", columns, null, null, null, null, null, null); 
      if(c.getCount() > 0){ 
       while(c.moveToNext()){ 
        invoices.add(new Invoice(
          c.getInt(c.getColumnIndex("invoice_id")), 
          c.getString(c.getColumnIndex("type")), 
          c.getInt(c.getColumnIndex("vendor_id")), 
          c.getString(c.getColumnIndex("venue_name")), 
          c.getString(c.getColumnIndex("reference_code")), 
          c.getInt(c.getColumnIndex("total_no_of_tickets")), 
          c.getFloat(c.getColumnIndex("total_tickets_amount")), 
          c.getFloat(c.getColumnIndex("total_extras_amount")), 
          c.getFloat(c.getColumnIndex("total_amount_billed")), 
          c.getFloat(c.getColumnIndex("total_charges_applied")), 
          c.getFloat(c.getColumnIndex("total_discounts_applied")), 
          new JSONObject(c.getString(c.getColumnIndex("customer"))), 
          new JSONArray(c.getString(c.getColumnIndex("tickets"))), 
          new JSONArray(c.getString(c.getColumnIndex("extras"))), 
          c.getString(c.getColumnIndex("created_at")), 
          c.getString(c.getColumnIndex("updated_at")), 
          c.getString(c.getColumnIndex("deleted_at")) 
        )); 
       } 

      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } finally{ 
      if (c !=null && !c.isClosed()) { 
       c.close(); 
      } 

      if(db!=null && db.isOpen()) { 
       db.close(); 
      } 
     } 

     return invoices.size() > 0 ? invoices : new ArrayList<Invoice>(); 
    } 
} 

Antwort

2

Der Fehler wird dadurch verursacht:

Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. 
Make sure the Cursor is initialized correctly before accessing data from it. 
    at android.database.CursorWindow.nativeGetString(Native Method) 
    at android.database.CursorWindow.getString(CursorWindow.java:434) 
    at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51) 
    at com.xxxxxx.eventmanager.models.InvoiceModel.get(InvoiceModel.java:129) 

Insbesondere Linie 129:

c.getString(c.getColumnIndex("venue_name")), 

Enthält diese Spalte existieren? Ist es eine Schnur?

Ich würde sagen, dass solche Spalte nicht existiert. Tatsächlich entsprechend die Dokumentation, getColumnIndex -1 zurück, wenn die Spalte nicht existiert:

Gibt den nullbasierten Index für die angegebenen Spaltennamen, oder -1, wenn die Spalte nicht existiert. Wenn Sie erwarten, dass die Spalte existiert, verwenden Sie stattdessen getColumnIndexOrThrow (String), wodurch der Fehler deutlicher wird.

+0

Vielen Dank !! Das habe ich gar nicht bemerkt! Aber warum wird SQLite mir keinen datenbankspezifischen Fehler wie "Spalte nicht gefunden" geben? Ich habe viel Zeit damit verbracht zu erforschen, warum mein Aktivitätsfenster undicht war. – user3718908

+1

Da Sie Low-Level-API verwenden, um mit der Datenbank umzugehen, müssen Sie also wissen, was Sie tun - Sie hätten getColumnIndexOrThrow verwenden können, wie in der Dokumentation vorgeschlagen, und Sie hätten ein besseres Feedback erhalten. Lies immer den vollen Stack von oben beginnend :) – Markon

1

Sie verwenden nicht vorhandenen Spaltennamen in get() Methode Change -

c.getString(c.getColumnIndex("venue_name")), 

von

c.getString(c.getColumnIndex("vendor_name")), 

Hinweis: Um diese Art von Tippfehler zu vermeiden immer die Konstanten verwenden, um Speichern Sie Ihre Spaltennamen und verwenden Sie diese Konstanten in Ihren Datenbankoperationen.

+0

was ist der Sinn beim Kopieren einer bereits existierenden Antwort? – Markon

+0

Entschuldigung. Ich habe niemandes Antwort kopiert. Es könnte passieren, dass beim Verfassen meiner Antwort du deine gedrückt hast. –

+0

Es ist in Ordnung. Es passiert. – Markon

Verwandte Themen