Using method from another class containing Cursor - android

Working on developing a Class for my android app that will randomly generate NPCs and their stats. Since these methods will be called in different activities figured putting them in their own class would be best. Yet having some trouble getting the cursors they contain to work correctly.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
public class startscreen extends Activity {
private dbhelper mydbhelper;
Intent intent;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startscreen);
mydbhelper = dbhelper.getInstance(startscreen.this);
}
public void onClickNew(View v){
intent = new Intent(getBaseContext(), newgame.class);
startActivity(intent);
}
public void onClickLoad(View v){
//intent = new Intent(getBaseContext(), mainmenu.class);
//startActivity(intent);
Generator obj = new Generator();
obj.randomName();
}
I am calling the method on this bottom button to my main menu for easy testing.
import java.util.Random;
import android.database.Cursor;
import android.util.Log;
public class Generator {
public dbhelper mydbhelper;
public String randomName(){
Cursor name;
Random nameRandom = new Random();
int first = nameRandom.nextInt(171)+1;
name = mydbhelper.getRandomName(first); //This is where I get the error. "NullPointerException"
String firstName = name.getString(name.getColumnIndex(dbhelper.KEY_FIRST));
int last = nameRandom.nextInt(245)+1;
name = mydbhelper.getRandomName(last);
String lastName = name.getString(name.getColumnIndex(dbhelper.KEY_LAST));
String fullName = firstName + " " + lastName;
Log.e(fullName, "was the generated name");
return fullName;
}
}
If I take out the cursors and put in a stat string to return it works fine. So I'm handling this cursors incorrectly. Sadly Singleton and using methods from other classes is on of my short comings so hoping someone here will be able to explain what I'm doing wrong.
public Cursor getRandomName(int number){
return myDataBase.query(NAME_TABLE, new String[]{KEY_ID, KEY_FIRST, KEY_LAST},
KEY_ID + " = " + number , null, null, null, KEY_ID);
}
This is the cursor I'm working with, located in my dbhelper class.

mydbhelper in your Activity class is a different reference than the mydbhelper in your Generator class. You need to call mydbhelper = dbhelper.getInstance() in your Generator class or pass in the reference before you use it.
A quick way to do it would be:
public String randomName(dbhelper mydbhelp) {
// code
name = mydbhelper.getRandomName(first);
// code
name.close
}
Remember to close both your cursor and your database when you're done with it. Close the Cursor first.

Related

Package has already posted 50 toasts. Not showing more

