In my Android app, I made an SQLite database containig
(_id, FRIEND_NAME, FRIEND_PLACE(detailed address), FRIEND_PHONE, FRIEND_LOC(location), FRIEND_CATEG)
Also i implemented a List View wich displays all the FRIEND_NAMEs (from the database).
I want to call the selected friend when i click his name.
Infortunatly in despite of calling his number, the app calls always this number "74663".
In fact, I think that the problem is in the assignement of the variable "phone" so when i use (Intent.ACTION_CALL, Uri.parse(phone)) , it gives everytime this same number(74663) (maybe when it does "parse uri" or in the cursor of the database's listview).
1) Where is the problem?
2) Why it always gives the number 74663 to dial
3) can you (please) tell me how to assign the variable phone to get the FRIEND_PHONE of the clicked FRIEND_NAME?
this is the code of the class
`package com.softeq.prepopdb.activity;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.softeq.android.prepopdb.R;
import com.softeq.prepopdb.dbhelper.ExternalDbOpenHelper;`
//������� ��������� �������� ������� ���� ����� ��
public class PrepopSqliteDbActivity extends ListActivity {
private static final String DB_NAME = "yourdb.sqlite";
private static final String TABLE_NAME = "friends";
private static final String FRIEND_ID = "_id";
private static final String FRIEND_NAME = "name";
public static final String FRIEND_PLACE = "place";
public static final String FRIEND_PHONE = "phone";
public static final String FRIEND_LOC = "loc";
public static final String FRIEND_CATEG = "categ";
private SQLiteDatabase database;
private ListView listView;
private ArrayList<String> friends;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//��� �������� ������
ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(this, DB_NAME);
database = dbOpenHelper.openDataBase();
//��� ���� ����������
fillFreinds();
setUpList();
}
//filling the list with friends//
private void fillFreinds() {
friends = new ArrayList<String>();
Cursor friendCursor = database.query(TABLE_NAME,
new String[]
{FRIEND_ID, FRIEND_NAME,FRIEND_PLACE,FRIEND_PHONE,FRIEND_LOC,FRIEND_CATEG},
null, null,null,null, FRIEND_CATEG);
friendCursor.moveToFirst();
if(!friendCursor.isAfterLast()) {
do {
String name = friendCursor.getString(1);
String phone= friendCursor.getString(3);
friends.add(name);
friends.add(phone);
} while (friendCursor.moveToNext());
}
friendCursor.close();
}
//setting up the list to call (or dial) a friend's number onItemClick
private void setUpList() {
setListAdapter(new ArrayAdapter<String>(this,android.R.layout. simple_expandable_list_item_1 , friends));
listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position,long id) {
String phone = "tel:" + FRIEND_PHONE.toString().trim();
Intent i = new Intent(Intent.ACTION_CALL, Uri.parse(phone));
startActivity(i);
}
});
}
}
Create two separate lists for names and phones.
ArrayList<String> names;
ArrayList<String> phones;
Change this portion of your code:
do {
String name = friendCursor.getString(1);
String phone = friendCursor.getString(3);
names.add(name);
phones.add(phone);
} while (friendCursor.moveToNext());
Set names as the data source of your adapter.
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, names));
And access the appropriate phone number in the list like this:
String phone = "tel:" + phones.get(position);
Intent i = new Intent(Intent.ACTION_CALL, Uri.parse(phone));
startActivity(i);
Obviously you will give same value.
use getItemAtPosition(position); to get the exact item on which you have clicked.
Related
this is my saveddata.java page who can I solve
when I want to update data its say number expectation
and data insert but not update
I am trying to take the input values from EditText and I want to save it to SQLite Database. I don't know how to use the logcat [also please explain how can I read the errors from the LogCat].
package com.turningpoint.currencycounter;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class saveddata extends Activity{
DBHelper mydb;
private ListView obj;
ListViewAdapter lviewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.saveditem);
ListViewAdapter arrayAdapter;
mydb = new DBHelper(this);
List<String> friendsnames= mydb.getAllCotacts();
List<String> friendsnames2= mydb.getAllCotacts2();
String frnames[]=friendsnames.toArray(new String[friendsnames.size()]);
String frnames2[]=friendsnames2.toArray(new String[friendsnames2.size()]);
arrayAdapter = new ListViewAdapter(this, frnames, frnames2);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2;
List array_list = mydb.getAllCotacts();
String s = array_list.get(id_To_Search).toString();
Cursor c2 = mydb.getData4(s);
while (c2.moveToNext()) {
String id = c2.getString(0);
String code = c2.getString(1);
// String code ..give me Number inut Expetation
int id2 = Integer.parseInt(id);
int code2 = Integer.parseInt(code);
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id2);
int update=1;
dataBundle.putInt("update", update);
dataBundle.putInt("code", code2);
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.putExtras(dataBundle);
Toast.makeText(getApplicationContext(), code, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
Toast.makeText(getApplicationContext(), s,Toast.LENGTH_SHORT).show();
}
});
}
}
Use android:inputType="number" in EditText to make sure that the input is a number not a string or a charater like this
<EditText
.
.
.
android:inputType="number"
/>
Another solution:
Check if it is a number programmatically
boolean digitsOnly = TextUtils.isDigitsOnly(editText.getText());
Read this article. You will know how to use the logcat
https://guides.codepath.com/android/Debugging-Exceptions-within-your-App
I solve this problem
int code2 = Integer.parseInt(code);
this c2.getString(1) could not Int its give me String
I have a 2 radioButtons in my layout. One is for yes and the other is for no when asked if insured or not. When I click my save button and the data posts to firestore, it shows both NO INSURED and YES INSURED. The way I have my code set up is why it's that way but what I want to do is have one source where if the person clicks yes or no then in firestore I will have Insured : Yes or Insured : No. I will post my code down below
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.gms.dynamic.ObjectWrapper;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.HashMap;
import java.util.Map;
public class ProviderSignUp extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private static final String TAG = "MainActivity";
private static final String KEY_FNAME = "First Name";
private static final String KEY_LNAME = "Last Name";
private static final String KEY_ADDRESS = "Address";
private static final String KEY_SPINNER_VALUE = "Spinner Value";
private static final String KEY_FIXED= "Fixed Rate";
private static final String KEY_HOURLY = "Hourly Rate";
private static final String KEY_AGE_VALE= "Age Value";
private static final String KEY_DOLLAR_VALUE = "Dollar Value";
private static final String KEY_YES_INSURED = "Yes Insured";
private static final String KEY_NO_INSURED = "No Insured";
private EditText fName;
private EditText lName;
private EditText address;
private Spinner my_spinner;
private RadioButton fixedRadioButton;
private RadioButton hourlyRadioButton;
private EditText ageEditText;
private EditText dollarEditText;
private RadioButton yesButton;
private RadioButton noButton;
// Reference to firestore database
private FirebaseFirestore db = FirebaseFirestore.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.provider_signup);
Spinner spinner = findViewById(R.id.mySpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.provider_choices, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
// FireStore Storage for Provider
fName = findViewById(R.id.firstName);
lName = findViewById(R.id.lastName);
address = findViewById(R.id.Address);
my_spinner = (Spinner)findViewById(R.id.mySpinner);
fixedRadioButton = findViewById(R.id.fixedRadioButton);
hourlyRadioButton = findViewById(R.id.hourlyRadioButton);
ageEditText = findViewById(R.id.ageEditText);
dollarEditText = findViewById(R.id.dollarEditText);
yesButton = findViewById(R.id.yesRadioButton);
noButton = findViewById(R.id.noRadioButton);
}
#Override
public void onBackPressed() {
startActivity(new Intent(ProviderSignUp.this,PreSignUp.class));
finish();
}
// These two methods below are for the spinner in the ProviderSignUp
#Override
// Will show a toast message after user selects spinner item
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
String text = adapterView.getItemAtPosition(position).toString();
Toast.makeText(adapterView.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
String fname = fName.getText().toString();
String lname = lName.getText().toString();
String my_address = address.getText().toString();
String spinner = my_spinner.getSelectedItem().toString();
String fixed_radioButton = fixedRadioButton.getText().toString();
String hourly_Radiobutton = hourlyRadioButton.getText().toString();
String age = ageEditText.getText().toString();
String dollar = dollarEditText.getText().toString();
String yes_button = yesButton.getText().toString();
String no_button = noButton.getText().toString();
Map<String,Object> myMap = new HashMap<String,Object>();
myMap.put(KEY_FNAME,fname);
myMap.put(KEY_LNAME,lname);
myMap.put(KEY_ADDRESS, my_address);
myMap.put(KEY_FIXED, fixed_radioButton);
myMap.put(KEY_HOURLY, hourly_Radiobutton);
myMap.put(KEY_AGE_VALE, age);
myMap.put(KEY_DOLLAR_VALUE, dollar);
myMap.put(KEY_YES_INSURED, yes_button);
myMap.put(KEY_NO_INSURED, no_button);
myMap.put(KEY_SPINNER_VALUE , spinner);
db.collection("demoProviders").document("First Provider")
.set(myMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(ProviderSignUp.this, "User Saved", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ProviderSignUp.this, "Error!", Toast.LENGTH_SHORT).show();
Log.d(TAG, e.toString());
}
});
}
}
First thing first,
When I click my save button and the data posts to firestore
This is not happening according to your code. You should use OnClickListener method to implement your thought. I suggest going through this documentation.
Second thing second,
Hope, you are using RadioGroup for your RadioButton. That won't allow more than one RadioButton to be selected at a single time. Here is how you can implement RadioGroup.
Last thing last,
Use a single key to store a boolean value instead of storing multiple key-value pairs for RadioButton state in Firestore. Try this :
if (radioGroup.getCheckedRadioButtonId() == R.id.yesRadioButton){
myMap.put("isInsured", true);
} else {
myMap.put("isInsured", false);
}
instead of this :
myMap.put(KEY_YES_INSURED, yes_button);
myMap.put(KEY_NO_INSURED, no_button);
If you do all the mentioned steps correctly your database should store one value for your RadioButton states. Try and let us know if this worked or not.
I'm working on a app where saxophone players can choose a saxophone (soprano, alto, tenor or baritone). The database should output all the music pieces that are available for that specific saxophone, together with the composer and publisher.
I've used a prepopulated db (created with SQLite Manager) and used the SQLite Asset Helper.
The database (so far) has some 600 records.
Whenever I query the database (let's say on 'alto'), it takes some 10 seconds before the results are found.
I've tried many things: indexing (both in the db file as in the Java code), changed between sqlite-file and db-file, tried on a real device instead of emulator etc, etc.
Nothing seems to work... I hope someone out there can help me on this...
I use two java classes: MyDatabase and SQLiteOpenHelper. If you need more info, please let me know.
MyDatabase class:
package com.example.musicrepertoiredatabase2;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class MyDatabase extends SQLiteAssetHelper {
SqliteAssetHelper helper = new SqliteAssetHelper();
private static final String DATABASE_NAME = "saxophone_repertoire.sqlite";
private static final String TABLE_NAME = "repertoire";
private static final int DATABASE_VERSION = 1;
private static final String ID = "id";
private static final String COMPOSER = "composer";
private static final String TITLE = "title";
private static final String PUBLISHER = "publisher";
private static final String SAXOPHONE = "saxophone";
private static final String ACCOMPANIMENT = "form";
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
String saxSort = SqliteAssetHelper.chooseSax;
String composer = SqliteAssetHelper.chooseComposer;
Cursor result = db.rawQuery("SELECT Composer, id FROM " + TABLE_NAME
+ " WHERE " + SAXOPHONE + "='" + saxSort + "'", null);
return result;
}
}
My SQLiteAssetHelper class:
package com.example.musicrepertoiredatabase2;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class SqliteAssetHelper extends ActionBarActivity implements
OnItemSelectedListener, OnClickListener {
TextView composer, title, saxophone, accompaniment, showInfo, count;
EditText etComposer, etTitle;
Spinner spinnerSaxophone, spinnerAccompaniment;
Button search, clear;
String[] arraySaxophone = { "Soprano", "Alto", "Tenor", "Baritone" };
String[] arrayAccompaniment = { "Solo", "Piano" };
public static String chooseSax = null;
public static String chooseComposer = null;
Handler updateBarHandler;
private MyDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateBarHandler = new Handler();
spinnerSaxophone = (Spinner) findViewById(R.id.spinner_saxophone);
spinnerSaxophone.setOnItemSelectedListener(this);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arraySaxophone);
spinnerSaxophone.setAdapter(adapter1);
spinnerAccompaniment = (Spinner) findViewById(R.id.spinner_accompaniment);
spinnerAccompaniment.setOnItemSelectedListener(this);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arrayAccompaniment);
spinnerAccompaniment.setAdapter(adapter2);
etComposer = (EditText) findViewById(R.id.et_composer);
etComposer.setHint(Html.fromHtml("<small>"
+ getString(R.string.hint_composer) + "<small>"));
etTitle = (EditText) findViewById(R.id.et_title);
etTitle.setHint(Html.fromHtml("<small>"
+ getString(R.string.hint_title) + "<small>"));
search = (Button) findViewById(R.id.btn_search);
clear = (Button) findViewById(R.id.btn_clear);
search.setOnClickListener(this);
clear.setOnClickListener(this);
showInfo = (TextView) findViewById(R.id.tv_showinfo);
count = (TextView) findViewById(R.id.tv_count);
db = new MyDatabase(this);
}
public void launchRingDialog() {
final ProgressDialog ringProgressDialog = ProgressDialog.show(this,
"Searching database...", "Please wait...", true);
ringProgressDialog.setCancelable(true);
new Thread(new Runnable(){
#Override
public void run(){
try{
Thread.sleep(5000);
}catch (Exception e){
}
ringProgressDialog.dismiss();
}
}).start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
int choosePositionSax = spinnerSaxophone.getSelectedItemPosition();
switch (choosePositionSax) {
case 0:
chooseSax = "Soprano";
break;
case 1:
chooseSax = "Alto";
break;
case 2:
chooseSax = "Tenor";
break;
case 3:
chooseSax = "Baritone";
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_search:
launchRingDialog();
chooseComposer = etComposer.getText().toString();
Cursor result = db.getData();
if (result.getCount() == 0) {
Toast.makeText(this, "Nothing found", Toast.LENGTH_SHORT)
.show();
}
launchRingDialog();
StringBuffer buffer = new StringBuffer();
while (result.moveToNext()) {
//buffer.append("Title: " + result.getString(2) + "\n");
buffer.append("Composer: " + result.getString(1) + "\n\n");
showInfo.setText(buffer);
int countFiles = result.getCount();
count.setText(Integer.toString(countFiles));
}
break;
case R.id.btn_clear:
showInfo.setText("");
etComposer.setText("");
etComposer.requestFocus();
break;
default:
break;
}
}
}
Well you have to wait for 5 seconds, why =) ?
Thread.sleep(5000);
Delete this line and your query will be faster!
I have seen that you have launchRingDialog() declared two times in your code so you have to wait for 10 seconds. Your query should last no more than milliseconds so probably you don´t need any ProgressDialog.
I'd suggest adding an index to your table:
Create Index IF NOT EXISTS _index_saxophone on T_ResultsSummary(saxophone);
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()
I can't get my ListView work. When i run emulator it doesn't display ListView with data from databse wihich I created.
I would like to insert data to database through EditText and then display data
Main Program
package test.test;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class TestActivity extends Activity {
/** Called when the activity is first created. */
private ListView listview;
private TextView textview;
private Button button;
private EditText edittext;
SQLiteDatabase databas;
//private String[] test = {"abc","abc","abc", "abc", "abc", "abc"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<String> test2 = new ArrayList<String>();
listview = (ListView)findViewById(R.id.test);
textview = (TextView)findViewById(R.id.mm);
button = (Button)findViewById(R.id.kanp);
edittext = (EditText)findViewById(R.id.textetid);
databas = (new dbHelper(this)).getWritableDatabase();
final ContentValues values = new ContentValues();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Editable ord = edittext.getText();
String ordDb = ord.toString();
//String sql = "INSERT INTO ordlista (ord) " +
//"VALUES (" + ordDb + ")";
//databas.rawQuery(sql, null);
values.put("ord", ordDb);
long varde = databas.insert("ordlista", null, values);
String varde2 = Long.toString(varde);
textview.setText(varde2);
}
});
//#############################TORSDAG###############################
Cursor c = databas.rawQuery( "select ord from ordlista", null);
startManagingCursor(c);
int n = 1;
while(c.isBeforeFirst() == false){
String dbVarde = c.getString(n);
test2.add(dbVarde);
c.moveToNext();
n++;
}
ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, test2);
listview.setAdapter(aa);
//listview.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, test));
}
}
You could try using a SimpleCursorAdapter and save the overhead of maintaining an ArrayAdapter. Rather than having to populate an ArrayList all the time, you can just create a Cursor against the query when you need it updated and set the ListView's adapter. A SimpleCursorAdapter also has the added benefit of handling the list item's population for you based on the columns you provide.
For example:
String[] fieldsFromDB = new String[] {"ord"};
int[] fieldsOnListItem = new int[] {android.R.id.text1};
Cursor c = databas.rawQuery("select ord from ordlista", null);
listview.setAdapter(new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,c,fieldsFromDB,fieldsOnListItem));