Problems with dbhelper - Android Q&A, Help & Troubleshooting

Good day to you all. I have problems with my application, no synchronization with db. An error occurs when you try to log in or register, and the error code indicates a request raw.query.
Code my db.
Code:
CREATE TABLE `logpass` (
`_id` INTEGER PRIMARY KEY AUTOINCREMENT,
`login` TEXT,
`pass` TEXT,
`Name` TEXT,
`Surname` TEXT,
`Groupi` TEXT
);
Code DataBaseHelper
Code:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import android.content.ContentValues;
import android.database.Cursor;
public class DataBaseHelper extends SQLiteOpenHelper {
public static String DB_NAME = "auth.db";
private static final int SCHEMA = 1;
static final String TABLE = "logpass";
private static String DB_PATH;
public static final String _id ="_id";
public static final String login = "login";
public static final String pass = "pass";
public static final String Name = "Name";
public static final String Surname = "Surname";
public static final String Groupi = "Groupi";
public SQLiteDatabase database;
private Context myContext;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, SCHEMA);
this.myContext=context;
DB_PATH = "/data/data/com.example.nikita.myapplication/databases/";
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public boolean insert(String login,String pass,String Name,String Surname,String Groupi){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("login",login);
contentValues.put("pass",pass);
contentValues.put("Name",Name);
contentValues.put("Surname",Surname);
contentValues.put("Groupi",Groupi);
long ins = database.insert( "logpass", null, contentValues);
if (ins==-1) return false;
else return true;
}
public Boolean chklogin(String login){
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = database.rawQuery("Select * from logpass where login=?",new String[]{login});
if (cursor.getCount()>0) return false;
else return true;
}
//LoginPassword verification
public Boolean loginpassword(String login,String pass){
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = database.rawQuery("select * from logpass where login=? and password=?",new String[]{login,pass});
if (cursor.getCount()>0) return true;
else return false;
}
public void create_db(){
InputStream myInput = null;
OutputStream myOutput = null;
try {
File file = new File(DB_PATH + DB_NAME);
if (!file.exists()) {
this.getReadableDatabase();
myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
}
catch(IOException ex){
}
}
public void open() throws SQLException {
String path = DB_PATH + DB_NAME;
database = SQLiteDatabase.openDatabase(path, null,
SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if (database != null) {
database.close();
}
super.close();
}
}
And code Main Activity (where to log in)
Code:
public class MainActivity extends AppCompatActivity {
Button b1, b2;
EditText e1, e2;
DataBaseHelper database;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
database = new DataBaseHelper(this);
b1 = (Button) findViewById(R.id.accept);
e1 = (EditText) findViewById(R.id.email);
e2 = (EditText) findViewById(R.id.pass);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String login = e1.getText().toString();
String password = e2.getText().toString();
Boolean Chkloginpass = database.loginpassword(login, password);
if
(Chkloginpass == true) {
Toast.makeText(getApplicationContext(), "Successful log in", Toast.LENGTH_SHORT).show();
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,Main3Activity.class);
startActivity(i);
}
});
} else
Toast.makeText(getApplicationContext(), "Inccorect log or pass", Toast.LENGTH_SHORT).show();
}
});
b2 = (Button) findViewById(R.id.register);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
Intent i = new Intent(MainActivity.this, LoginLoginActivity.class);
startActivity(i);
}
});
}
}
Also i can send full database

Related

android quiz help

