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?
Related
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
Hello everyone I want to put my own textview or edittext in canvas1.java or canvasclass.java . Actually this coding are lipitk toolkit handwriting recognition android application. Please help me if possible.
/************************canvas1.java*********************/
package com.canvas;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.inputmethodservice.InputMethodService;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Scroller;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;
import com.google.tts.TTS;
public class Canvas1 extends Activity implements OnClickListener,OnLongClickListener{
private TTS myTts;
CanvasClass canClass;
private LinearLayout main;
private LinearLayout cenerLayout;
private LinearLayout topLayout;
private LinearLayout subLayout;
private LinearLayout tvLayout;
private LinearLayout SecondLayout;
private LinearLayout mylayout;
private ImageView Exit;
private ScrollView scrllView;
private HorizontalScrollView HorizontalSV;
private TextView[] TV=new TextView[1];
private TextView[] s=new TextView[1];
private TextView[] TViews=new TextView[5];
public final static int mButtonHeight = 220;
public final static int mButtonWidth = 80;
String inst[]=new String[5]; ;
String InstTemp;
int flag=0;
int c0flag=0;
int c1flag=0;
int c2flag=0;
int c3flag=0;
int SpaceSelFlag = 1;
String newStr="";
int height;
public static int width;
Vibrator v;
/** Called when the activity is first created. */
CanvasClass canvasClass = null;
Canvas1 conObj = null;
public final int MY_DATA_CHECK_CODE = 1;
private TextToSpeech mTts = null;
public ProgressDialog dialog;
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
width = display.getWidth();
height = display.getHeight();
v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
AssetInstaller assetInstaller = new AssetInstaller(getApplicationContext(), "projects");
try {
assetInstaller.execute();
} catch (IOException e) {
e.printStackTrace();
}
conObj = this;
canvasClass = new CanvasClass(this,conObj);
main = new LinearLayout(this);
main.setOrientation(LinearLayout.VERTICAL);
main.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT));
topLayout = new LinearLayout(this);
topLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
((height/2)+130)));
topLayout.setOrientation(LinearLayout.VERTICAL);
topLayout.setBackgroundColor(0xffffffcc);
topLayout.addView(canvasClass);
/*
mylayout = new LinearLayout(this);
mylayout.setOrientation(LinearLayout.VERTICAL);
mylayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
mylayout.setBackgroundColor(Color.WHITE);
for(int i = 0; i <s.length; i++) {
s = new EditText(this);
s.setTextColor(Color.RED);
s.setTextSize(40);
s.setGravity(Gravity.AXIS_Y_SHIFT);
s.setTypeface(null, Typeface.BOLD);
s.setHeight(height/8);
s.setPadding(5, 0, 0, 0);
s.setScroller(new Scroller(this));
s.setVerticalScrollBarEnabled(true);
s.setMovementMethod(ScrollingMovementMethod.getInstance());
mylayout.addView(s);
}
*/
cenerLayout = new LinearLayout(this);
cenerLayout.setOrientation(LinearLayout.VERTICAL);
cenerLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
cenerLayout.setBackgroundColor(Color.GREEN);
for(int i = 0; i <TV.length; i++) {
TV = new TextView(this);
TV.setTextColor(Color.RED);
TV.setTextSize(40);
TV.setGravity(Gravity.CENTER_HORIZONTAL);
TV.setTypeface(null, Typeface.BOLD);
TV.setHeight(height/8);
TV.setPadding(5, 0, 0, 0);
TV.setScroller(new Scroller(this));
TV.setVerticalScrollBarEnabled(true);
TV.setMovementMethod(ScrollingMovementMethod.getInstance());
cenerLayout.addView(TV);
}
SecondLayout = new LinearLayout(this);
SecondLayout.setOrientation(LinearLayout.VERTICAL);
SecondLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
70));
SecondLayout.setBackgroundColor(0xff26466D);
tvLayout = new LinearLayout(this);
tvLayout.setOrientation(LinearLayout.HORIZONTAL);
tvLayout.setLayoutParams(new LinearLayout.LayoutParams(
(width-20),
((height/8)-30)));
for(int i = 0; i < TViews.length; i++) {
TViews = new TextView(this);
TViews.setTextColor(Color.YELLOW);
TViews[0].setText("Suggested words..");
TViews[0].setTextColor(0xffE8E8E8);
TViews.setTextSize(15);
TViews.setGravity(Gravity.CENTER);
TViews.setPadding(10, 0, 0, 0);
TViews.setHeight(((height/8)-30));
TViews.setOnClickListener(this);
tvLayout.addView(TViews);
}
HorizontalSV=new HorizontalScrollView(this);
HorizontalSV.setLayoutParams(new LinearLayout.LayoutParams(
(width-125),
LinearLayout.LayoutParams.WRAP_CONTENT));
HorizontalSV.addView(tvLayout,new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
SecondLayout.addView(HorizontalSV);
subLayout = new LinearLayout(this);
subLayout.setOrientation(LinearLayout.HORIZONTAL);
subLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
((height/8)-16)));
subLayout.setGravity(Gravity.BOTTOM);
Exit = new ImageView(this);
Exit.setImageResource(R.drawable.exit);
Exit.setPadding(30, 0, 0, 0);
Exit.setOnClickListener(this);
subLayout.addView(Exit);
main.addView(cenerLayout);
main.addView(topLayout);
main.addView(subLayout);
setContentView(main);
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
mTts = new TextToSpeech(this, new OnInitListener() {
public void onInit(int status) {
// TODO Auto-generated method stub
//mTts.speak("Hello World", TextToSpeech.QUEUE_FLUSH, null);
}
});
} else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(
TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
public void onClick(View v) {
if(v==Exit){
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
}
}
/* This method will handle the swipe across the edge. Calls Freepad once the
touch area reaches the right end of screen */
public void ClearCanvas(){
if(canvasClass != null){
topLayout.removeView(canvasClass);
canvasClass = new CanvasClass(this,conObj);
topLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
((height/2)+130)));
topLayout.addView(canvasClass);
}
}
class ProgressdialogClass extends AsyncTask<Void, Void, String> {
@override
protected String doInBackground(Void... unsued) {
canvasClass.addStroke(canvasClass._currentStroke);
return null;
}
@override
protected void onPostExecute(String sResponse) {
dialog.dismiss();
FreePadCall();
}
@override
protected void onPreExecute(){
dialog = ProgressDialog.show(Canvas1.this, "Processing","Please wait...", true);
}
}
public void CallingMethod(){
ProgressdialogClass ObjAsy=new ProgressdialogClass();
ObjAsy.execute();
}
public void FreePadCall(){
HorizontalSV.setVisibility(View.VISIBLE);
if(canvasClass != null){
topLayout.removeView(canvasClass);
canvasClass.destroyDrawingCache();
canvasClass = new CanvasClass(this,conObj);
topLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
((height/2)+130)));
topLayout.addView(canvasClass);
}
TV[0].setText(canvasClass.character[0]);
String str1 = TV[0].getText().toString();
mTts.speak(str1, 0, null);
}
public boolean onLongClick(View v) {
System.out.println("-----long click------");
return true;
}
int curr_indx = 0;
public void SpeakOutChoices(){
if(canvasClass != null){
topLayout.removeView(canvasClass);
canvasClass = new CanvasClass(this,conObj);
topLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
((height/2)+130)));
topLayout.addView(canvasClass);
}
System.out.println("index"+curr_indx +"---"+ CanvasClass.StrokeResultCount);
if(curr_indx < CanvasClass.StrokeResultCount){
TV[0].setText(CanvasClass.character[curr_indx]);
String Choice1=CanvasClass.character[curr_indx];
mTts.speak(Choice1, 0, null);
curr_indx++;
if(curr_indx == CanvasClass.StrokeResultCount)
curr_indx = 0;
}
}
}
/***************Convasclass.java*******************/
package com.canvas;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import com.canvas.Canvas1.ProgressdialogClass;
import android.R.color;
import android.R.style;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.os.CountDownTimer;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.view.View;
import android.view.View.OnTouchListener;
public class CanvasClass extends View implements OnTouchListener{
private LipiTKJNIInterface _lipitkInterface;
private LipiTKJNIInterface _recognizer;
private Page _page;
private PointF _lastSpot;
public Stroke _currentStroke;
private ArrayList<PointF> _currentStrokeStore;
private ArrayList<Stroke> _strokes;
private Stroke[] _recognitionStrokes;
private ArrayList<Symbol> _symbols;
public static String[] character;
public static int StrokeResultCount=0;
ArrayList<Values> vals = new ArrayList<Values>();
public static int min=480;
public static int max=0;
public static int minX=800;
public static int maxX=0;
public static int XCood=0;
private int mPosX;
private int mPosY;
private int mLastTouchX=0;
private int mLastTouchY=0;
boolean flag=true;
boolean flagbs=true;
public static boolean canvastest=true;
MyCount counter;
MyLongPressCount myLongPress;
BufferedWriter out;
Canvas1 canObj=null;
private static final String TAG = "DrawView";
public CanvasClass(Context context,Canvas1 canObjParam) {
super(context);
canObj=canObjParam;
globalvariable.paint=new Paint();
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
globalvariable.paint.setColor(Color.BLUE);
globalvariable.paint.setAntiAlias(true);
globalvariable.paint.setDither(true);
globalvariable.paint.setStyle(Paint.Style.STROKE);
globalvariable.paint.setStrokeJoin(Paint.Join.ROUND);
globalvariable.paint.setStrokeCap(Paint.Cap.ROUND);
globalvariable.paint.setStrokeWidth(5);
counter = new MyCount(700,1000);
myLongPress = new MyLongPressCount(3000,1000);
_currentStroke = new Stroke();
_strokes = new ArrayList<Stroke>();
_recognizer = null;
_symbols = new ArrayList<Symbol>();
// Initialize lipitk
Context contextlipi = getContext();
File externalFileDir = contextlipi.getExternalFilesDir(null);
String path = externalFileDir.getPath();
Log.d("JNI", "Path: " + path);
_lipitkInterface = new LipiTKJNIInterface(path, "SHAPEREC_ALPHANUM");
_lipitkInterface.initialize();
_page = new Page(_lipitkInterface);
_recognizer=_lipitkInterface;
}
public boolean onTouch(View view, MotionEvent event) {
Values vs=new Values();
final int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN: {
min=480;
max=0;
maxX=0;
minX=800;
counter.cancel();
myLongPress.start();
globalvariable.IsUserWriting=true;
vs.x = (int) event.getX();
vs.y = (int) event.getY();
float X= (float) vs.x;
float Y= (float) vs.y;
PointF p = new PointF(X, Y);
_lastSpot=p;
_currentStroke.addPoint(p);
if(vs.y>max)
max=vs.y;
if(vs.y<min)
min=vs.y;
if(vs.x>maxX)
maxX=vs.x;
if(vs.x<minX)
minX=vs.x;
XCood=vs.x;
globalvariable.strokeXY += "{" + vs.x + "," + vs.y + "}|";
vals.add(vs);
invalidate();
System.out.println("action down stroke values===");
break;
}
case MotionEvent.ACTION_MOVE: {
counter.cancel();
vs.x = (int) event.getX();
vs.y = (int) event.getY();
float X= (float) vs.x;
float Y= (float) vs.y;
PointF p = new PointF(X, Y);
_lastSpot=p;
_currentStroke.addPoint(p);
//myLongPress.cancel();
globalvariable.VSG=vs.x;
globalvariable.LongPressFlag=true;
globalvariable.strokeXY += "{" + vs.x + "," + vs.y + "}|";
vals.add(vs);
if(vs.y>max)
max=vs.y;
if(vs.y<min)
min=vs.y;
if(vs.x>maxX)
maxX=vs.x;
if(vs.x<minX)
minX=vs.x;
XCood=vs.x;
System.out.println("action move stroke values===");
invalidate();
break;
}
case MotionEvent.ACTION_UP:{
vs.x = (int) event.getX();
vs.y = (int) event.getY();
float X= (float) vs.x;
float Y= (float) vs.y;
PointF p = new PointF(X, Y);
_lastSpot=p;
_currentStroke.addPoint(p);
_currentStrokeStore = new ArrayList<PointF>();
_currentStrokeStore.add(p);
System.out.println("Max==="+max);
System.out.println("Min==="+min);
globalvariable.strokeXY += "N";
/* this condition should be checked only once for the first stroke after
a time out */
if(globalvariable.isFirststroke)
{
if((max-min) < 30 &&(max!=min))
{
globalvariable.IsUserWriting = false;
}
}
if(globalvariable.isFirststroke && globalvariable.IsUserWriting == false)
{
globalvariable.isFirststroke = true;
}
else
{
globalvariable.isFirststroke = false;
}
if(globalvariable.IsUserWriting)
{
counter.start();
}
else
{
if(XCood < 30)
{
//canObj.backspace();
}
else if(XCood > (canObj.width - 30))
{
canObj.SpeakOutChoices();
}
}
myLongPress.cancel();
System.out.println("action up stroke values===");
break;
}
}
return true;
}
public void addStroke(Stroke stroke) {
_strokes.add(stroke);
_recognitionStrokes = new Stroke[_strokes.size()];
for (int s = 0; s < _strokes.size(); s++)
_recognitionStrokes = _strokes.get(s);
LipitkResult[] results = _recognizer.recognize(_recognitionStrokes);
for (LipitkResult result : results) {
Log.e("jni", "ShapeID = " + result.Id + " Confidence = " + result.Confidence);
}
String configFileDirectory = _recognizer.getLipiDirectory() + "/projects/alphanumeric/config/";
character=new String[results.length];
for(int i=0;i<character.length;i++){
character = _recognizer.getSymbolName(results.Id, configFileDirectory);
}
StrokeResultCount=results.length;
_recognitionStrokes = null;
}
public void clearCanvas(){
System.out.println("====inside clearcanvas====");
canvasCpy.drawColor(Color.BLUE);
System.out.println("====over clearcanvas====");
}
public static Canvas canvasCpy = null;
int canvasWidth = 0;
int canvasHeight = 0;
private Bitmap bitmap;
@override
protected void onDraw(Canvas canvas) {
canvasHeight=canvas.getHeight();
canvasWidth=canvas.getWidth();
for (Values values : vals) {
canvas.save();
canvas.drawPoint(values.x, values.y, globalvariable.paint);
canvas.restore();
mLastTouchX=values.x;
mLastTouchY=values.y;
}
File root = android.os.Environment.getExternalStorageDirectory();
File file = new File(root, "Freepad/points.txt");
if(!(file.isDirectory()))
{
return;
}
else
{
try {
out = new BufferedWriter(new FileWriter(file));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.write(globalvariable.strokeXY);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
globalvariable.canvasvar=canvas;
System.out.println("stroke values:-------"+globalvariable.strokeXY);
System.out.println("stroke values:-------"+globalvariable.strokeXY.length());
}
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@override
public void onFinish() {
System.out.println("Timer Flag :: " + globalvariable.TimerFlag);
if(globalvariable.LongPressFlag){
canObj.CallingMethod();
globalvariable.IsUserWriting=false;
globalvariable.isFirststroke = true;
}
else{
}
}
@override
public void onTick(long millisUntilFinished) {
System.out.println("Tick tick Flag :: " + globalvariable.TimerFlag);
}
}
public class MyLongPressCount extends CountDownTimer{
public MyLongPressCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@override
public void onFinish() {
globalvariable.LongPressFlag=false;
System.out.println("Long press timer expiry: Timer Flag :: " + globalvariable.TimerFlag);
canObj.ClearCanvas();
}
@override
public void onTick(long millisUntilFinished) {
System.out.println("Tick tick Flag :: " + globalvariable.TimerFlag);
}
}
}
class Values {
int x, y;
@override
public String toString() {
return x + ", " + y;
}
}
Hi i have problem capturing the information using the facebook SDK.
The console dont show any error but capture nothing.
In this code below i want to capture the name provided by the facebook SDK
Code:
package com.eduardoh89saluguia;
import java.util.List;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.OpenRequest;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionDefaultAudience;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
@SuppressWarnings("unused")
public class Registro extends Activity {
String get_id, get_name, get_gender, get_email, get_birthday, get_locale, get_location;
private Session.StatusCallback fbStatusCallback = new Session.StatusCallback() {
public void call(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Request.newMeRequest(session, new Request.GraphUserCallback() {
public void onCompleted(GraphUser user, Response response) {
if (response != null) {
String LOG_TAG = null;
// do something with <response> now
try{
// get_id = user.getId();
get_name = user.getName();
//get_gender = (String) user.getProperty("gender");
//get_email = (String) user.getProperty("email");
//get_birthday = user.getBirthday();
//get_locale = (String) user.getProperty("locale");
//get_location = user.getLocation().toString();
Log.d(LOG_TAG, user.getId() + "; " +
user.getName() + "; " //+
//(String) user.getProperty("gender") + "; " +
//(String) user.getProperty("email") + "; " +
//user.getBirthday()+ "; " +
//String) user.getProperty("locale") + "; " +
//user.getLocation()
);
TextView temp;
temp =(TextView)findViewById(R.id.edit1);
temp.setText("your name is "+get_name);
} catch(Exception e) {
e.printStackTrace();
Log.d(LOG_TAG, "Exception e");
}
}
}
}).executeAsync();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registro);
findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(), Ejecucion.class);
startActivity(i);
}
});
}
private Session openActiveSession(Activity activity, boolean allowLoginUI,
StatusCallback callback, List<String> permissions, Bundle savedInstanceState) {
OpenRequest openRequest = new OpenRequest(activity).
setPermissions(permissions).setLoginBehavior(SessionLoginBehavior.
SSO_WITH_FALLBACK).setCallback(callback).
setDefaultAudience(SessionDefaultAudience.FRIENDS);
String LOG_TAG = null;
Session session = Session.getActiveSession();
Log.d(LOG_TAG, "" + session);
if (session == null) {
Log.d(LOG_TAG, "" + savedInstanceState);
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, fbStatusCallback, savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED) || allowLoginUI) {
session.openForRead(openRequest);
return session;
}
}
return null;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.registro, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
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
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