Hello I am working on an app and in which at one point I need to take input from user and store it in database and then fetch that data and put it on different TextView. Problem is I did stored the data in database and when i trying to fetch it My app shows a pop up i.e : App is not responding and logcat shows this:
Package has already posted 50 toasts. Not showing more.
I have used 6 database operations before this pullAccStt can this be a problem.
DatabseAdapotor
public long updateAccSettTable(String loactionName, String hospitalname, String PatientId, String FirstName, String MiddleName, String LastName, String DOB,
String Gender, String Weight, String Height, String MobNo, String emailId, String Ethinicity, String patientConcentStatus, String DevicePatientId,
String CoSensorId, String DeviceId, String VideoId){
SQLiteDatabase db= helper.getWritableDatabase();
ContentValues contentValuesAccSett= new ContentValues();
contentValuesAccSett.put(DatabaseHelper.PatientId,PatientId);
contentValuesAccSett.put(DatabaseHelper.LocationName,loactionName);
contentValuesAccSett.put(DatabaseHelper.HospitalName,hospitalname);
contentValuesAccSett.put(DatabaseHelper.FirstName,FirstName);
contentValuesAccSett.put(DatabaseHelper.MiddleName,MiddleName);
contentValuesAccSett.put(DatabaseHelper.LastName,LastName);
contentValuesAccSett.put(DatabaseHelper.DateOfBirth,DOB);
contentValuesAccSett.put(DatabaseHelper.Gender,Gender);
contentValuesAccSett.put(DatabaseHelper.Weight,Weight);
contentValuesAccSett.put(DatabaseHelper.Height,Height);
contentValuesAccSett.put(DatabaseHelper.MobileNo,MobNo);
contentValuesAccSett.put(DatabaseHelper.EmailId,emailId);
contentValuesAccSett.put(DatabaseHelper.Ethnicity,Ethinicity);
contentValuesAccSett.put(DatabaseHelper.P_ConsentStatus,patientConcentStatus);
contentValuesAccSett.put(DatabaseHelper.DevicePId,DevicePatientId);
contentValuesAccSett.put(DatabaseHelper.DeviceId,DeviceId);
contentValuesAccSett.put(DatabaseHelper.CoSensorId,CoSensorId);
contentValuesAccSett.put(DatabaseHelper.VideoId,VideoId);
long id1= db.insert(DatabaseHelper.Accoun_setting_Table,null,contentValuesAccSett);
if (id1<0){
Message.message(helper.context,"Unsuccessfull");
}else {
Message.message(helper.context,"Account setting Updated");
}
db.close();
return id1;
}
public String pullAccSett(){
String patientId = null;
Message.message(helper.context,"patient id is: ");
SQLiteDatabase db=helper.getWritableDatabase();
String query="Select * From "+DatabaseHelper.Accoun_setting_Table+" ;";
Cursor AccCursor=db.rawQuery(query,null);
Message.message(helper.context,"query "+query);
while(AccCursor.moveToFirst()) {
int index1 = AccCursor.getColumnIndex(DatabaseHelper.PatientId);
patientId=AccCursor.getString(index1);
}
AccCursor.close();
db.close();
return patientId ;
}
Activity Class calling this
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class AccountSettingFragment extends Fragment {
FloatingActionButton fabEdit;
DatabaseAdaptor databaseAdaptor=null;
TextView PatientId;
private Context context;
public AccountSettingFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_account_setting, container, false);
fabEdit=(FloatingActionButton)view.findViewById(R.id.btnFabEdit);
PatientId=(TextView)view.findViewById(R.id.patientId);
context=getActivity();
databaseAdaptor=new DatabaseAdaptor(context);
databaseAdaptor.pullAccSett();
fabEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), AccountsSettingEdit.class);
getActivity().startActivity(intent);
}
});
return view;
}
}
Message Class
import android.content.Context;
import android.widget.Toast;
/**
* Created by frnds on 3/2/2016.
*/
public class Message {
public static void message(Context context,String message){
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}
}
And when i call this pullAccSett(); my app hangs and goes to not responding.
and log cat shows message:
Package has already posted 50 toasts. Not showing more.
What is the reason behind this.
Your while loop i thinks will runs for infinite time. because every time it will be true and you have no break statement.
so change your code like this.
try {
if (AccCursor.moveToFirst()) {
while (AccCursor.moveToNext()) {
//code for fetch data from cursor
}
}
AccCursor.close();
}catch (Exception e) {
Log.e("Getdata", e.getMessage(), e);
}
There is some enhancement for the code above. If cursor is in position -1, AccCursor.moveToNext will move it to position 0, so you can do better something like:
try {
while(AccCursor.moveToNext()) {
//Execute code
}
AccCursor.close();
}catch(final Exception lException) {
Log.e("Getdata", "Exception looping Cursor: " + lException.getMessage());
}

Why am I getting this context and database error?

