jeudi 24 septembre 2015

Error in app,caused wrong using of SQLite and something else [duplicate]

This question already has an answer here:

Error was caused when Im trying to add DataBase to my app.I have SQLHelper.class,MainActivity.class.I want to store data from database and show then in ListView when I haven't the Internet access .Whats wrong? SQLHelper:

public class SqlHelper {
String title;
    String description;
    String image;
    public static final String KEY_ROWID = "_id";
    public static final String KEY_TITLE = "title";
    public static final String KEY_DESCRIPTION = "description";
    public static final String KEY_IMAGE = "image";
private SqlHelper mDb;
    private static final String DATABASE_NAME = "DBCategory";
    private static final String DATABASE_TABLE = "categoryTable";
    private static final int DATABASE_VERSION = 1;

    private DbHelper ourHelper;
    private final Context ourContext;
    private SQLiteDatabase ourDatabase;

    public SqlHelper(Context c){
        ourContext = c;
    }

    public SqlHelper open() throws SQLException{
        ourHelper = new DbHelper(ourContext);
        ourDatabase = ourHelper.getWritableDatabase();
        return this;
    }

    public void close(){
        ourHelper.close();
    }





    private static class DbHelper extends SQLiteOpenHelper{

        public DbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
                            KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                            KEY_TITLE + " TEXT NOT NULL," +KEY_DESCRIPTION +"TEXT NOT NULL ," +KEY_IMAGE + "TEXT NOT NULL );"
            );
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
            onCreate(db);
        }

    }

    public long createEntry(String title, String description,String image) {
        ContentValues cv = new ContentValues();
        cv.put(KEY_TITLE, title);
        cv.put(KEY_DESCRIPTION,description);
        cv.put(KEY_IMAGE, image);
        return ourDatabase.insert(DATABASE_TABLE, null, cv);
    }

    public ArrayList<HashMap<String, String>> getAllData()
    {
        ArrayList<HashMap<String, String>> array_list = new ArrayList<HashMap<String, String>>();

        //hp = new HashMap();
        SQLiteDatabase db = this.ourHelper.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from categoryTable", null );
        res.moveToFirst();

        while(res.isAfterLast() == false){

            HashMap<String,String>  hashmap = new HashMap<String, String>();
            hashmap.put("title", res.getString(res.getColumnIndex(title)));
            hashmap.put("description", res.getString(res.getColumnIndex(description)));
            hashmap.put("image", res.getString(res.getColumnIndex(image)));


            array_list.add(hashmap);
            res.moveToNext();
        }
        return array_list;
    }
}

MainActivity:

public class MainActivity extends ListActivity {
private Context context;
SqlHelper dbHelper;
    Intent intent;
    private static String url = "http://ift.tt/1MiJRNN";
    private static final String TITLE = "title";
    private static final String DESCRIPTION = "description";
    private static final String IMAGE = "image";
    ArrayList<HashMap<String,String>> jsonlist = new ArrayList<HashMap<String, String>>();
    ArrayList<HashMap<String,String>> bdList;
   ListView lv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

lv=(ListView) findViewById(android.R.id.list);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String title1 = jsonlist.get(position).get("title");
                String description1 = jsonlist.get(position).get("description");
                String url1 = jsonlist.get(position).get("image");
                intent = new Intent(MainActivity.this, DetailInfo.class);
                new ProgressTask(MainActivity.this).execute();
               // bdList = dbHelper.getAllData();
                intent.putExtra("title", title1);
                intent.putExtra("description", description1);
                intent.putExtra("url", url1);
                startActivity(intent);
                dbHelper = new SqlHelper(MainActivity.this);
                try {
                    dbHelper.open();
                } catch (SQLException e) {
                    e.printStackTrace();
        }
    }
});



    }



    @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.reload) {
         new ProgressTask(MainActivity.this).execute();
        }
else if(id == R.id.menu_item_share){
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT, "Put whatever you want");
            startActivity(Intent.createChooser(intent,"Share via"));
        }
        return super.onOptionsItemSelected(item);
    }

    private class ProgressTask extends AsyncTask<String,Void,Boolean> {
        private ProgressDialog dialog;
        private ListActivity activity;
        private Context context;
        public ProgressTask(MainActivity activity) {
            this.activity = activity;
            context = activity;
            dialog = new ProgressDialog(context);
        }

        protected void onPreExecute(){
           this.dialog.setMessage("Progress start");
           this.dialog.show();
        }
        protected void onPostExecute(final Boolean success){
            try{
       if((this.dialog != null)&& this.dialog.isShowing()){
this.dialog.dismiss();
            }
            CustomListAdapter adapter =  new CustomListAdapter(MainActivity.this,jsonlist, R.layout.list_item,new String[]{TITLE,DESCRIPTION},new int[]{R.id.title,R.id.description});
lv.setAdapter(adapter);
//setListAdapter(adapter);


        }catch (final IllegalArgumentException e){e.printStackTrace();}
        }
        protected Boolean doInBackground(String... args) {
           JSONParser jParser = new JSONParser();
            JSONArray json = jParser.getJSONFromUrl(url);
            for(int i =0;i<json.length();i++) {
                try {
                    JSONObject c = json.getJSONObject(i);
                    String vtitle = c.getString(TITLE);
                    String vdescription = c.getString(DESCRIPTION);
                    String vimage = c.getString(IMAGE);
                    dbHelper.createEntry(vtitle,vdescription,vimage);
                   // dbHelper.close();
                    HashMap<String, String> map = new HashMap<>();
                    map.put(TITLE, vtitle);
                    map.put(DESCRIPTION, vdescription);
map.put(IMAGE, vimage);
                    jsonlist.add(map);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }
    }
/*private void displaysavedlv(){
    Cursor cursor = dbHelper.fetchAllCountries();
CustomCursorAdapter adapter1 = new CustomCursorAdapter(MainActivity.this,cursor);
lv.setAdapter(adapter1);


}*/
  /*  private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni == null) {
            // There are no active networks.
            return false;
        } else
            return true;
    }*/
}

Error:

09-24 14:35:16.965  17283-17648/com.example.vnvbnv.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:299)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
            at java.util.concurrent.FutureTask.run(FutureTask.java:239)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:864)
     Caused by: java.lang.NullPointerException
            at com.example.vnvbnv.myapplication.MainActivity$ProgressTask.doInBackground(MainActivity.java:152)
            at com.example.vnvbnv.myapplication.MainActivity$ProgressTask.doInBackground(MainActivity.java:117)
            at android.os.AsyncTask$2.call(AsyncTask.java:287)
            at java.util.concurrent.FutureTask.run(FutureTask.java:234)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:864)