So I've decided to to teach myself how to program for android and have a general understanding for java. Well i decided to borrow someones code from the internet and utilize it to assist in creating my first quiz app. I am getting some errors in this code and was wondering if anyone would be so kind to assist me. Thanks
Code:
package com.danyluk.MedicStudyGuide;
import java.io.IOException;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class Quiz extends Activity{
/** Called when the activity is first created. */
private RadioButton radioButton;
private TextView quizQuestion;
private TextView tvScore;
private int rowIndex = 1;
private static int score=0;
private int questNo=0;
private boolean checked=false;
private boolean flag=true;
private RadioGroup radioGroup;
String[] corrAns = new String[5];
final DataBaseHelper db = new DataBaseHelper(this);
Cursor c1;
Cursor c2;
Cursor c3;
int counter=1;
String label;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz);
String options[] = new String[19];
// get reference to radio group in layout
RadioGroup radiogroup = (RadioGroup) findViewById(R.id.rdbGp1);
// layout params to use when adding each radio button
LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
try {
db.createDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c3 = db.getCorrAns();
tvScore = (TextView) findViewById(R.id.tvScore);
for (int i=0;i<=4;i++)
{
corrAns[i]=c3.getString(0);
c3.moveToNext();
}
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.rdbGp1);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
for(int i=0;;){
RadioButton btn = (RadioButton) radioGroup.getChildAt(i);
String text;
if (btn.isPressed() && btn.isChecked() && questNo < 5)
{
Log.e("corrAns[questNo]",corrAns[questNo]);
if (corrAns[questNo].equals(btn.getText()) && flag==true)
{
score++;
flag=false;
checked = true;
}
else if(checked==true)
{
score--;
flag=true;
checked = false;
}
}
}
tvScore.setText = ("Score: " + Integer.toString(score) + "/5");
Log.e("Score:", Integer.toString(score));
}
});
quizQuestion = (TextView) findViewById(R.id.TextView01);
displayQuestion();
/*Displays the next options and sets listener on next button*/
Button btnNext = (Button) findViewById(R.id.btnNext);
btnNext.setOnClickListener(btnNext_Listener);
/*Saves the selected values in the database on the save button*/
Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(btnSave_Listener);
}
/*Called when next button is clicked*/
private View.OnClickListener btnNext_Listener= new View.OnClickListener() {
@Override
public void onClick(View v) {
flag=true;
checked = false;
questNo++;
if (questNo < 5)
{
c1.moveToNext();
displayQuestion();
}
}
};
/*Called when save button is clicked*/
private View.OnClickListener btnSave_Listener= new View.OnClickListener() {
@Override
public void onClick(View v) {
}
};
private void displayQuestion()
{
//Fetching data quiz data and incrementing on each click
c1=db.getQuiz_Content(rowIndex);
c2 =db.getAns(rowIndex++);
quizQuestion.setText(c1.getString(0));
radioGroup.removeAllViews();
for (int i=0;i<=3;i++)
{
//Generating and adding 4 radio buttons dynamically
radioButton = new RadioButton(this);
radioButton.setText(c2.getString(0));
radioButton.setId(i);
c2.moveToNext();
radioGroup.addView(radioButton);
}
}}}
You forgot give us the error that you get

Using multiple drawables with MapsForge