I am trying to...
create a simple listview that can be populated with data from an sqldatabase. The database works, I've seen it work with other code. The XML is fine and I really don't need to share it. When it comes to the XML, there is two buttons in the main activity: new and show. New sends you to the next activity to add to the list. Show will add data to the listview. That's all for the main activity. The other activity called NewEntry has a cancel button and a save button. It also has three editviews to help you add data.
Problems:
Right now it doesn't even compile without errors. The two errors are listed below in the main activity. If I comment out those two errors, I can get the application to run. when I open a new activity and try to save it, it crashes. They have to do with Context. I only sort of understand what Context does besides the fact that it is in everything.
This error has been solved see the bottom
The two compiler errors are in this code here. This is the main activity.
There are no other compiler errors, just logical ones.
I have pointed them out in the comments
""DATA BASE MANAGER CANNOT BE APPLIED TO LISTENER""
"CANNOT RESOLVE CONSTRUCTOR"
Also any explanations of Context will be appreciated.
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
public class Main extends Activity {
private DatabaseManager mydManager;
private ListView productRec;
ArrayList<String> tableContent;
private LinearLayout addLayout;
ArrayList<String> arrayAdpt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
productRec=(ListView)findViewById(R.id.list);
Button newButton = (Button) findViewById(R.id.new_button);
Button showButton = (Button) findViewById(R.id.show_button);
Button newButton = (Button) findViewById(R.id.new_button);
newButton.setOnClickListener(new OnClickListener() {
public void onClick(View n) {
Intent x = new Intent(Main.this.getApplicationContext(), NewEntry.class);
startActivity(x);
}
});
showButton.setOnClickListener(new OnClickListener() { //Want this to launch new intent
public void onClick(View s) {
mydManager = new DatabaseManager(this); // <ERROR:
mydManager.openReadable(); //"DATA BASE MANAGER CANNOT BE APPLIED TO LISTENER"
tableContent = mydManager.retrieveRows();
productRec = (ListView)findViewById(R.id.list);
mydManager.retrieveRows(); //ERROR:
ArrayAdapter<String> arrayAdpt=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tableContent); //ERROR:CANNOT RESOLVE CONSTRUCTOR
productRec.setAdapter(arrayAdpt);
productRec.setVisibility(View.VISIBLE);
mydManager.close();
}
});
}
}
This is the NewEntry java class:
import android.content.Context;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
public class NewEntry extends Activity {
// public static final int REQUEST_CODE = 1;
private EditText titleView;
private EditText authorView;
private EditText priceView;
private Button doneButton;
private Button cancelButton;
private DatabaseManager mydManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit);
titleView = (EditText) findViewById(R.id.title_input);
authorView = (EditText) findViewById(R.id.author_input);
priceView = (EditText) findViewById(R.id.price_input);
doneButton = (Button) findViewById(R.id.done_button);
cancelButton = (Button) findViewById(R.id.cancel_button);
Intent i = this.getIntent();
//rec inserted, its a boolean in the other one
doneButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
mydManager = new DatabaseManager(NewEntry.this);
mydManager.addRow(Integer.parseInt(titleView.getText().toString()), authorView.getText().toString(),
Float.parseFloat(priceView.getText().toString())); ///sending in back to database
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.hideSoftInputFromWindow(priceView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
mydManager.close();
titleView.setText("");
authorView.setText(""); //SOMETHING TO DO WITH DATA? maybe its blanking it out
priceView.setText("");
finish();
}
});
cancelButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
This is the database:
import android.database.sqlite.SQLiteDatabase;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
public class DatabaseManager {
public static final String DB_NAME = "shopping";
public static final String DB_TABLE = "products";
public static final int DB_VERSION = 1;
private static final String CREATE_TABLE = "CREATE TABLE " + DB_TABLE + " (code INTEGER PRIMARY KEY, product_name TEXT, date FLOAT);";
private SQLHelper helper;
private SQLiteDatabase db;
private Context context;
public DatabaseManager(Context c){
this.context = c;
helper=new SQLHelper(c);
this.db = helper.getWritableDatabase();
}
public DatabaseManager openReadable() throws android.database.SQLException {
helper=new SQLHelper(context);
db = helper.getReadableDatabase();
return this;
}
public void close(){
helper.close();
}
public boolean addRow(int t, String a, float p){
ContentValues newProduct = new ContentValues();
newProduct.put("title", t);
newProduct.put("author", a);
newProduct.put("price", p);
try{db.insertOrThrow(DB_TABLE, null, newProduct);}
catch(Exception e) {
Log.e("Error in inserting rows ", e.toString());
e.printStackTrace();
return false;
}
db.close();
return true;
}
public ArrayList<String> retrieveRows(){ ///Retrieves edit
ArrayList<String> productRows=new ArrayList<String>();
String[] columns = new String[]{"title", "author", "price"};
Cursor cursor = db.query(DB_TABLE, columns, null, null, null, null, null);
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
productRows.add(Integer.toString(cursor.getInt(0)) + ", "+cursor.getString(1)+", "+Float.toString(cursor.getFloat(2)));
cursor.moveToNext();
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return productRows;
}
public class SQLHelper extends SQLiteOpenHelper {
public SQLHelper(Context c){
super(c, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Products table","Upgrading database i.e. dropping table and recreating it");
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
onCreate(db);
}
}
}
Error when trying to retrieve rows:
04-11 22:08:25.552 21767-21767/com.example.alex.checkbox W/dalvikvm? threadid=1: thread exiting with uncaught exception (group=0x41e7cda0)
04-11 22:08:25.572 21767-21767/com.example.alex.checkbox E/AndroidRuntime? FATAL EXCEPTION: main
Process: com.example.alex.checkbox, PID: 21767
android.database.sqlite.SQLiteException: no such column: title (code 1): , while compiling: SELECT title, author, price FROM products
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:690)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1448)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1295)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1166)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1334)
at com.example.alex.favoritebooks.DatabaseManager.retrieveRows(DatabaseManager.java:56)
at com.example.alex.favoritebooks.Main$2.onClick(Main.java:45)
at android.view.View.performClick(View.java:4654)
at android.view.View$PerformClick.run(View.java:19438)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5487)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
In your newButton.setOnClickListener(...) code you are using the application Context when creating your Intent. Don't do that - instead use the Activity Context...
newButton.setOnClickListener(new OnClickListener() {
public void onClick(View n) {
// Simply use Main.this on the next line...
Intent x = new Intent(Main.this, NewEntry.class);
startActivity(x);
}
});
In your showButton.setOnClickListener(...) code you are passing a reference to the OnClickListener object to the constructor of your DatabaseManager and also when creating your ArrayAdapter...
showButton.setOnClickListener(new OnClickListener() {
public void onClick(View s) {
mydManager = new DatabaseManager(this); //Here is the error
...
ArrayAdapter<String> arrayAdpt=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tableContent);
...
}
});
The this keyword refers to the current instance of any object which uses it - in this case, this refers to the OnClickListener which is not a Context. Also, as an aside, you're declaring a new ArrayAdapter variable in your OnClickListener code instead of using the one declared in the Activity. Change the code as follows...
showButton.setOnClickListener(new OnClickListener() {
public void onClick(View s) {
mydManager = new DatabaseManager(Main.this);
...
arrayAdpt = new ArrayAdapter<String>(Main.this, android.R.layout.simple_list_item_1, tableContent);
...
}
});

