0

My App crashes on starting the log shows that the error is when i try to get readable database , it seems that i got problems with context but i don't know what to do i've done much searching and tried many things .

i will post my classes and log .

My Fragment Class

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import com.example.ahmed.popularmovies.data.DbOpenHelper;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;



public class MainFragment extends Fragment {

public final String API_KEY = "b932ba435fc93a5944938fe9d44cd198";
public final String BASE_URL = "http://api.themoviedb.org/3/discover/movie?sort_by=&api_key=";


ArrayList<movie> movies = new ArrayList<>();
movieAdapter adapter;
GridView gridview;

DbOpenHelper dbHelper;


public MainFragment() {
    getDataFromDB();
}


public MainFragment(String SortBy) {
    new FetchDataFromApi(SortBy).execute();
}



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater,container,savedInstanceState);
    View view = inflater.inflate(R.layout.fragment_main, container, false);
    dbHelper = new DbOpenHelper(getActivity());
    gridview = (GridView) getActivity().findViewById(R.id.gridView);
    return view;
}


class FetchDataFromApi extends AsyncTask<String, Void, Boolean> {
    String SORT_CATEGORY;

    FetchDataFromApi(String paramUrl) {
        SORT_CATEGORY = paramUrl;
    }

    @Override
    protected Boolean doInBackground(String... params) {

        HttpURLConnection urlConnection = null;

        try {
            Uri uriBuilder = Uri.parse(BASE_URL).buildUpon()
                    .appendQueryParameter("sort_by", SORT_CATEGORY)
                    .appendQueryParameter("api_key", API_KEY)
                    .build();
            URL url = new URL(uriBuilder.toString());
            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream in = urlConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
            StringBuilder sb = new StringBuilder();
            String line;

            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }

            String response = sb.toString();
            ParseJsonData(response);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            urlConnection.disconnect();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        adapter = new movieAdapter(getActivity(), R.layout.movie_item, movies);
        gridview.setAdapter(adapter);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PassDataToDetailedActivity(position);
            }
        });
    }


    private void ParseJsonData(String response) throws JSONException {
        String PosterBaseUrl = "http://image.tmdb.org/t/p/";
        String LargePoster = "w185";
        String SmallPoster = "";
        final String RESULTS = "results";
        final String ORIGINAL_TITLE = "original_title";
        final String OVERVIEW = "overview";
        final String RELEASE_DATE = "release_date";
        final String POSTER_PATH = "poster_path";
        final String VOTE_AVERAGE = "vote_average";
        final String POPULARITY = "popularity";


        JSONObject jsono = new JSONObject(response);
        Log.v("Json", response);
        JSONArray jarray = jsono.getJSONArray(RESULTS);

        for (int i = 0; i < jarray.length(); i++) {
            JSONObject object = jarray.getJSONObject(i);

            String title = object.getString(ORIGINAL_TITLE);
            String releaseDate = object.getString(RELEASE_DATE);
            String overView = object.getString(OVERVIEW);
            String voteAverage = object.getString(VOTE_AVERAGE);
            String popularity = object.getString(POPULARITY);
            String posterPath = object.getString(POSTER_PATH);

            String MaxPoster = PosterBaseUrl + LargePoster + posterPath;
            String MinPoster = PosterBaseUrl + SmallPoster + posterPath;

            movie m = new movie();
            m.setTitle(title);
            m.setReleaseDate(releaseDate);
            m.setOverView(overView);
            m.setVoteAverage(voteAverage);
            m.setPopularity(popularity);
            m.setLargePoster(MaxPoster);
            m.setMinPoster(MinPoster);

            movies.add(m);
        }
    }
}

private void PassDataToDetailedActivity(int position) {
    String title = movies.get(position).getTitle();
    String releaseDate = movies.get(position).getReleaseDate();
    String overView = movies.get(position).getOverView();
    String voteAverage = movies.get(position).getVoteAverage();
    String popularity = movies.get(position).getPopularity();
    String MaxPoster = movies.get(position).getLargePoster();
    String MinPoster = movies.get(position).getMinPoster();

    Intent intent = new Intent(getActivity(), DetailedActivity.class);
    intent.putExtra("title", title);
    intent.putExtra("releaseDate", releaseDate);
    intent.putExtra("overView", overView);
    intent.putExtra("voteAverage", voteAverage);
    intent.putExtra("popularity", popularity);
    intent.putExtra("", MaxPoster);
    intent.putExtra("MinPoster", MinPoster);
    startActivity(intent);
}

private void getDataFromDB() {
  \\ the problem is here
    SQLiteDatabase db = dbHelper.getReadableDatabase(); 
    String PosterUrl;
    ArrayList<String> list= new ArrayList<>();


    Cursor cursor = db.rawQuery("select * from " + DbOpenHelper.TABLE_NAME ,null );
    if (cursor .moveToFirst()) {
    do{PosterUrl = cursor.getString(cursor
                    .getColumnIndex(DbOpenHelper.FeedEntry.KEY_LARGE_POSTER_URL));

            list.add(PosterUrl);}

        while (cursor.isAfterLast() == false); {

            cursor.moveToNext();
        }
    }
    cursor.close();
    db.close();

    for(int i = 0; i < list.size(); i++) {
        Log.v("List",(list.get(i)).toString());
    }

    Log.v("hello", "its working");

}

}

My DbHelper Class

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;

  /**
  * Created by ahmed on 12/17/2015.
  */
public class DbOpenHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;