After following the developer tutorial using Google Maps, my code is crashing when trying to execute the map code from the start up screen. I am trying to add Big East basketball team icons on the map in the correct GPS location. When that part of the code is taken out it works but I can't find what I'm doing wrong. Thanks for any help you can provide.
Here is the map code:
Code:
public class MapsForgeViewer extends MapActivity implements LocationListener, OnClickListener {
private static final double latitudePitt = 40.443061;
private static final double longitudePitt = -79.962273;
private static final double latitudeUConn = 41.807975;
private static final double longitudeUConn = -72.253626;
private MapView mapView;
private GeoPoint myCurrentLocation;
private Button findPosition;
private Button roster;
private Button schedule;
private Button stats;
private Button exit;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.map_view);
// setting up the location listener
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
100, 0, mlocListener);
// end of location listener setup
// find from XML and set onClickListeners
findPosition = (Button) findViewById(R.id.findPositionButton);
roster = (Button) findViewById(R.id.roster);
schedule = (Button) findViewById(R.id.schedule);
stats = (Button) findViewById(R.id.stats);
exit = (Button) findViewById(R.id.exit);
findPosition.setOnClickListener(this);
roster.setOnClickListener(this);
schedule.setOnClickListener(this);
stats.setOnClickListener(this);
exit.setOnClickListener(this);
// end of mapView layout setup
// setting the up the map at the proper zoom level and creating the
// scale bars and buttons
mapView = (MapView) findViewById(R.id.mapView);
mapView.setMapViewMode(MapViewMode.MAPNIK_TILE_DOWNLOAD);
mapView.setBuiltInZoomControls(true);
mapView.setScaleBar(true);
mapView.setClickable(true);
findPositionButton(myCurrentLocation);
mapView.getController().setZoom(14);
setCenterlocation();
// end of mapView setup
//Put pins on map
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawablePitt = this.getResources().getDrawable(R.drawable.pittspin);
CustomItemizedOverlay itemizedOverlayPitt = new CustomItemizedOverlay(drawablePitt, this);
Drawable drawableUConn = this.getResources().getDrawable(R.drawable.connpin);
CustomItemizedOverlay itemizedOverlayUConn = new CustomItemizedOverlay(drawableUConn, this);
//Create points using latitude and longitude
GeoPoint pointPitt = new GeoPoint(latitudePitt, longitudePitt);
OverlayItem overlayitemPitt = new OverlayItem(pointPitt, "Pitt", "Panthers");
GeoPoint pointUConn = new GeoPoint(latitudeUConn, longitudeUConn);
OverlayItem overlayitemUConn = new OverlayItem(pointUConn, "UConn", "Huskies");
itemizedOverlayPitt.addOverlay(overlayitemPitt);
itemizedOverlayUConn.addOverlay(overlayitemUConn);
//add to map
mapOverlays.add(itemizedOverlayPitt);
mapOverlays.add(itemizedOverlayUConn);
}
public void onClick(View v)
{
switch (v.getId())
{
case (R.id.findPositionButton):
findPositionButton(myCurrentLocation);
break;
case (R.id.roster):
// get data from database
break;
case (R.id.schedule):
break;
case (R.id.stats):
break;
// close the app
case (R.id.exit):
finish();
break;
}
}
public void findPositionButton(GeoPoint p)
{
mapView.getController().setCenter(p);
}
@Override
// resumes the actions of the application on a pause
protected void onResume()
{
super.onResume();
}
// sets the center of the screen on the map
protected void setCenterlocation()
{
if (myCurrentLocation == null)
mapView.getController().setCenter(new GeoPoint(39.00, -100.00));
else
mapView.getController().setCenter(myCurrentLocation);
}
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
GeoPoint gp = new GeoPoint(loc.getLatitude(), loc.getLongitude());
if (gp != null)
myCurrentLocation = gp;
}
// activates when the current provider is disabled, or inactive
public void onProviderDisabled(String provider)
{
Toast.makeText(getApplicationContext(), "GPS Disabled",
Toast.LENGTH_LONG).show();
}
// activates when a provider is found.
public void onProviderEnabled(String provider)
{
Toast.makeText(getApplicationContext(), "GPS Enabled",
Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
public void onLocationChanged(Location arg0)
{
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
CustomItemizedOverlay:
Code:
public class CustomItemizedOverlay extends ItemizedOverlay<OverlayItem> {
public ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private Context context;
public MapsForgeViewer mActivtyl;
public CustomItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public CustomItemizedOverlay(Drawable defaultMarker, Context context) {
this(defaultMarker);
this.context = context;
}
@Override
protected OverlayItem createItem(int i) {
return mapOverlays.get(i);
}
@Override
public int size() {
return mapOverlays.size();
}
@Override
protected boolean onTap(int index) {
OverlayItem item = mapOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
this.populate();
}
}

Android SQLLite Sample

Android SQLLite Sample
hello guys im new for xda, and this is a my first thread.please give me your feed back.
DataBase Setting Java File
Code:
package com.example.mydsqllite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBCon extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "myDoople";
private static final String TABLE_LABELS = "Customer";
private static final String KEY_ID = "ID";
private static final String KEY_NAME = "CName";
public DBCon(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";
db.execSQL(CREATE_CATEGORIES_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
onCreate(db);
}
/**
* Inserting new lable into lables table
* */
public void insertLabel(String label) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label);
db.insert(TABLE_LABELS, null, values);
db.close();
}
/**
* Getting all labels returns list of labels
* */
public void deleteLabel(String label1) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label1);
db.delete(TABLE_LABELS, KEY_NAME + "=?", new String[] {label1});
db.close();
}
public List<String> getAllLabels() {
List<String> labels = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return labels;
}
}
Main Activity File
Code:
package com.example.mydsqllite;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
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.Toast;
public class MainActivity extends Activity implements OnClickListener,
OnItemSelectedListener {
private Spinner sp;
private Button bt;
private Button dl;
private EditText tx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UI();
InitSpinner();
}
public void UI() {
sp = (Spinner) findViewById(R.id.spinner1);
sp.setOnItemSelectedListener(this);
bt = (Button) findViewById(R.id.btUpdate);
bt.setOnClickListener(this);
dl = (Button) findViewById(R.id.btDel);
dl.setOnClickListener(this);
tx = (EditText) findViewById(R.id.TxtCus);
}
private void InitSpinner() {
DBCon db = new DBCon(getApplicationContext());
List<String> lables = db.getAllLabels();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(dataAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String label = arg0.getItemAtPosition(arg2).toString();
Toast.makeText(arg0.getContext(), "Customer Name : " + label,
Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
@Override
public void onClick(View v) {
if (v == bt) {
String label = tx.getText().toString();
if (label.trim().length() > 0) {
DBCon db = new DBCon(getApplicationContext());
db.insertLabel(label);
tx.setText("");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(tx.getWindowToken(), 0);
InitSpinner();
}
} else if (v == dl) {
String CName = tx.getText().toString();
if (CName.trim().length() > 0) {
DBCon db = new DBCon(getApplicationContext());
db.deleteLabel(CName);
tx.setText("");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(tx.getWindowToken(), 0);
InitSpinner();
}
} else {
Toast.makeText(getApplicationContext(), "Please Enter Customer Name",
Toast.LENGTH_SHORT).show();
}
}
}
mydoople said:
Android SQLLite Sample
hello guys im new for xda, and this is a my first thread.please give me your feed back.
DataBase Setting Java File
Code:
package com.example.mydsqllite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBCon extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "myDoople";
private static final String TABLE_LABELS = "Customer";
private static final String KEY_ID = "ID";
private static final String KEY_NAME = "CName";
public DBCon(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";
db.execSQL(CREATE_CATEGORIES_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
onCreate(db);
}
/**
* Inserting new lable into lables table
* */
public void insertLabel(String label) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label);
db.insert(TABLE_LABELS, null, values);
db.close();
}
/**
* Getting all labels returns list of labels
* */
public void deleteLabel(String label1) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label1);
db.delete(TABLE_LABELS, KEY_NAME + "=?", new String[] {label1});
db.close();
}
public List<String> getAllLabels() {
List<String> labels = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return labels;
}
}
Main Activity File
Code:
package com.example.mydsqllite;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
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.Toast;
public class MainActivity extends Activity implements OnClickListener,
OnItemSelectedListener {
private Spinner sp;
private Button bt;
private Button dl;
private EditText tx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UI();
InitSpinner();
}
public void UI() {
sp = (Spinner) findViewById(R.id.spinner1);
sp.setOnItemSelectedListener(this);
bt = (Button) findViewById(R.id.btUpdate);
bt.setOnClickListener(this);
dl = (Button) findViewById(R.id.btDel);
dl.setOnClickListener(this);
tx = (EditText) findViewById(R.id.TxtCus);
}
private void InitSpinner() {
DBCon db = new DBCon(getApplicationContext());
List<String> lables = db.getAllLabels();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(dataAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String label = arg0.getItemAtPosition(arg2).toString();
Toast.makeText(arg0.getContext(), "Customer Name : " + label,
Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
@Override
public void onClick(View v) {
if (v == bt) {
String label = tx.getText().toString();
if (label.trim().length() > 0) {
DBCon db = new DBCon(getApplicationContext());
db.insertLabel(label);
tx.setText("");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(tx.getWindowToken(), 0);
InitSpinner();
}
} else if (v == dl) {
String CName = tx.getText().toString();
if (CName.trim().length() > 0) {
DBCon db = new DBCon(getApplicationContext());
db.deleteLabel(CName);
tx.setText("");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(tx.getWindowToken(), 0);
InitSpinner();
}
} else {
Toast.makeText(getApplicationContext(), "Please Enter Customer Name",
Toast.LENGTH_SHORT).show();
}
}
}
Click to expand...
Click to collapse
So what is exactly the point of this thread?

[Q] How do I filter a retrieve data in Spinner?

I'm new to android,stuck in this part of my code.
I do hope, someone would help me with it.
As ,I've stuck for quite a while and have to complete within 2 days,
If I would like to filter in spinner based on the dates, how should I do it? For example,
I've a list of events, and in my spinner
when I select "Today", it will show out the list for today.
I've tried out the coding, however, I met some error. The part in BOLD, ** is having error.
I would like to get the XML data from here:
[attached in this thread]
the highlighted part
here is my coding: AndroidXMLParsingActivity.java
public class AndroidXMLParsingActivity extends ListActivity implements OnItemSelectedListener {
String[] browseby;
String[] dates = { "Today", "Tomorrow", "Next Week",
};
ArrayList<String> browse = new ArrayList<String>();
ArrayList<String> mPostingData = new ArrayList<String>();
Spinner s1;
ListView listview;
CustomAdapter cus;
// All static variables
static final String URL = " URL ";
// XML node keys
static final String KEY_EVENT = "event"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_START_TIME = "start_time";
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_EVENT);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_START_TIME, parser.getValue(e, KEY_START_TIME));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item, new String[] { KEY_TITLE,KEY_START_TIME }, new int[] {
R.id.title,
R.id.startTime });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title))
.getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
startActivity(in);
}
});
listview = (ListView) findViewById(R.id.listView1);
s1 = (Spinner) findViewById(R.id.spinner1);
for (int i = 0; i < browseby.length; i++) {
browse.add(browseby);
}
// aa = new
// ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Category);
s1.setOnItemSelectedListener(this);
mPostingData = browse;
for (int i = 0; i < mPostingData.size(); i++) {
if (mPostingData.size() > 0)
Log.i("Datas", mPostingData.get(i));
}
cus = new CustomAdapter(this, 0);
setListAdapter(cus);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, dates);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(aa);
}
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// listview.setFilterText(Category[position]);
String Text = s1.getSelectedItem().toString();
cus.getFilter().filter(Text);
cus.notifyDataSetChanged();
}
public void onNothingSelected(AdapterView<?> parent) {
// listview.setFilterText("");
}
public void onListItemClick(ListView parent, View v, int position, long id) {
Toast.makeText(this, "You have selected " + mPostingData.get(position),
Toast.LENGTH_SHORT).show();
}
class CustomAdapter extends ArrayAdapter<String> {
public void setData(ArrayList<String> mPpst) {
mPostingData = mPpst;// contains class items data.
}
@override
******public Filter getFilter() {
return new Filter() {
@override
protected void publishResults(CharSequence constraint,
FilterResults start_time) {
if (start_time.equals("2013-09-25") {
setData((ArrayList<String>) start_time.values);
} else {
setData(browse);// set original values
}
notifyDataSetInvalidated();
}******
@override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if (!TextUtils.isEmpty(constraint)) {
constraint = constraint.toString();
ArrayList<String> foundItems = new ArrayList<String>();
if (browse != null) {
for (int i = 0; i < browse.size(); i++) {
if (browse.get(i).contains(constraint)) {
System.out.println("My datas" + browse.get(i));
foundItems.add(browse.get(i));
} else {
}
}
}
result.count = foundItems.size();// search results found
// return count
result.values = foundItems;// return values
} else {
result.count = -1;// no search results found
}
return result;
}
};
}
LayoutInflater mInflater;
public CustomAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@override
public int getCount() {
// TODO Auto-generated method stub
return mPostingData.size();
}
@override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder vh;
if (convertView == null) {
vh = new ViewHolder();
convertView = mInflater.inflate(R.layout.row, null);
vh.t1 = (TextView) convertView.findViewById(R.id.textView1);
convertView.setTag(vh);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
vh = (ViewHolder) convertView.getTag();
}
if (mPostingData.size() > 0)
vh.t1.setText(mPostingData.get(position));
return convertView;
}
}
static class ViewHolder {
TextView t1;
}
}
randomise said:
I'm new to android,stuck in this part of my code.
I do hope, someone would help me with it.
As ,I've stuck for quite a while and have to complete within 2 days,
If I would like to filter in spinner based on the dates, how should I do it? For example,
I've a list of events, and in my spinner
when I select "Today", it will show out the list for today.
I've tried out the coding, however, I met some error. The part in BOLD, ** is having error.
I would like to get the XML data from here:
[attached in this thread]
the highlighted part
here is my coding: AndroidXMLParsingActivity.java
public class AndroidXMLParsingActivity extends ListActivity implements OnItemSelectedListener {
String[] browseby;
String[] dates = { "Today", "Tomorrow", "Next Week",
};
ArrayList<String> browse = new ArrayList<String>();
ArrayList<String> mPostingData = new ArrayList<String>();
Spinner s1;
ListView listview;
CustomAdapter cus;
// All static variables
static final String URL = " URL ";
// XML node keys
static final String KEY_EVENT = "event"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_START_TIME = "start_time";
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_EVENT);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_START_TIME, parser.getValue(e, KEY_START_TIME));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item, new String[] { KEY_TITLE,KEY_START_TIME }, new int[] {
R.id.title,
R.id.startTime });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title))
.getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
startActivity(in);
}
});
listview = (ListView) findViewById(R.id.listView1);
s1 = (Spinner) findViewById(R.id.spinner1);
for (int i = 0; i < browseby.length; i++) {
browse.add(browseby);
}
// aa = new
// ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Category);
s1.setOnItemSelectedListener(this);
mPostingData = browse;
for (int i = 0; i < mPostingData.size(); i++) {
if (mPostingData.size() > 0)
Log.i("Datas", mPostingData.get(i));
}
cus = new CustomAdapter(this, 0);
setListAdapter(cus);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, dates);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(aa);
}
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// listview.setFilterText(Category[position]);
String Text = s1.getSelectedItem().toString();
cus.getFilter().filter(Text);
cus.notifyDataSetChanged();
}
public void onNothingSelected(AdapterView<?> parent) {
// listview.setFilterText("");
}
public void onListItemClick(ListView parent, View v, int position, long id) {
Toast.makeText(this, "You have selected " + mPostingData.get(position),
Toast.LENGTH_SHORT).show();
}
class CustomAdapter extends ArrayAdapter<String> {
public void setData(ArrayList<String> mPpst) {
mPostingData = mPpst;// contains class items data.
}
@override
******public Filter getFilter() {
return new Filter() {
@override
protected void publishResults(CharSequence constraint,
FilterResults start_time) {
if (start_time.equals("2013-09-25") {
setData((ArrayList<String>) start_time.values);
} else {
setData(browse);// set original values
}
notifyDataSetInvalidated();
}******
@override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if (!TextUtils.isEmpty(constraint)) {
constraint = constraint.toString();
ArrayList<String> foundItems = new ArrayList<String>();
if (browse != null) {
for (int i = 0; i < browse.size(); i++) {
if (browse.get(i).contains(constraint)) {
System.out.println("My datas" + browse.get(i));
foundItems.add(browse.get(i));
} else {
}
}
}
result.count = foundItems.size();// search results found
// return count
result.values = foundItems;// return values
} else {
result.count = -1;// no search results found
}
return result;
}
};
}
LayoutInflater mInflater;
public CustomAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@override
public int getCount() {
// TODO Auto-generated method stub
return mPostingData.size();
}
@override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder vh;
if (convertView == null) {
vh = new ViewHolder();
convertView = mInflater.inflate(R.layout.row, null);
vh.t1 = (TextView) convertView.findViewById(R.id.textView1);
convertView.setTag(vh);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
vh = (ViewHolder) convertView.getTag();
}
if (mPostingData.size() > 0)
vh.t1.setText(mPostingData.get(position));
return convertView;
}
}
static class ViewHolder {
TextView t1;
}
}
Click to expand...
Click to collapse
Can someone please help me out?
your help will be appreciated.
Thanks