Fetch and display sqlite data through a List Adapter in a Fragment

I wish to show all the values in a database table in a list within a fragment. For this I'm using a custom list adapter to show values present in the cursor in a fragment list.
The fragment class is showing some constructor related error(which says the constructor is undefined) in my DatabaseHandler class and the adapter class.
I guess the error is due to the context variable that I've used in my Databasehandler class. And I think we need to declare some other variable type for fragments.
This will also help others in using custom list adapters and listview in a fragment as I hardly find any good tutorial over the net.
So when I create a new constructor like this is in my Handler class --
public Database_Schema(Fragment_Java fragment_Java) {
context = fragment_Java;
dbHelper = new DatabaseHelper(context);
}
the editor again complains to change the type of context to fragment_java.
Here's the DatabaseHandler class I'm using in my application:
package info.aea.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper{
// Called when no database exists in disk and the helper class needs
// to create a new one.
SQLiteDatabase sqldb;
public long r;
public void onCreate(SQLiteDatabase _db)
{
// _db.execSQL(LoginTable.DATABASE_CREATE);
// sqldb = this.getWritableDatabase();
}
/* public LoginDatabaseHelper(Context context, String name,CursorFactory factory, int version) {
super(context, name, factory, version);
}*/
public DatabaseHelper(Context context) {
super(context, "java.db", null, 1);
sqldb = this.getWritableDatabase();
try {
sqldb.execSQL("CREATE TABLE if not exists SourceCodes (CodeID text PRIMARY KEY NOT NULL , " +
"CodeLang text NOT NULL, CodeTitle text NOT NULL , CodeSource text NOT NULL , " +
"CodeOutput text NOT NULL);");
ContentValues cv = new ContentValues();
cv.put("CodeID", "t1");
cv.put("CodeLang", "java");
cv.put("CodeTitle", "title1");
cv.put("CodeSource", "source code here1");
cv.put("CodeOutput", "output here1");
r = sqldb.insert("SourceCodes", null, cv);
//ContentValues cv2 = new ContentValues();
cv.put("CodeID", "t2");
cv.put("CodeLang", "java");
cv.put("CodeTitle", "title2");
cv.put("CodeSource", "source code here2");
cv.put("CodeOutput", "output here2");
r = sqldb.insert("SourceCodes", null, cv);
} catch (Exception e) {
// TODO: handle exception
}
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
#Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + Database_Schema.DATABASE_CREATE);
// Create a new one.
onCreate(_db);
}
}
Below is the Class defining the database schema and containing CRUD operation methods related to the table --
package info.aea.database;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class Database_Schema {
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table "+" LOGIN "+
"( " +"ID"+" integer primary key autoincrement," + "USERNAME char unique,PASSWORD text, USERTYPE text); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DatabaseHelper dbHelper;
public Database_Schema(Context _context) {
context = _context;
dbHelper = new DatabaseHelper(context);
}
public Database_Schema open() throws SQLException {
db = dbHelper.getWritableDatabase();
return this;
}
public void close() {
db.close();
}
public SQLiteDatabase getDatabaseInstance(){
return db;
}
//---------------------CRUD Operations---------------------//
// get all query
public List<SourceCode_Table> getall(String lang) {
List<SourceCode_Table> codelist = new ArrayList<SourceCode_Table>();
String selectQuery = "SELECT * FROM SourceCodes where codelang='java'" ; // Select All Query
db = dbHelper.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to Vector
if (cursor.moveToFirst()) {
do {
SourceCode_Table a = new SourceCode_Table();
a.setCodeID(cursor.getString(0));
a.setCodeTitle(cursor.getString(1));
a.setCodeSource(cursor.getString(3));
a.setCodeOutput(cursor.getString(4));
codelist.add(a);
} while (cursor.moveToNext());
}
return codelist;
}
}
Also I wish to merge both these DB_related classes in a single DB_handler class. But it gives some weird errors or doesn't create a database if compiles without an error. Need a help in doing this also. I simply want to remove that extra class as it creates confusion while declaring DB schema and applying queries.
For the table named source codes I have made an adapter class. This is the list adapter class --
package info.aea.database;
import info.devey.java.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class SourceCode_Adapter extends ArrayAdapter<String> {
private final Context context;
private final String[] CodeID;
private final String[] CodeLang;
private final String[] CodeTitle;
private final String[] CodeSource;
private final String[] CodeOutput;
public SourceCode_Adapter(Context context, String[] codeid, String[] codelang, String[] codetitle, String[] codesource, String[] codeoutput) {
super(context, R.layout.list_items, codeid);
this.context = context;
this.CodeID = codeid;
this.CodeLang = codelang;
this.CodeTitle = codetitle;
this.CodeSource = codesource;
this.CodeOutput = codeoutput;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_items, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.tvPat);
String test=(" code ID: "+ CodeID[position]+ "\n code Language: "+ CodeLang[position]+ "\n Code Title: "+
CodeTitle[position]+ "\n code Source: "+ CodeSource[position]+ "\n code output: "+ CodeOutput[position]);
textView.setText(test);
System.out.println("list values ------->> " + CodeID[position] + CodeLang[position] + CodeOutput[position] + CodeSource[position] + CodeTitle[position] );
return rowView;
}
}
And finally here is the Fragment class in which I want to show the database values in a list. But When I try to instantiate a new DB object, the editor shows an error mark and suggests to change the constructor declaration and context type.
Guess all due to those poorly written database classes.
package info.aea.drawer;
import info.aea.database.Database_Schema;
import info.aea.database.SourceCode_Adapter;
import info.aea.database.SourceCode_Table;
import info.devey.java.R;
import java.util.List;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class Fragment_Java extends Fragment {
String[] codeid;
String codelang[];
String codetitle[];
String codesource[];
String codeoutput[];
ListView listview;
SQLiteDatabase db;
Database_Schema logindb;
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_java, container,false);
logindb=new Database_Schema(this);
logindb=logindb.open();
String lang="java";
List<SourceCode_Table> ls = logindb.getall(lang);
codeid = new String[ls.size()];
codelang = new String[ls.size()];
codetitle = new String[ls.size()];
codesource = new String[ls.size()];
codeoutput = new String[ls.size()];
for(int i = 0; i<ls.size();i++) {
codeid[i]= ls.get(i).getCodeID();
codelang[i]= ls.get(i).getCodeLang();
codetitle[i]= ls.get(i).getCodeTitle();
codesource[i]= ls.get(i).getCodeSource();
codeoutput[i]= ls.get(i).getCodeOutput();
Log.v("code id","-------"+ls.get(i).getCodeID());
Log.v("code lang","-------"+ls.get(i).getCodeLang());
System.out.println("patname==============+++++++++++++++++++"+ codeid);
System.out.println("date==============+++++++++++++++++++"+ codelang);
}
SourceCode_Adapter adapter = new SourceCode_Adapter(this, codeid, codelang, codetitle, codesource, codeoutput);
listview.setAdapter(adapter);
}
}
So need a help in rectifying these errors. I'm willing to share the whole project as an export file so as to make it simple for the debugging.
Okey I found out where I was wrong. I was passing a context which is meant for activities to a fragment. The fragment needs a Fragment context and not an activity context.
getActivity() is used to pass a context to a fragment, which returns the activity associated with a fragment.
If your activity class extends Activity, you can get application context using getApplicatoinContext(). But this method won’t be available when your Activity extends from Fragment.
When your activity extends Fragment, use getActivity() to get the context of the activity.
public class MainActivity extends Fragment {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting application context
Context context = getActivity();
}
}
So I replaced
logindb=new Database_Schema(this);
logindb=logindb.open();
with
logindb = new Database_Schema(getActivity());
logindb = logindb.open()