// Database Name
public static final String DATABASE_NAME = "fav.db";

// Table name
public static final String TABLE_NAME = "Data";

// Table Columns names
private static final String KEY_ID = "id";


public static abstract class FeedEntry implements BaseColumns {

    public static final String KEY_LARGE_POSTER_URL = "largePoster";
    public static final String KEY_MINI_POSTER_URL = "minPoster";
    public static final String KEY_MOVIE_NAME = "movieName";
    public static final String KEY_RELEASE_DATE = "releaseDate";
    public static final String KEY_VOTE_AVERAGE = "vote_average";
    public static final String KEY_OVERVIEW = "overview";

}

public DbOpenHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_FAVORITES_TABLE = "CREATE TABLE " + TABLE_NAME + "("
            + KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"
            + FeedEntry.KEY_LARGE_POSTER_URL + " TEXT,"
            + FeedEntry.KEY_MINI_POSTER_URL + " TEXT, "
            + FeedEntry.KEY_MOVIE_NAME + " TEXT,"
            + FeedEntry.KEY_RELEASE_DATE+" TEXT,"
            + FeedEntry.KEY_OVERVIEW+" TEXT,"
            + FeedEntry.KEY_VOTE_AVERAGE+" TEXT,"
            + ")";
    db.execSQL(CREATE_FAVORITES_TABLE);
}

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

My log

12-18 01:44:36.915 12140-12140/? E/AndroidRuntime: FATAL EXCEPTION: main
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime: Process:         com.example.ahmed.popularmovies, PID: 12140
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ahmed.popularmovies/com.example.ahmed.popularmovies.MainActivity}: android.view.InflateException: Binary XML file line #22: Error inflating class fragment
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2493)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2555)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.ActivityThread.access$800(ActivityThread.java:176)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1437)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:111)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:194)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5576)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:372)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:955)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:750)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:  Caused by: android.view.InflateException: Binary XML file line #22: Error inflating class fragment
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at com.example.ahmed.popularmovies.MainActivity.onCreate(MainActivity.java:19)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.Activity.performCreate(Activity.java:6005)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2446)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2555) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.ActivityThread.access$800(ActivityThread.java:176) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1437) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:111) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:194) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5576) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:372) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:955) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:750) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase com.example.ahmed.popularmovies.data.DbOpenHelper.getReadableDatabase()' on a null object reference
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at com.example.ahmed.popularmovies.MainFragment.getDataFromDB(MainFragment.java:194)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at com.example.ahmed.popularmovies.MainFragment.<init>(MainFragment.java:49)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at java.lang.reflect.Constructor.newInstance(Native Method)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at java.lang.Class.newInstance(Class.java:1572)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.support.v4.app.Fragment.instantiate(Fragment.java:423)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.support.v4.app.Fragment.instantiate(Fragment.java:398)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2275)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:111)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:314)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:504) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:414) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:365) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at com.example.ahmed.popularmovies.MainActivity.onCreate(MainActivity.java:19) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.Activity.performCreate(Activity.java:6005) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2446) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2555) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.ActivityThread.access$800(ActivityThread.java:176)     
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1437) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:111) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:194) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5576) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:372) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:955) 
12-18 01:44:36.915 12140-12140/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:750) 

`

Ahmed Atwa
  • 23
  • 7
  • `Caused by: android.view.InflateException: Binary XML file line #22: Error inflating class fragment` maybe the error is on your activity – Vassilis Pallas Dec 17 '15 at 23:54
  • @vspallas this error only shows when i add the line i commented in my class with "the problem is here" if i remove it the app doesn't crash and works well so the problem happens bcuz of getting the database due to nullpointerExcepton – Ahmed Atwa Dec 17 '15 at 23:56
  • 1
    ok then try not to call the `getDataFromDB();` on the constructor but on the `onCreateView` below the `gridview`. – Vassilis Pallas Dec 18 '15 at 00:00
  • @vspallas the nullpointerException is now gone dude thank you ^^ – Ahmed Atwa Dec 18 '15 at 00:37

1 Answers1

0

In your zero-argument fragment constructor, you are calling getDataFromDB(). In there, you are calling getReadableDatabase() on dbHelper. You have not initialized dbHelper, in part because you have no way to do so at this point. Hence, you crash with a NullPointerException.

First, do not implement constructors on fragments. I do not even recommend that for experts, let alone people new to Android and Java. The default zero-argument constructor that you get automatically will suffice for Android's needs. Do all your work elsewhere, driven by the fragment lifecycle methods (e.g., onCreate()).

Second, do database I/O (or any I/O) on background threads. Had you followed this rule, at least you would not have tried to do database I/O in a method invoked from a constructor, even if you ignored my first rule.

In order to use SQLiteOpenHelper, you need to create an instance of it. You are doing that in onCreateView(), which is fine. However, that means that you cannot attempt to use that instance of SQLiteOpenHelper until onCreateView() has been called, or at least until that line of code has been executed.

CommonsWare
  • 910,778
  • 176
  • 2,215
  • 2,253
  • i made the db work in asynctask which has made it much more easier as it doesn't block the ui so the error in MainActivity doesn't show ,, I will see about the constructors later but the whole problem now is the NullPointerException – Ahmed Atwa Dec 18 '15 at 00:31
  • There are 2 things to prevent this error you can initialize dbHalper in constructor or you can call getDataFromDB(); in your onCreateView method to . – Sandeep Joshi Dec 18 '15 at 09:17