Hey all, i want to make an android app which presents a form which sends the data ins

Hey all, i want to make an android app which presents a form which sends the data inserted in a database when the submit button is pressed..im a newbie but i think i ve got some progress here. i present my code:
package com.example.marialena.practice;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_LAST_NAME = "last_name";
private static final String KEY_ORIGIN = "origin";
public DatabaseHandler(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION);}
// Creating Tables
@override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_LAST_NAME + " TEXT," + KEY_ORIGIN + "TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
@override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_LAST_NAME, contact.getLastName()); // Contact last Name
values.put(KEY_ORIGIN, contact.getOrigin()); // Contact Origin
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_LAST_NAME, KEY_ORIGIN }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null) cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),cursor.getString(3));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setLastName(cursor.getString(2));
contact.setOrigin(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_LAST_NAME, contact.getLastName());
values.put(KEY_ORIGIN, contact.getOrigin());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?", new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
DisplayMessageActivity.java
package com.example.marialena.practice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;
import java.util.List;
public class DisplayMessageActivity extends MyActivity {
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
//receiving data
Intent intent = getIntent();
//manipulating message extraction and thank u message.
String message = "Thank You!";
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
setContentView(textView);
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Ravi", "Alonso","HollowStr"));
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Last Name: " + cn.getLastName() + " ,Origin: " + cn.getOrigin();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
@override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MyActivity.java
package com.example.marialena.practice;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MyActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.marialena.practice.MESSAGE";
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_my, menu);
return true;
}
@override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.name);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
/* Intent intent2 = new Intent(this, DisplayMessageActivity.class);
EditText editText2 = (EditText) findViewById(R.id.last);
String message2 = editText2.getText().toString();
intent2.putExtra(EXTRA_MESSAGE, message2);
startActivity(intent2);*/
}
}
CONTACT.JAVA
package com.example.marialena.practice;
/**
* Created by Marialena on 7/31/2015.
*/
public class Contact {
//private variables
int _id;
String _name;
String _last_name;
String _origin;
//empty constructor
public Contact(){}
//constructor plus ID
public Contact(int id,String name, String last_name, String origin){
this._id=id;
this._last_name=last_name;
this._name=name;
this._origin=origin;
}
//constructor simple
public Contact(String name, String last_name, String origin){
this._origin=origin;
this._name=name;
this._last_name=last_name;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
// getting last name
public String getLastName(){
return this._last_name;
}
// setting last name
public void setLastName(String last_name){
this._last_name = last_name;
}
// getting origin
public String getOrigin(){
return this._origin;
}
// setting origin
public void setOrigin(String origin){
this._origin = origin;
}
}
nikoc03 said:
Hey all, i want to make an android app which presents a form which sends the data inserted in a database when the submit button is pressed..im a newbie but i think i ve got some progress here. i present my code:
package com.example.marialena.practice;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_LAST_NAME = "last_name";
private static final String KEY_ORIGIN = "origin";
public DatabaseHandler(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION);}
// Creating Tables
@override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_LAST_NAME + " TEXT," + KEY_ORIGIN + "TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
@override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_LAST_NAME, contact.getLastName()); // Contact last Name
values.put(KEY_ORIGIN, contact.getOrigin()); // Contact Origin
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_LAST_NAME, KEY_ORIGIN }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null) cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),cursor.getString(3));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setLastName(cursor.getString(2));
contact.setOrigin(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_LAST_NAME, contact.getLastName());
values.put(KEY_ORIGIN, contact.getOrigin());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?", new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
DisplayMessageActivity.java
package com.example.marialena.practice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;
import java.util.List;
public class DisplayMessageActivity extends MyActivity {
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
//receiving data
Intent intent = getIntent();
//manipulating message extraction and thank u message.
String message = "Thank You!";
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
setContentView(textView);
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Ravi", "Alonso","HollowStr"));
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Last Name: " + cn.getLastName() + " ,Origin: " + cn.getOrigin();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
@override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MyActivity.java
package com.example.marialena.practice;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MyActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.marialena.practice.MESSAGE";
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_my, menu);
return true;
}
@override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.name);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
/* Intent intent2 = new Intent(this, DisplayMessageActivity.class);
EditText editText2 = (EditText) findViewById(R.id.last);
String message2 = editText2.getText().toString();
intent2.putExtra(EXTRA_MESSAGE, message2);
startActivity(intent2);*/
}
}
CONTACT.JAVA
package com.example.marialena.practice;
/**
* Created by Marialena on 7/31/2015.
*/
public class Contact {
//private variables
int _id;
String _name;
String _last_name;
String _origin;
//empty constructor
public Contact(){}
//constructor plus ID
public Contact(int id,String name, String last_name, String origin){
this._id=id;
this._last_name=last_name;
this._name=name;
this._origin=origin;
}
//constructor simple
public Contact(String name, String last_name, String origin){
this._origin=origin;
this._name=name;
this._last_name=last_name;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
// getting last name
public String getLastName(){
return this._last_name;
}
// setting last name
public void setLastName(String last_name){
this._last_name = last_name;
}
// getting origin
public String getOrigin(){
return this._origin;
}
// setting origin
public void setOrigin(String origin){
this._origin = origin;
}
}
Click to expand...
Click to collapse
I suggest starting here:
http://forum.xda-developers.com/app-development

Categories

Resources