Display results from Database to a new Black Activity

i have created a database and run a query which add some elements to results.
I want the button that i have, to respond on click and show the results to a new black activity. I will post my current classes.
Sorry for everything but im very new to android programming. :)
package com.example.pota;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
public class createDatabase extends ListActivity{
private final String DATABASE_NAME = "potaDB";
private final String DATABASE_TABLE = "olaPota";
private final String DATABASE_TABLE2 = "favorites";
private final int DATABASE_VERSION = 1;
private SQLiteDatabase potaDB=null;;
//Kaleitai otan dimiourgeitai to activiy
public void onCreate(Bundle icicle, Context ctx){
super.onCreate(icicle);
ArrayList <String> results = new ArrayList<String>();
try {
//Dhmiourgei ti vasi an den uparxei alliws tin anoigei
this.openOrCreateDatabase(DATABASE_NAME, DATABASE_VERSION, null);
//Dhmiourgei ena table sti vasi me ta ekseis paidia
potaDB.execSQL("CREATE TABLE IF NOT EXISTS" + DATABASE_TABLE + "(id INT PRIMARY KEY AUTOINCREMENT, name VARCHAR, category VARCHAR, info TEXT, difficulty INT);", null);
//Vazei eggrafes ston pinaka
potaDB.execSQL("INSERT INTO" + DATABASE_TABLE + "(name, category, info, difficulty)" + "VALUES ('Screwdriver', 'Pota', 'i klassiki vodka lemoni', 5);");
//Ena query pou tha mas gurisei ta stoixeia tou pinaka
Cursor c = potaDB.rawQuery("SELECT *" + "FROM" + DATABASE_TABLE,null);
//Pernoume ta dedomena tou pinaka pou xreiazomaste
int name1=c.getColumnIndex("name");
int category1=c.getColumnIndex("category");
int info1=c.getColumnIndex("info");
int difficulty1=c.getColumnIndex("difficulty");
//Pernei ta dedomena ekei pou deixnei o Cursor
String name = c.getString(name1);
String category = c.getString(category1);
String info = c.getString(info1);
int difficulty = c.getInt(difficulty1);
//Prosthetei ta trexontai dedomena sto results
results.add("Onoma Potou: " + name + "Katigoria Potou: " + category + "Suntagi: "+ info + "Duskolia: " + difficulty);
} catch(Exception e) {
System.out.println(e);
}finally {
if (potaDB != null)
potaDB.close();
}
}
}
And the Main Activity:
package com.example.pota;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Ok, I'm not sure which Activity you want to use the button in but do something like:
public class MainActivity extends Activity {
Button myBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBtn = (Button) findViewById(R.id.my_button);
mBtn.setOnclickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this, ReceivingActivity.class);
intent.putExtra("key", value); //name key whatever you want then value is whatever you are sending
startActivity(intent); //this starts the next activity through an intent
}
}
There are different ways to use onClick() but this is probably the most popular but it just depends on what you need. Here is one of my answers that shows how to do it using xml
You also need to Read about Intents and understand how to use them and what they are capable of.
To get the data in your other Activity you will do something like
public void onCreate()
{
...
Intent recIntent = getIntent();
String variableName = recIntent.getStringExtra("key");
}