09-24 14:35:17.315  17283-17283/com.example.vnvbnv.myapplication D/qdmemalloc﹕ ion: Unmapping buffer  base:0x54cb6000 size:1536000
09-24 14:35:17.315  17283-17283/com.example.vnvbnv.myapplication D/qdmemalloc﹕ ion: Unmapping buffer  base:0x48e5b000 size:4096
09-24 14:35:17.315  17283-17283/com.example.vnvbnv.myapplication D/qdmemalloc﹕ ion: Unmapping buffer  base:0x54f5d000 size:1536000
09-24 14:35:17.315  17283-17283/com.example.vnvbnv.myapplication D/qdmemalloc﹕ ion: Unmapping buffer  base:0x49151000 size:4096
09-24 14:35:17.315  17283-17283/com.example.vnvbnv.myapplication D/qdmemalloc﹕ ion: Unmapping buffer  base:0x550d4000 size:1536000
09-24 14:35:17.325  17283-17283/com.example.vnvbnv.myapplication D/qdmemalloc﹕ ion: Unmapping buffer  base:0x5040d000 size:4096
09-24 14:35:17.485  17283-17283/com.example.vnvbnv.myapplication D/qdmemalloc﹕ ion: Unmapping buffer  base:0x5547f000 size:307200
09-24 14:35:17.525  17283-17283/com.example.vnvbnv.myapplication D/qdmemalloc﹕ ion: Unmapping buffer  base:0x50cd7000 size:4096
09-24 14:35:17.525  17283-17283/com.example.vnvbnv.myapplication D/qdmemalloc﹕ ion: Unmapping buffer  base:0x55520000 size:307200
09-24 14:35:17.525  17283-17283/com.example.vnvbnv.myapplication D/qdmemalloc﹕ ion: Unmapping buffer  base:0x50d30000 size:4096
09-24 14:35:17.525  17283-17283/com.example.vnvbnv.myapplication D/qdmemalloc﹕ ion: Unmapping buffer  base:0x5556b000 size:307200
09-24 14:35:17.525  17283-17283/com.example.vnvbnv.myapplication D/qdmemalloc﹕ ion: Unmapping buffer  base:0x5111f000 size:4096
09-24 14:35:18.246  17283-17283/com.example.vnvbnv.myapplication E/WindowManager﹕ Activity com.example.vnvbnv.myapplication.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{415417b0 V.E..... R......D 0,0-456,144} that was originally added here
    android.view.WindowLeaked: Activity com.example.vnvbnv.myapplication.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{415417b0 V.E..... R......D 0,0-456,144} that was originally added here
            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:458)
            at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
            at android.app.Dialog.show(Dialog.java:286)
            at com.example.vnvbnv.myapplication.MainActivity$ProgressTask.onPreExecute(MainActivity.java:129)
            at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
            at android.os.AsyncTask.execute(AsyncTask.java:534)
            at com.example.vnvbnv.myapplication.MainActivity.onOptionsItemSelected(MainActivity.java:106)
            at android.app.Activity.onMenuItemSelected(Activity.java:2609)
            at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:1056)
            at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
            at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
            at com.android.internal.view.menu.ActionMenuView.invokeItem(ActionMenuView.java:559)
            at com.android.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:157)
            at android.view.View.performClick(View.java:4231)
            at android.view.View$PerformClick.run(View.java:17537)
            at android.os.Handler.handleCallback(Handler.java:725)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:158)
            at android.app.ActivityThread.main(ActivityThread.java:5751)
            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:1083)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
            at dalvik.system.NativeStart.main(Native Method)
09-24 14:35:18.256  17283-17283/com.example.vnvbnv.myapplication I/Choreographer﹕ Skipped 35 frames!  The application may be doing too much work on its main thread.
09-24 14:35:18.877  17283-17648/com.example.vnvbnv.myapplication D/Process﹕ killProcess, pid=17283
09-24 14:35:18.947  17283-17648/com.example.vnvbnv.myapplication D/Process﹕ dalvik.system.VMStack.getThreadStackTrace(Native Method)
09-24 14:35:19.067  17283-17648/com.example.vnvbnv.myapplication D/Process﹕ java.lang.Thread.getStackTrace(Thread.java:599)
09-24 14:35:19.067  17283-17648/com.example.vnvbnv.myapplication D/Process﹕ android.os.Process.killProcess(Process.java:1004)
09-24 14:35:19.097  17283-17648/com.example.vnvbnv.myapplication D/Process﹕ com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:123)
09-24 14:35:19.097  17283-17648/com.example.vnvbnv.myapplication D/Process﹕ java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
09-24 14:35:19.127  17283-17648/com.example.vnvbnv.myapplication D/Process﹕ java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)

Aucun commentaire:

Enregistrer un commentaire