当我在OneFragment.java中调用inp(用于从数据库中检索数据)函数时,它会捕获所有数据并将其存储在数据库中并抓取它并将其添加到列表视图中当我尝试检索它时工作正常给出错误是db关闭的问题?或上下文传递?我是新的 DatabaseHelper.java
package info.androidhive.UcCollegeNotifier;
/**
* Created by Extreme on 4/15/2017.
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
import android.util.Log;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_DATE = "date";
private static final String KEY_TIME = "time";
private static final String KEY_NEWS = "news";
private static final String KEY_VALID = "valid";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//context.deleteDatabase(DATABASE_NAME);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
//String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_DATE + " TEXT,"+KEY_TIME +"TEXT," + KEY_NEWS +"TEXT," + KEY_VALID + " TEXT)";
// db.execSQL("CREATE TABLE contacts1(id INTEGER AUTOINCREMENT, date VARCHAR,time VARCHAR,news VARCHAR);");
Log.d("Creadeted","DB Creadeted");
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_DATE + " TEXT,"
+ KEY_TIME + " TEXT," + KEY_NEWS + " TEXT,"+ KEY_VALID+ " TEXT"+")";
db.execSQL(CREATE_CONTACTS_TABLE);
//
// db.execSQL(
// "create table contacts1 " +
// "(id integer primary key, date text,time text,news text, valid text)"
// );
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
public void addContact(String id,String date,String time,String news,String valid) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// values.put(KEY_ID,id ); // Contact Name
values.put(KEY_DATE,date); // Contact Phone
values.put(KEY_TIME,time ); // Contact Phone
values.put(KEY_NEWS,news);
db.insert(TABLE_CONTACTS, null, values);
//values.put(KEY_VALID,valid);
//Log.d("Insering",id);
Log.d("Insering",date);
Log.d("Insering",time);
Log.d("Insering",news);
// Log.d("Insering",valid);
// Inserting Row
db.close(); // Closing database connection
}
// Getting single contact
// Contact getContact(int id) {
// SQLiteDatabase db = this.getReadableDatabase();
//
// Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
// KEY_DATE, KEY_TIME,KEY_NEWS,KEY_VALID }, KEY_ID + "=?",
// new String[] { String.valueOf(id) }, null, null, null, null);
// if (cursor != null)
// cursor.moveToFirst();
//
//// Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
//// cursor.getString(1), cursor.getString(2));
// // return contact
// return contact;
// }
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID((Integer.parseInt(cursor.getString(0))));
contact.setDate(cursor.getString(1));
contact.setTime(cursor.getString(2));
contact.setNews(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
// public int updateContact(Contact contact) {
// SQLiteDatabase db = this.getWritableDatabase();
//
// ContentValues values = new ContentValues();
// values.put(KEY_NAME, contact.getName());
// values.put(KEY_PH_NO, contact.getPhoneNumber());
//
// // updating row
// return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
// new String[] { String.valueOf(contact.getID()) });
// }
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
OneFragment.java
public class OneFragment extends Fragment {
public static boolean flagt;
public static String[] ids;
public static String[] date;
public static String[] time;
public static String[] news;
public static String[] valid;
public static String log;
public static String strArray[]={"Hello there","hi"};
//=new String[10];
ArrayList<String> listItems=new ArrayList<String>();
//private ListView mainListView ;
ArrayAdapter<String> adapter;
List<Map<String,List<String>>> list = new ArrayList<Map<String,List<String>>>();//This is the final list you need
Map<String, List<String>> map1 = new HashMap<String, List<String>>();//This is one instance of the map you want to store in the above map
List<String> arraylist1 = new ArrayList<String>();
// List<Map<String, String>> data = new ArrayList<Map<String, String>>();
//String ts;
boolean ts;
private ProgressDialog loading;
DatabaseHandler db=new DatabaseHandler(getActivity());
public OneFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getda();
//getData();
ts=MainActivity.chek();
if(ts) {
Toast.makeText(getActivity(),"Loggin found",Toast.LENGTH_SHORT).show();
getData();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_one, container, false);
//ArrayAdapter<String> ListViewAdapter =new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,ids);
// ts=MainActivity.chek();
// if(ts) {
// Toast.makeText(getActivity(),"Loggin found",Toast.LENGTH_SHORT).show();
// getData();
// }
// Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_one, container, false);
//Toast.makeText(getActivity(),"e,lladasd",Toast.LENGTH_SHORT).show();
// ListView ls=(ListView)view.findViewById(R.id.lis1);
// ListViewAdapter =new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1,strArray);
// ls.setAdapter(ListViewAdapter);
ListView ls=(ListView)view.findViewById(R.id.list);
adapter=new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1,
arraylist1);
ls.setAdapter(adapter);
return view;
}
public class Config {
public static final String DATA_URL = "http://kambi.appsmash.in/kuntham.php";
public static final String k_date12 = "id";
public static final String k_first = "date";
public static final String k_second = "time";
public static final String k_third = "news";
public static final String k_compli = "valid";
public static final String JSON_ARRAY = "result";
}
private void getData() {
//String id = editTextId.getText().toString().trim();
//if (id.equals("")) {
//Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
//return;
Toast.makeText(getActivity(), "e,lladasd", Toast.LENGTH_SHORT).show();
String url = Config.DATA_URL;
StringRequest stringRequest = new StringRequest("http://disapp.000webhostapp.com/ucgrab.php/ucgrab.php", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
//ParseJSON pj=new ParseJSON(json)
//pj.parseJSON();
// String date123 = "";
// String first1 = "";
// String second2 = "";
// String third3 = "";
// String compli4 = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
// date123 = collegeData.getString(Config.k_date12);
// first1 = collegeData.getString(Config.k_first);
// second2 = collegeData.getString(Config.k_second);
// third3 = collegeData.getString(Config.k_third);
// compli4 = collegeData.getString(Config.k_compli);
ids= new String[result.length()];
date= new String[result.length()];
time= new String[result.length()];
news= new String[result.length()];
valid= new String[result.length()];
for(int i=0;i<result.length();i++) {
JSONObject jo = result.getJSONObject(i);
ids[i] = jo.getString("id");
date[i] = jo.getString("date");
time[i] = jo.getString("time");
news[i] = jo.getString("news");
valid[i] = jo.getString("valid");
//Used to show data get from server
// Toast.makeText(getActivity(), ids[i].toString(), Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(), date[i].toString(), Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(), time[i].toString(), Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(), news[i].toString(), Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(), valid[i].toString(), Toast.LENGTH_SHORT).show();
DatabaseHandler db = new DatabaseHandler(getActivity());
db.addContact(ids[i], date[i], time[i], news[i], valid[i]);
//if()
//{
// flagt=true;
//}
// }
// if(flagt==true)
// {
// inp();
}
//Log.d("Reading: ","Reading all contacts..");
// List<Contact> contacts = db.getAllContacts();
//
// for (Contact cn : contacts) {
// log = "Date: " + cn.getDate() + "Time: " + cn.getTime()+"Notification"+cn.getNews()+";";
// // Writing Contacts to log
// getda(log);
// Log.d("Name: ", log);
//// ArrayList<String> planetList = new ArrayList<String>();
//// planetList.addAll( Arrays.asList(log) );
//// listAdapter = new ArrayAdapter<String>(this,R.layout.fragment_one, planetList);
// //ListView ls=(ListView)view.findViewById(R.id.lis1
// //ArrayAdapter<String> ListViewAdapter =new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,ids);
// String strArray[] = log.split(";");
// System.out.println("String Array is : ");
//// for(i=0; i < strArray.length; i++){
//// //System.out.println(strArray[i]);
//// //ListViewAdapter.add("log");
//// // getda(log);
//// }
// }
// Map<String, String> datum = new HashMap<String, String>(2);
// datum.put("First Line", "First line of text");
// datum.put("Second Line","Second line of text");
// listItems.add(datum);
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(getActivity(), date123, Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(), first1, Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(), second2, Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(), third3, Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(), compli4, Toast.LENGTH_SHORT).show();
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
Toast.makeText(getActivity(), "chhosed one", Toast.LENGTH_LONG).show();
// getData();
}
}
//Log.d("Reading: ","Reading all contacts..");
// List<Contact> contacts = db.getAllContacts();
//
// for (Contact cn : contacts) {
// String log = "Id: "+cn.getID()+" ,Name: " + cn.getDate() + " ,Phone: " + cn.getTime()+",NEws"+cn.getNews();
// // Writing Contacts to log
// Log.d("Name: ", log);
// }
public void getda(String log)
{
arraylist1.add(log);//And so on..
map1.put(log,arraylist1);
//And so on...
list.add(map1);//In this way you can add.
//listItems.add(log);
adapter.notifyDataSetChanged();
}
public void inp()
{
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
log = "Date: " + cn.getDate() + "Time: " + cn.getTime()+"Notification"+cn.getNews()+";";
// Writing Contacts to log
getda(log);
Log.d("Name: ", log);
// ArrayList<String> planetList = new ArrayList<String>();
// planetList.addAll( Arrays.asList(log) );
// listAdapter = new ArrayAdapter<String>(this,R.layout.fragment_one, planetList);
//ListView ls=(ListView)view.findViewById(R.id.lis1
//ArrayAdapter<String> ListViewAdapter =new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,ids);
String strArray[] = log.split(";");
System.out.println("String Array is : ");
// for(i=0; i < strArray.length; i++){
// //System.out.println(strArray[i]);
// //ListViewAdapter.add("log");
// // getda(log);
// }
}
}
}
答案 0 :(得分:0)
找到问题所在的解决方案
DatabaseHandler db=new DatabaseHandler(getActivity());
在#34; onefragment&#34;文件我把操作分成两部分 第一个是在顶部
DatabaseHandler db;
在Oncreate()上
db =new DatabaseHandler(getActivity());
感谢这个帖子帮助我(kdehairy) SQLite database in combination with fragments