Getting Force close when I try to open my golf scoreboard application

I am quite new androids and seem to have came across a Force close on my app and have no idea how to solve it.
Basically a part of my golf app is a scoreboard that the hole the person is on and the amount of strokes taken.
My code works were you have 2 buttons, add and subtract and change the number that shows up in the EditText. A button is then clicked and submits the number into a listview.I'm now trying to get it so that there is 2 add, subtract buttons and edittext and when both numbers have been entered and button to submit is clicked, will show something like 'Your stroke was 2' 'On hole 1'
Here is the code for it
package com.uhi.myGolfApp;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class scoreboard extends Activity implements OnClickListener {
Button buttonPlus1;
Button buttonMinus1;
EditText editScore1;
Button buttonPlus;
Button buttonMinus;
Button buttonOk;
EditText editScore;
ListView scoreCard;
Cursor cursor;
SimpleCursorAdapter adapter;
Integer score=0;
Integer score1=0;
SharedPreferences prefs;
databaseHelper dbHelper;
SQLiteDatabase db;
Intent i;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate UI from XML
setContentView(R.layout.scoreboard);
// Get a hang of UI components
buttonPlus1 = (Button)findViewById(R.id.buttonadd);
buttonMinus1 = (Button)findViewById(R.id.buttonsub);
editScore1 = (EditText)findViewById(R.id.score1);
buttonPlus = (Button)findViewById(R.id.add);
buttonMinus= (Button)findViewById(R.id.subtract);
buttonOk = (Button)findViewById(R.id.enter);
editScore = (EditText)findViewById(R.id.score);
scoreCard = (ListView)findViewById(R.id.scorePosted);
// Add onClick listeners
buttonPlus1.setOnClickListener(this);
buttonMinus1.setOnClickListener(this);
buttonPlus.setOnClickListener(this);
buttonMinus.setOnClickListener(this);
buttonOk.setOnClickListener(this);
// Get preferences
prefs = PreferenceManager.getDefaultSharedPreferences(this);
editScore.setText( score.toString() );
editScore1.setText( score1.toString() );
// Initialize the database
dbHelper = new databaseHelper(this);
db = dbHelper.getWritableDatabase();
// Load the data (essentially executes a SELECT statement)
cursor = db.query(databaseHelper.tableName, null, null, null, null, null, null);
startManagingCursor(cursor);
// Set the list adapter
String[] from = {databaseHelper.colStrokes, databaseHelper.colHole};
int[] to = {R.id.textStroke, R.id.textHole};
adapter = new SimpleCursorAdapter(this, R.layout.golfscores, cursor, from, to);
scoreCard.setAdapter(adapter);
}
#Override
public void onRestoreInstanceState(Bundle inState) {
score = (inState!=null) ? inState.getInt("score",0) : 0;
score1 = (inState!=null) ? inState.getInt("score1",0) : 0;
editScore.setText( score.toString() );
editScore1.setText( score1.toString() );
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt("score", score);
outState.putInt("score1", score1);
super.onSaveInstanceState(outState);
}
#Override
public void onClick(View src) {
switch(src.getId()) {
case R.id.buttonadd:
score1++;
break;
case R.id.buttonsub:
score1--;
break;
case R.id.add:
score++;
break;
case R.id.subtract:
score--;
break;
case R.id.enter:
// Save in DB
ContentValues values = new ContentValues();
values.put(databaseHelper.colHole, score1);
values.put(databaseHelper.colStrokes, score);
db.insert(databaseHelper.tableName, null, values);
cursor = db.query(databaseHelper.tableName, null, null, null, null, null, null);
startManagingCursor(cursor);
adapter.changeCursor(cursor);
score=0;
adapter.changeCursor(cursor);
score1=0;
break;
}
editScore.setText( score.toString() );
editScore1.setText( score1.toString() );
}
}
and the database
package com.uhi.myGolfApp;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class databaseHelper extends SQLiteOpenHelper {
// DB constants
private static final String DB_NAME = "scoreboard.db";
private static final int DB_VERSION = 1; // Schema version
// Schema constants
public static final String tableName = "scoreboard";
public static final String colHole = "hole";
public static final String colStrokes = "strokes";
// Constructor
public databaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
//create the SQL table and the attributes it will hold
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table "+tableName +
" (_id integer not null primary key autoincrement, "+
colHole + " integer, "+ colStrokes+" integer)";
db.execSQL(sql);
}
// upgrade the database off the old version
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Also I dont know if this is any help but this appears in the LogCat = 'Caused by: java.lang.IllegalArgumentException: column 'hole' does not exist'
Appreciate any help =]
I would guess that you ran your code once, before you added the "hole" column, and that is the database that is being read. You need to delete your app's data (Settings -> Applications -> Your app) so that the newest version of the database is created. If you don't have the option to delete data then uninstall it.

Categories

Resources