我的应用程序在启动日志时崩溃显示错误是当我尝试获取可读数据库时, 似乎我遇到了上下文的问题,但我不知道该怎么做我已经做了很多搜索并尝试了很多东西。
我会发布课程和日志。
My Fragment Class
$pdfFilePath = FCPATH."/pdf/report/test.pdf";
$data['page_title'] = 'Hello world'; // pass data to the view
if (file_exists($pdfFilePath) == FALSE) {
ini_set('memory_limit','32M');
$html = $this->load->view('pdf_output', $data, true); // render the view into HTML
$this->load->library('m_pdf');
$pdf = $this->pdf->load();
$pdf->SetFooter($_SERVER['HTTP_HOST'].'|{PAGENO}|'.date(DATE_RFC822));
$pdf->WriteHTML($html); // write the HTML into the PDF
$pdf->Output($pdfFilePath, 'F');
}
}
我的DbHelper课程
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");
}
我的日志
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);
}
}
`
答案 0 :(得分:0)
在零参数片段构造函数中,您正在调用getDataFromDB()
。在那里,您在getReadableDatabase()
上呼叫dbHelper
。您尚未初始化dbHelper
,部分原因是此时您无法执行此操作。因此,您使用NullPointerException
崩溃了。
首先,不要在片段上实现构造函数。我甚至不建议专家,更不用说刚接触Android和Java的人了。您自动获得的默认零参数构造函数足以满足Android的需求。在片段生命周期方法(例如onCreate()
)的推动下,在其他地方完成所有工作。
其次,在后台线程上执行数据库I / O(或任何I / O)。如果您遵循此规则,至少您不会尝试在从构造函数调用的方法中执行数据库I / O,即使您忽略了我的第一条规则。
要使用SQLiteOpenHelper
,您需要创建它的实例。你是在onCreateView()
做的,这很好。但是,这意味着在调用SQLiteOpenHelper
之前,您不能尝试使用onCreateView()
的实例,或至少在执行该代码行之前使用该实例。