I have got these issue, but can not get solutation
Launch timeout has expired, giving up wake lock!
Activity idle timeout for HistoryRecord{44e26a30 com.india.screen/.CategoryList}
This problem get after adding these lines ( String numOfRows="select count(*) from Holyplace_Tbl where State_id='"+stateId+"'";) console nothing print after it
Activity
public class CategoryList extends Activity{
private TableRow holyPlaces,historicalPalces,beach,museum,hills,lakes;
private int stateId;
private AssetDatabaseOpenHelper assetDatabaseHelper;
private Cursor holyplacesCursor,rowsCursor;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.category_screen);
Bundle extras = getIntent().getExtras();
if (extras != null) {
stateId=extras.getInt("stateid");
System.out.println("stateid"+stateId);
}
holyPlaces=(TableRow) findViewById(R.id.holyPlaces);
historicalPalces=(TableRow) findViewById(R.id.historicalPlaces);
museum=(TableRow) findViewById(R.id.museum);
beach=(TableRow) findViewById(R.id.beach);
hills=(TableRow) findViewById(R.id.hills);
lakes=(TableRow) findViewById(R.id.lakes);
assetDatabaseHelper=new AssetDatabaseOpenHelper(CategoryList.this);
assetDatabaseHelper.openDatabase();
assetDatabaseHelper.openReadableMode();
System.out.println("success.....!");
String numOfRows="select count(*) from Holyplace_Tbl where State_id='"+stateId+"'";
System.out.println("rav "+numOfRows);
rowsCursor=assetDatabaseHelper.executeQuery(numOfRows);
System.out.println("hjkdfhfh .............................."+rowsCursor);
System.out.println("hj hi .............................."+rowsCursor);
if(rowsCursor.moveToFirst())
{
System.out.println("hi.........."+rowsCursor.getColumnCount());
do{
int count=rowsCursor.getInt(0);
System.out.println("cu "+count);
System.out.println("cursor.. "+rowsCursor.getCount());
System.out.println("ccccc "+rowsCursor.getInt(0));
System.out.println("jdjhfhf "+rowsCursor.getColumnCount());
}while(rowsCursor.moveToNext());
}
else{
System.out.println("cursor not move");
}
rowsCursor.close();
assetDatabaseHelper.close();
System.out.println("no next value");
}
}
AssetDatabaseOpenHelper.class
public class AssetDatabaseOpenHelper {
private Context context;
private SQLiteDatabase sqliteDatabaseObj;
private String database_name;
private CreateQueries createQueriesObj;
private MySQLiteHelper mySQLitehelperObj;
private int database_version;
private String databaseName="TravelguideDb";
private int databaseVersion=3;
public AssetDatabaseOpenHelper(Context context,String databaseName,int database_version) {
this.context = context;
this.database_name=databaseName;
this.database_version=database_version;
}
public AssetDatabaseOpenHelper(Context context) {
this.context = context;
this.database_name = databaseName;
this.database_version = databaseVersion;
}
public void openDatabase() {
mySQLitehelperObj = new MySQLiteHelper(context, database_name,
database_version);
File dbFile = context.getDatabasePath(database_name);
System.out.println("Assests"+dbFile.exists());
if (!dbFile.exists()) {
try {
copyDatabase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
}
public void openReadableMode()
{
sqliteDatabaseObj = mySQLitehelperObj.getReadableDatabase();
}
public void openWriteableMode()
{
sqliteDatabaseObj = mySQLitehelperObj.getWritableDatabase();
}
public void close() {
mySQLitehelperObj.close();
}
private void copyDatabase(File dbFile) throws IOException {
OutputStream os = new FileOutputStream(dbFile);
InputStream is = null;
byte[] buffer = new byte[1024];
for(int i=1;i<5;i++)
{
is = context.getAssets().open("TravelguideDb.sqlite.00"+1);
int length;
while ((length=is.read(buffer))!=-1) {
os.write(buffer,0,length);
}
is.close();
}
os.flush();
os.close();
is.close();
}
public Cursor executeQuery(String query)
{
Cursor outputCursor= sqliteDatabaseObj.rawQuery(query, null);
return outputCursor;
}
public void createTable(String tableName, String[] columns, String[] value) {
createQueriesObj = new CreateQueries();
String createTableQuery = createQueriesObj.CreateTableQuery(tableName,
columns, value);
sqliteDatabaseObj.execSQL(createTableQuery);
System.out.println("Query" + createTableQuery);
}
public void deleteTable(String tableName)
{
sqliteDatabaseObj.execSQL("Drop table " + tableName);
}
public void deleteAllDataFromTable(String tableName) {
// truncate table
sqliteDatabaseObj.delete(tableName, null, null);
}
public void deletePerticularRows(String tableName, String whereClause,
String[] whereArgs) {
sqliteDatabaseObj.delete(tableName, whereClause, whereArgs);
}
public Cursor fetchAllRows(String tableName) {
return sqliteDatabaseObj.query(tableName, null, null, null, null, null,
null);
}
public Cursor selectOnWhereCondition(String tableName,
String[] columnsToSelect, String whereColumnName,
String[] whereEqualsTo, String groupBy, String having,
String orderBy) {
return sqliteDatabaseObj.query(tableName, columnsToSelect,
whereColumnName, whereEqualsTo, groupBy, having, orderBy);
}
public void updateRows(String tableName, String[] columnNames,
String[] values, String whereClause, String[] whereArgs)
throws SQLException {
if (columnNames.length != values.length) {
throw new SQLException();
}
ContentValues contentValue = new ContentValues();
int length = values.length;
for (int i = 0; i < length; i++) {
contentValue.put(columnNames[i], values[i]);
}
sqliteDatabaseObj.update(tableName, contentValue, whereClause,
whereArgs);
}
public long addRecords(String TableName, String[] columnNames,
String[] values) throws SQLException {
long result = 0;
if (columnNames.length != values.length) {
throw new SQLException();
} else {
ContentValues contentValues = new ContentValues();
int length = columnNames.length;
for (int i = 0; i < length; i++) {
contentValues.put(columnNames[i], values[i]);
}
result = sqliteDatabaseObj.insert(TableName, null, contentValues);
}
return result;
}
}
Related
I can't seem work out why I am getting a null pointer on this?
This is my AsyncTask that I call to grab the data. It passes it to a JSON Parser and an array of Objects is returned. This is then passed to my DBHelper where it was passing to my database through a ContentResolver....
public class getFilms extends AsyncTask<String, Void, Void> {
public int LIMIT_FILMS = 10;
String KEY = "apikey";
String LIMIT = "limit";
private static final String URL = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?";
private static final String API_KEY = "******************";
ArrayList<HashMap<String, String>> filmArrayList = new ArrayList<HashMap<String, String>>();
Context mContext;
#Override
protected Void doInBackground(String... params) {
Uri RottenUrl = Uri.parse(URL).buildUpon()
.appendQueryParameter(KEY, API_KEY)
.appendQueryParameter(LIMIT, Integer.toString(LIMIT_FILMS))
.build();
JSONParser jParser = new JSONParser();
Film[] json = jParser.getJSONFromUrl(RottenUrl.toString());
sortData(json);
return null;
}
public void sortData(Film[] jsonlist) {
DatabaseHelper dbHelper = new DatabaseHelper(mContext, null, null, 1);
dbHelper.deleteAll();
for (int i = 0; i < jsonlist.length; i++) {
dbHelper.contentAddFilm(jsonlist[i]);
}
}
}
This is my Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
private ContentResolver myCR;
public DatabaseHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, FilmDataContract.DATABASE_NAME, factory, FilmDataContract.DATABASE_VERSION);
myCR = context.getContentResolver();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(FilmDataContract.FilmEntry.SQL_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(FilmDataContract.FilmEntry.DELETE_TABLE);
onCreate(db);
}
public void addFilm(Film film) {
ContentValues values = new ContentValues();
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_TITLE, film.getTitle());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RATING, film.getRating());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RUNTIME, film.getRuntime());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_CRITICS, film.getCritics());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_AUDIENCE, film.getAudience());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_SYNOPSIS, film.getSynopsis());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_PROFILE, film.getProfile());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(FilmDataContract.TABLE_NAME,
null,
values);
db.close();
}
public Film getFilm(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor =
db.query(FilmDataContract.TABLE_NAME,
FilmDataContract.FilmEntry.COLUMNS,
"_id = ?",
new String[]{String.valueOf(id)},
null,
null,
null,
null);
if (cursor != null)
cursor.moveToFirst();
Film film = new Film();
film.setTitle(cursor.getString(1));
film.setRating(cursor.getString(2));
film.setRuntime(cursor.getString(3));
film.setCritics(cursor.getString(4));
film.setAudience(cursor.getString(5));
film.setSynopsis(cursor.getString(6));
film.setProfile(cursor.getString(7));
return film;
}
public List<Film> getAllFilms() {
List<Film> films = new LinkedList<Film>();
String query = "SELECT * FROM " + FilmDataContract.TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Film film = null;
if (cursor.moveToFirst()) {
do {
film = new Film();
film.setId(Integer.parseInt(cursor.getString(0)));
film.setTitle(cursor.getString(1));
film.setRating(cursor.getString(2));
film.setRuntime(cursor.getString(3));
film.setCritics(cursor.getString(4));
film.setAudience(cursor.getString(5));
film.setSynopsis(cursor.getString(6));
film.setProfile(cursor.getString(7));
films.add(film);
} while (cursor.moveToNext());
}
return films;
}
public int updateFilm(Film film) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_TITLE, film.getTitle());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RATING, film.getRating());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RUNTIME, film.getRuntime());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_CRITICS, film.getCritics());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_AUDIENCE, film.getAudience());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_SYNOPSIS, film.getSynopsis());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_PROFILE, film.getProfile());
int i = db.update(FilmDataContract.FilmEntry.TABLE_NAME,
values,
"_id+ = ?",
new String[]{String.valueOf(film.getId())});
db.close();
return i;
}
public int getFilmsCount() {
String countQuery = "SELECT * FROM " + FilmDataContract.FilmEntry.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
public void deleteAll() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(FilmDataContract.FilmEntry.TABLE_NAME, null, null);
}
public boolean contentDelete(String filmName) {
boolean result = false;
String selection = "title = \"" + filmName + "\"";
int rowsDeleted = myCR.delete(FilmProvider.CONTENT_URI,
selection, null);
if (rowsDeleted > 0)
result = true;
return result;
}
public Film contentFindFilm(String filmName) {
String[] projection = FilmDataContract.FilmEntry.COLUMNS;
String selection = "title = \"" + filmName + "\"";
Cursor cursor = myCR.query(FilmProvider.CONTENT_URI,
projection, selection, null,
null);
Film film = new Film();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
film.setId(Integer.parseInt(cursor.getString(0)));
film.setTitle(cursor.getString(1));
film.setRating(cursor.getString(2));
film.setRuntime(cursor.getString(3));
film.setCritics(cursor.getString(4));
film.setAudience(cursor.getString(5));
film.setSynopsis(cursor.getString(6));
film.setProfile(cursor.getString(7));
cursor.close();
} else {
film = null;
}
return film;
}
public void contentAddFilm(Film film) {
ContentValues values = new ContentValues();
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_TITLE, film.getTitle());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RATING, film.getRating());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_RUNTIME, film.getRuntime());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_CRITICS, film.getCritics());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_AUDIENCE, film.getAudience());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_SYNOPSIS, film.getSynopsis());
values.put(FilmDataContract.FilmEntry.COLUMN_FILM_PROFILE, film.getProfile());
myCR.insert(FilmProvider.CONTENT_URI, values);
}
This is my stack trace... Seems to be happening when I am passing the context.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference
at com.purewowstudio.topmovies.data.DatabaseHelper.<init>(DatabaseHelper.java:25)
at com.purewowstudio.topmovies.util.getFilms.sortData(getFilms.java:48)
at com.purewowstudio.topmovies.util.getFilms.doInBackground(getFilms.java:43)
at com.purewowstudio.topmovies.util.getFilms.doInBackground(getFilms.java:16)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
DatabaseHelper dbHelper = new DatabaseHelper(mContext, null, null, 1);
mContext is null, because you never assign a value to it.
Is it possible to write APN programmatically on Android 4.4?
I noticed that the Telephony.Carriers is available for API level 19.
I have a software with APN write feature. Since Android 4.0 you can write APN settings only if you have system permissions. My software was designed to be a system software, so I can write APN and other settings. But, this feature is no longer working in Android 4.4 and I don't know why yet.
After read the Telephony.Carriers class, I could not find a new way to write APN. It's just a class to tell you informations but can't change them.
My code to write APN is:
public class APN {
public static final int AUTH_TYPE_UNKNOW = -1;
public static final int AUTH_TYPE_NONE = 0;
public static final int AUTH_TYPE_PAP = 1;
public static final int AUTH_TYPE_CHAP = 2;
public static final int AUTH_TYPE_PAP_OR_CHAP = 3;
private int id;
private String name;
private String user;
private String password;
private String apn;
private String mcc;
private String mnc;
private String type;
private String server;
private String proxy;
private String port;
private String mmsProxy;
private String mmsPort;
private String mmsc;
private String current;
private int authType;
public APN() {
id = -1;
name = "";
user = "";
password = "";
apn = "";
mcc = "";
mnc = "";
type = "default,supl";
server = "";
proxy = "";
port = "";
mmsProxy = "";
mmsPort = "";
mmsc = "";
current = "";
authType = AUTH_TYPE_NONE;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getApn() {
return apn;
}
public void setApn(String apn) {
this.apn = apn;
}
public String getMcc() {
return mcc;
}
public void setMcc(String mcc) {
this.mcc = mcc;
}
public String getMnc() {
return mnc;
}
public void setMnc(String mnc) {
this.mnc = mnc;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public String getProxy() {
return proxy;
}
public void setProxy(String proxy) {
this.proxy = proxy;
}
public String getMmsProxy() {
return mmsProxy;
}
public void setMmsProxy(String mmsProxy) {
this.mmsProxy = mmsProxy;
}
public String getMmsPort() {
return mmsPort;
}
public void setMmsPort(String mmsPort) {
this.mmsPort = mmsPort;
}
public String getMmsc() {
return mmsc;
}
public void setMmsc(String mmsc) {
this.mmsc = mmsc;
}
public String getCurrent() {
return current;
}
public void setCurrent(String current) {
this.current = current;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public int getAuthType() {
return authType;
}
public void setAuthType(int authType) {
this.authType = authType;
}
}
and:
public class APNUtils {
private static final Uri APN_TABLE_URI = Uri.parse("content://telephony/carriers");
private static final Uri APN_PREFER_URI = Uri.parse("content://telephony/carriers/preferapn");
private static ContentValues prepareValues(APN apn) {
ContentValues values = new ContentValues();
if (!apn.getName().trim().equals(""))
values.put("name", apn.getName());
if (!apn.getApn().trim().equals(""))
values.put("apn", apn.getApn());
if (!apn.getMcc().trim().equals(""))
values.put("mcc", apn.getMcc());
if (!apn.getMnc().trim().equals(""))
values.put("mnc", apn.getMnc());
if (!apn.getMcc().trim().equals("") && !apn.getMnc().trim().equals(""))
values.put("numeric", apn.getMcc() + apn.getMnc());
if (!apn.getUser().trim().equals(""))
values.put("user", apn.getUser());
if (!apn.getPassword().trim().equals(""))
values.put("password", apn.getPassword());
if (!apn.getServer().trim().equals(""))
values.put("server", apn.getServer());
if (!apn.getProxy().trim().equals(""))
values.put("proxy", apn.getProxy());
if (!apn.getPort().trim().equals(""))
values.put("port", apn.getPort());
if (!apn.getMmsProxy().trim().equals(""))
values.put("mmsproxy", apn.getMmsProxy());
if (!apn.getMmsPort().trim().equals(""))
values.put("mmsport", apn.getMmsPort());
if (!apn.getMmsc().trim().equals(""))
values.put("mmsc", apn.getMmsc());
if (!apn.getType().trim().equals(""))
values.put("type", apn.getType());
if (!apn.getCurrent().trim().equals(""))
values.put("current", apn.getCurrent());
values.put("authtype", apn.getAuthType());
return values;
}
public static int createNewApn(Context context, APN apn, boolean setAsDefaultAPN) {
Logs.infoLog("APNutils.createNewApn.");
int apnid = -1;
try {
if (apn != null) {
Logs.infoLog("APNutils.createNewApn. Reading APN list.");
Uri APN_URI = Uri.parse("content://telephony/carriers");
ContentResolver resolver = context.getContentResolver();
Logs.infoLog("APNutils.createNewApn. Creating new registry based on parameters.");
ContentValues values = prepareValues(apn);
Logs.infoLog("APNutils.createNewApn. Inserting new APN.");
Cursor c = null;
Uri newRow = resolver.insert(APN_URI, values);
if(newRow != null) {
Logs.infoLog("APNutils.createNewApn. Getting new ID.");
c = resolver.query(newRow, null, null, null, null);
int tableIndex = c.getColumnIndex("_id");
c.moveToFirst();
apnid = c.getShort(tableIndex);
} else
Logs.warningLog("APNutils.createNewApn. New APN was not found. Inserting failed?");
if(c != null){
c.close();
}
if (apnid > -1 && setAsDefaultAPN) {
Logs.infoLog("APNutils.createNewApn. Setting new APN as default.");
ContentValues v = new ContentValues(1);
v.put("apn_id", apnid);
context.getContentResolver().update(APN_PREFER_URI, v, null, null);
}
} else
Logs.warningLog("APNutils.createNewApn. Invalid apn (null).");
} catch (Exception e) {
Logs.errorLog("createNewApn: error", e);
}
Logs.infoLog("APNutils.createNewApn. Returning ID " + String.valueOf(apnid));
return apnid;
}
public static boolean updateApn(Context context, int id, APN apn) {
Logs.infoLog("APNutils.updateApn.");
if (apn != null) {
try {
Logs.infoLog("APNutils.updateApn. Reading APN list.");
Uri APN_URI = Uri.parse("content://telephony/carriers");
ContentResolver resolver = context.getContentResolver();
Logs.infoLog("APNutils.updateApn. Creating new registry based on parameters.");
ContentValues values = prepareValues(apn);
Logs.infoLog("APNutils.updateApn. Inserting new APN.");
int result = resolver.update(APN_URI, values, "_id = " + String.valueOf(id), null);
if (result != -1) {
Logs.infoLog("APNutils.updateApn. APN updated.");
return true;
} else {
Logs.warningLog("APNutils.updateApn. Invalid ID (" + String.valueOf(id) + ").");
return false;
}
} catch (Exception e) {
Logs.errorLog("APNUtils.updateApn error: ", e);
return false;
}
} else {
Logs.warningLog("APNutils.updateApn. Invalid apn (null).");
return false;
}
}
public static boolean verifyApn(Context context, String apn) {
Logs.infoLog("APNutils.verifyApn.");
return getApn(context, apn) > -1;
}
public static int getApn(Context context, String apn) {
Logs.infoLog("APNutils.getApn.");
int result = -1;
Logs.infoLog("APNutils.getApn. Looking for APN " + apn);
String columns[] = new String[] { "_ID", "NAME" };
String where = "name = ?";
String wargs[] = new String[] { apn };
String sortOrder = null;
Cursor cur = context.getContentResolver().query(APN_TABLE_URI, columns, where, wargs, sortOrder);
if (cur != null) {
int tableIndex = cur.getColumnIndex("_id");
if (cur.moveToFirst()) {
Logs.infoLog("APNutils.getApn. APN found.");
result = cur.getShort(tableIndex);
}
cur.close();
}
if (result == -1)
Logs.warningLog("APNutils.getApn. APN not found.");
return result;
}
public static boolean setPreferredApn(Context context, String apn) {
Logs.infoLog("APNutils.setPreferredApn.");
boolean changed = false;
Logs.infoLog("APNutils.setPreferredApn. Looking for APN " + apn);
String columns[] = new String[] { "_ID", "NAME" };
String where = "name = ?";
String wargs[] = new String[] { apn };
String sortOrder = null;
Cursor cur = context.getContentResolver().query(APN_TABLE_URI, columns, where, wargs, sortOrder);
if (cur != null) {
if (cur.moveToFirst()) {
Logs.infoLog("APNutils.setPreferredApn. APN found. Setting as default.");
ContentValues values = new ContentValues(1);
values.put("apn_id", cur.getLong(0));
if (context.getContentResolver().update(APN_PREFER_URI, values, null, null) == 1) {
Logs.infoLog("APNutils.setPreferredApn. APN marked as default.");
changed = true;
}
}
cur.close();
}
if (!changed)
Logs.warningLog("APNutils.setPreferredApn. APN not found or could not be marked as default.");
return changed;
}
public static APN[] getAllApnList(Context context) {
Logs.infoLog("APNutils.getAllApnList.");
APN[] result = null;
Uri contentUri = Uri.parse("content://telephony/carriers/");
Cursor cursor = null;
try
{
cursor = context.getContentResolver().query(contentUri,
new String[] {"_ID", "name", "apn", "mcc", "mnc", "numeric", "user", "password", "server", "proxy",
"port", "mmsproxy", "mmsport", "mmsc", "type", "current", "authtype "}, null, null, null);
if (cursor != null)
{
result = new APN[cursor.getCount()];
int i = 0;
while (cursor.moveToNext())
{
APN apn = new APN();
apn.setId(cursor.getInt(0));
apn.setName(cursor.getString(1));
apn.setApn(cursor.getString(2));
apn.setMcc(cursor.getString(3));
apn.setMnc(cursor.getString(4));
apn.setUser(cursor.getString(6));
apn.setPassword(cursor.getString(7));
apn.setServer(cursor.getString(8));
apn.setProxy(cursor.getString(9));
apn.setPort(cursor.getString(10));
apn.setMmsProxy(cursor.getString(11));
apn.setMmsPort(cursor.getString(12));
apn.setMmsc(cursor.getString(13));
apn.setType(cursor.getString(14));
apn.setCurrent(cursor.getString(15));
apn.setAuthType(cursor.getInt(16));
result[i] = apn;
i++;
}
}
}
catch (Exception ex)
{
//Handle exceptions here
return null;
}
finally
{
if (cursor != null)
cursor.close();
}
return result;
}
}
I am trying to search an item in sqlite by using String, & trying to return description contained in that row. items are stored in the table named Articles with column name A_name, Description column name is AS_name
This is my code, the cursor is not null, but the while loop is not getting executed once
public String searchData(String text)
{
Cursor cursor = sdb.query("Articles", new String[] {"A_name","AS_name"}, " A_name=?",new String[]{text}, null, null, null);
Log.e("running", "cursor run");
String temp = null,temp2 = null;
if(cursor!=null)
{
Log.e("running", "curosr is not null");
while(cursor.moveToFirst())
{
Log.e("running", "curosr while loop enter");
temp = (cursor.getString(cursor.getColumnIndex("A_name")));
//temp2 =(cursor.getString(cursor.getColumnIndex("AS_name")));
Log.e("running", "id email" +temp+ " name"+temp2);
}
}
return temp;
}
I want to return the corresponding element of AS_name, also I am confused what should I wrote in while loop ?
Can anyone please identify my mistake, Thanks in advance...
UPDATE DBAdapter.java
public class DBAdapter extends SQLiteOpenHelper
{
//CustomAdapter adapter;
static String name = "law6.sqlite";
static String path = "";
static ArrayList<GS> gs;
static SQLiteDatabase sdb;
#Override
public void onCreate(SQLiteDatabase db)
{
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
}
private DBAdapter(Context v)
{
super(v, name, null, 1);
path = "/data/data/" + v.getApplicationContext().getPackageName() + "/databases";
}
public boolean checkDatabase()
{
SQLiteDatabase db = null;
try
{
db = SQLiteDatabase.openDatabase(path + "/" + name, null, SQLiteDatabase.OPEN_READONLY);
} catch (Exception e)
{
e.printStackTrace();
}
if (db == null)
{
return false;
}
else
{
db.close();
return true;
}
}
public static synchronized DBAdapter getDBAdapter(Context v)
{
return (new DBAdapter(v));
}
public void createDatabase(Context v)
{
this.getReadableDatabase();
try
{
InputStream myInput = v.getAssets().open(name);
// Path to the just created empty db
String outFileName = path +"/"+ name;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0)
{
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
/*
InputStream is = v.getAssets().open("quiz.sqlite");
// System.out.println(is.available());
System.out.println(new File(path + "/" + name).getAbsolutePath());
FileOutputStream fos = new FileOutputStream(path + "/" + name);
int num = 0;
while ((num = is.read()) > 0) {
fos.write((byte) num);
}
fos.close();
is.close();*/
} catch (IOException e)
{
System.out.println(e);
}
}
public void openDatabase()
{
try
{
sdb = SQLiteDatabase.openDatabase(path + "/" + name, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (Exception e)
{
System.out.println(e);
}
}
public ArrayList<GS> getData()
{
try{
Cursor c1 = sdb.rawQuery("SELECT DISTINCT * FROM Articles", null);
gs = new ArrayList<GS>();
while (c1.moveToNext())
{
GS q1 = new GS();
q1.setId(c1.getString(0));
q1.setA_id(c1.getString(1));
q1.setA_name(c1.getString(2));
q1.setAS_name(c1.getString(3));
q1.setDesc_art(c1.getString(4));
// q1.setAct(c1.getString(5));
q1.setExtra(c1.getString(6));
q1.setPart(c1.getString(7));
q1.setItalic(c1.getString(8));
Log.v("AS_name",q1.AS_name);
gs.add(q1);
}
}
catch (Exception e) {
e.printStackTrace();
}
return gs;
}
public String searchData(String text)
{
Cursor cursor = sdb.query("Articles", new String[] {"A_name","AS_name"}, " A_name=?",new String[]{text}, null, null, null);
Log.e("running", "cursor run");
String temp = null,temp2 = null;
if(cursor!=null)
{
Log.e("running", "curosr is not null");
Log.v("", ""+cursor.getCount());
while(cursor.moveToNext())
{
Log.e("running", "curosr while loop enter");
temp = (cursor.getString(cursor.getColumnIndex("AS_name")));
// temp2 =(cursor.getString(cursor.getColumnIndex(name)));
Log.e("running", "desc" +temp);
}
}
return temp;
}
}
UPDATE after implementing rajaji answer, I got this error :
try this it will help you
create the raw query for getting the data
public String searchData(String text)
{
String strvalue=null;
SQliteDatabase db=this.getwritabledatabase();
Cursor cur=null;
String strquery="select * from youurtablename where A_name="+text;
cur=db.rawQuery(strquery,null);
if(cur!=null&&cur.moveToFirst())
{
do
{
strvalue=cur.getString(0);
}
while(cur.moveToNext());
}
}
let me inform once you complete
Is your Uri correct??
create Uri depends on your package name and table name, like the code below :
private static final String AUTHORITY = "com.sample.test_db_provider";
private static final String BASE_PATH = "Tables";
private static final Uri Sample_URI = Uri.parse("content://" + AUTHORITY
+ "/" + BASE_PATH
+ "/SampleTable");
Then in your get Method, query the db like the below code with Uri
cur = m_Resolver.query(Sample_URI, new String[] {"A_name","AS_name"},
"SampleTable.A_name = " + text, null, null);
if(cur != null && cur.moveToFirst())
{
do
{
...
}
while(cur.moveToNext());
}
cur.close();
I use the inline where clause but you can do it your way with a parameter. Is this what you are looking for?
sorry im kind of a beginner,
I have a simple app that stores data on one page and fetches it on another. i keep getting an error when i try and fetch the data, stating that no such column could be found. please help
this is my code from where i enter the data,
EnterDetails.java
#Override
public void onClick(View arg0) {
EditText holdersala = (EditText) findViewById(R.id.rawsalary);
EditText wantspercentage = (EditText) findViewById(R.id.wantspercent);
EditText needspercentage = (EditText) findViewById(R.id.needspercent);
String holdersalary = holdersala.getText().toString();
final int salary = Integer.parseInt(holdersalary);
String holderwantsp = wantspercentage.getText().toString();
final int wantsp = Integer.parseInt(holderwantsp);
String holderneedsp = needspercentage.getText().toString();
final int needsp = Integer.parseInt(holderneedsp);
if(wantsp + needsp <= 100){
DatabaseAdapter databaseAdapter = new DatabaseAdapter(getApplicationContext());
databaseAdapter.open();
databaseAdapter.createRecordS(salary);
databaseAdapter.createRecordW(wantsp);
databaseAdapter.createRecordN(needsp);
databaseAdapter.close();
startActivity(new Intent(EnterDetails.this, Summary.class));
} else {
}
Toast toast = Toast.makeText(EnterDetails.this, "incorrect data", 5000);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
code from where i fetch the data
TextView bn = (TextView) findViewById(R.id.budget_need);
DatabaseAdapter databaseAdapter = new DatabaseAdapter(getApplicationContext());
databaseAdapter.open();
bn.setText(databaseAdapter.fetchRecordS(1));
databaseAdapter.close();
and code from my databaseAdapter.java
public class DatabaseAdapter {
private Context context;
private SQLiteDatabase database;
private DatabaseOpenHelper dbHelper;
public DatabaseAdapter(Context context) {
this.context = context;
}
public DatabaseAdapter open() throws SQLException {
dbHelper = new DatabaseOpenHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
public long createRecordS(int interger) {
ContentValues contentValue = new ContentValues();
contentValue.put("salafig", interger);
return database.insert("maindata", null, contentValue);
}
public long createRecordN(int interger) {
ContentValues contentValue = new ContentValues();
contentValue.put("needsper", interger);
return database.insert("maindata", null, contentValue);
}
public long createRecordW(int interger) {
ContentValues contentValue = new ContentValues();
contentValue.put("wantsper", interger);
return database.insert("maindata", null, contentValue);
}
public int fetchRecordS(long rowId) throws SQLException {
Cursor mCursor = database.query(true, "maindata", new String[] { "salafig",
"needsper", "wantsper" }, "salafig"+ rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
return (mCursor.getInt(1));
}
return (Integer) null;
}
public int fetchRecordW(long rowId) throws SQLException {
Cursor mCursor = database.query(true, "maindata", new String[] { "salafig",
"needsper", "wantsper" }, "wantsper"+ rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
return (mCursor.getInt(1));
}
return (Integer) null;
}public int fetchRecordN(long rowId) throws SQLException {
Cursor mCursor = database.query(true, "maindata", new String[] { "salafig",
"needsper", "wantsper" }, "needsper"+ rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
return (mCursor.getInt(1));
}
hope it makes sense thanks if advance for any help.
Look at HEREto check the correct syntax of the SQLiteDatabase query method.
The forth parameter of the method is the selection condition, it s supposed to be something like:
"salafig = "+ rowId"
instead of this :
"salafig"+ rowId"
I need to display data from 4 different database tables in android. Previously for testing I used single table to display data. For that I have created three files.
1)DBAdapter.java
2)UserBO.java
3)Test.java
DBAdapter.java
public class DBAdapter extends SQLiteOpenHelper {
private static String DB_PATH = "";
private static final String DB_NAME = "mydb.sqlite";
private SQLiteDatabase myDataBase1;
private final Context myContext1;
private static DBAdapter mDBConnection;
private DBAdapter(Context context) {
super(context, DB_NAME, null, 1);
this.myContext1 = context;
DB_PATH = "/data/data/"
+ context.getApplicationContext().getPackageName()
+ "/databases/";
}
public static synchronized DBAdapter getDBAdapterInstance(Context context) {
if (mDBConnection == null) {
mDBConnection = new DBAdapter(context);
}
return mDBConnection;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
// By calling following method
// 1) an empty database will be created into the default system path of your application
// 2) than we overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext1.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
myDataBase1 = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
#Override
public synchronized void close() {
if (myDataBase1 != null)
myDataBase1.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor selectRecordsFromDB(String tableName, String[] tableColumns,
String whereClase, String whereArgs[], String groupBy,
String having, String orderBy) {
return myDataBase1.query(tableName, tableColumns, whereClase, whereArgs,
groupBy, having, orderBy);
}
public ArrayList<ArrayList<String>> selectRecordsFromDBList(String tableName, String[] tableColumns,
String whereClase, String whereArgs[], String groupBy,
String having, String orderBy) {
ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = myDataBase1.query(tableName, tableColumns, whereClase, whereArgs,
groupBy, having, orderBy);
if (cursor.moveToFirst()) {
do {
list = new ArrayList<String>();
for(int i=0; i<cursor.getColumnCount(); i++){
list.add( cursor.getString(i) );
}
retList.add(list);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return retList;
}
public Cursor selectRecordsFromDB(String query, String[] selectionArgs) {
return myDataBase1.rawQuery(query, selectionArgs);
}
public ArrayList<ArrayList<String>> selectRecordsFromDBList(String query, String[] selectionArgs) {
ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = myDataBase1.rawQuery(query, selectionArgs);
if (cursor.moveToFirst()) {
do {
list = new ArrayList<String>();
for(int i=0; i<cursor.getColumnCount(); i++){
list.add( cursor.getString(i) );
}
retList.add(list);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return retList;
}
}
**UserBO.java**
public class UserBO {
int sid;
String sname;
public int getsid() {
return sid;
}
public void setsid(int sid) {
this.sid = sid;
}
public String getsname() {
return sname;
}
public void setsname(String sname) {
this.sname= sname;
}
}
Test.java
public class Select extends Activity {
private Header header;
private ListView lvUsers;
private ArrayList<UserBO> mListUsers;
private SharedPreferences mPreferences1;
private SharedPreferences mPreferences2;
String myString1,query;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("before k select "+k);
setContentView(R.layout.select);
header = (Header) findViewById(R.id.layoutHeader);
mListUsers = getUsers();
lvUsers = (ListView) findViewById(R.id.lv_user);
lvUsers.setAdapter(new ListAdapter(this, R.id.lv_user, mListUsers));
}
public ArrayList<UserBO> getUsers(){
DBAdapter dbAdapter=DBAdapter.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
mPreferences1 = getSharedPreferences("CurrentUser1", 0);
myString1 = mPreferences1.getString("student id",sid);
dbAdapter.openDataBase();
**query="SELECT tabel1.*, tabel2.* FROM tabel1, tabel2 WHERE tabel1.PK=tabel2.FK;";**
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();
ArrayList<UserBO> usersList = new ArrayList<UserBO>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
UserBO user = new UserBO();
AppConstants.alConductedQuestions.add(user);
System.out.println("mListUsers");
System.out.println(user);
try {
user.sid = Integer.parseInt(list.get(0));
user.sname = list.get(1);
}
catch (Exception e) {
Log.i("***" + Test.class.toString(), e.getMessage());
}
usersList.add(user);
}
return usersList;
}
// ***ListAdapter***
private class ListAdapter extends ArrayAdapter<UserBO> { // --CloneChangeRequired
private ArrayList<UserBO> mList; // --CloneChangeRequired
private Context mContext;
public ListAdapter(Context context, int textViewResourceId,ArrayList<UserBO> list) { // --CloneChangeRequired
super(context, textViewResourceId, list);
//System.out.println(list);
this.mList = list;
this.mContext = context;
}
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
try{
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.list_item, null);
// --CloneChangeRequired(list_item)
}
final UserBO listItem = mList.get(position); // --CloneChangeRequired
if (listItem != null) {
// setting list_item views
( (TextView) view.findViewById(R.id.casedescription) ).setText( listItem.getsid()+"");
( (TextView) view.findViewById(R.id.tv_question) ).setText( listItem.getsname()+"");
ArrayList<UserBO> mList1;
}
}
catch(Exception e){
String err = (e.getMessage()==null)?"hii":e.getMessage();
Log.e("sdcard-err2:",err);
}
return view;
}
}
}
In test.java I am writing the query. In UserBO I am writing the setter and getter methods. In DBAdapter file I am mentioning the database name. So here my question is I have 4 tables in my database. So I need to display data using those tables. Shall I write the setter and getter methods of the column names of all the tables in one single UserBO file?
Also I am getting the values of each column of single table by giving
user.sid = Integer.parseInt(list.get(0));
user.sname = list.get(1);
*How do I get the column names of all the tables?* I mean shall I need to get all the columns of all the tables in Test.java file?
Please help me regarding this....I am it confused with this different tables.....
Thanks in Advance
you have one database & three tables or all three tables are in different databsaes ?