ANDROID: Database connection, check data, login page - sql

I'm doing Major Project on my final year and I'm very new to Android plus I;m not good at codings. I need help with my login page. I've created something like a database connection java file which is this:
package one.two;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
public class UserDB
{
public String KEY_USERNAME = "Username";
public String KEY_PASSWORD = "Password";
public String KEY_LNAME = "LastName";
public String KEY_FNAME = "FirstName";
private static final String DATABASE_NAME = "Users";
private static final String DATABASE_TABLE = "User";
private static final int DATABASE_VERSION = 1;
private static Context context;
private static DatabaseHelper DBHelper;
private static SQLiteDatabase db;
public UserDB(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, "Users", null, 1);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
#Override
public void onCreate(SQLiteDatabase db)
{
}
}//end DatabaseHelper
// ---opens the database---
public UserDB open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
// ---closes the database---
public void close()
{
DBHelper.close();
}
}
I've already created a database for users using SQLite. The database name is Users and the table is called User. The records inside the table are Username, Password, LastName, FirstName. I've inserted one user's info into the database. The problem is I do not know whether my UserDB.java is correct.
And I've also created login.java. Hardcoded Login page:
package one.two;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
public class Login extends Activity implements OnClickListener{
UserDB db = new UserDB(this);
/** Called when the activity is first created. */
private EditText etUsername;
private EditText etPassword;
private Button btnLogin;
//private Button btnRegister;
private TextView lblResult;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Get the EditText and Button References
etUsername = (EditText)findViewById(R.id.usernametxt);
etPassword = (EditText)findViewById(R.id.passwordtxt);
btnLogin = (Button)findViewById(R.id.btnLogin);
//btnRegister = (Button)findViewById(R.id.btnRegister);
lblResult = (TextView)findViewById(R.id.msglbl);
//Cursor c = (Cursor) db.getAllTitles();
Button btnArrival = (Button) findViewById(R.id.btnRegister);
btnArrival.setOnClickListener(this);
// Set Click Listener
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Check Login
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
if(username.equals("guest") && password.equals("guest")){
lblResult.setText("Login successful.");
} else {
lblResult.setText("Login failed. Username and/or password doesn't match.");
}
}
});
}
public void onClick(View v)
{
Intent intent = new Intent(this, DatabaseActivity.class);
startActivity(intent);
}
}
So I want to know how I should apply the database connection on the login.java. Should I insert database connection something like db.Open();? I studied ASP.Net a few months back and I kind of forget most of what I've learnt.
So how should I open the database connection on login.java and how to check with database whether the user enters the right username and password?
Just incase you need my xml, here's the code:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:id="#+id/widget0"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background = "#drawable/image"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:id="#+id/widget32"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ferry Hub"
android:textSize="25sp"
android:textStyle="bold"
android:textColor="#ff009999"
android:layout_x="97px"
android:layout_y="15px"
>
</TextView>
<TextView
android:id="#+id/widget35"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:textColor="#ff100999"
android:layout_x="116px"
android:layout_y="48px"
>
</TextView>
<EditText
android:layout_width="168px"
android:layout_height="42px"
android:text=""
android:textSize="18sp"
android:layout_x="133px"
android:layout_y="146px"
android:id="#+id/passwordtxt">
</EditText>
<EditText
android:layout_width="169px"
android:layout_height="41px"
android:text=""
android:textSize="18sp"
android:layout_x="132px"
android:layout_y="93px"
android:id="#+id/usernametxt">
</EditText>
<TextView
android:id="#+id/widget31"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username:"
android:textColor="#ff000000"
android:layout_x="32px"
android:layout_y="102px"
>
</TextView>
<TextView
android:id="#+id/widget32"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password:"
android:textColor="#ff000000"
android:layout_x="32px"
android:layout_y="155px"
>
</TextView>
<Button
android:id="#+id/btnLogin"
android:layout_width="109px"
android:layout_height="34px"
android:text="Login"
android:layout_x="38px"
android:layout_y="272px"
>
</Button>
<Button
android:id="#+id/btnRegister"
android:layout_width="110px"
android:layout_height="35px"
android:text="Register"
android:layout_x="159px"
android:layout_y="272px"
>
</Button>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click 'Register' if you do not have an account."
android:textSize="13px"
android:textColor="#ff000000"
android:layout_x="3px"
android:layout_y="305px"
android:id="#+id/msglbl">
</TextView>
</AbsoluteLayout>
Any help is appreciated. I need to learn how to do it so that I can apply for other pages for example Register.java page.
-Dayne

the first, Are you want to check whether or not record in User table. Ok you can. In Eclipse, Open File Explorer-->data-->data-->package of your app (i think one.two). after that click icon pull a file from the device (icon like FDD driver).
After that install SQLite Expert Professional to open this file. Ok you will know.
To make database in Android. See this site:
http://developer.android.com/resources/tutorials/notepad/index.html
hope helpful for you.

For the database: You should have a primary key that is autoincrement on user table. and try putting codes in onCreate() and onUpgrade(). here's example:
#Override
public void onCreate(SQLiteDatabase db) {
// Creating Tables
String CREATE_EMPLOYEES_TABLE = "CREATE TABLE " + TABLE_EMPLOYEES + "("
+ KEY_EMPID + " INTEGER PRIMARY KEY autoincrement," + KEY_FIRSTNAME
+ " TEXT not null," + KEY_LASTNAME + " TEXT not null," + KEY_DEPARTMENTNAME
+ " TEXT not null," + KEY_EMAIL + " TEXT not null," + KEY_PHONE
+ " TEXT not null," + KEY_PASSWORD + " TEXT not null " + ")";
db.execSQL(CREATE_EMPLOYEES_TABLE);
String CREATE_DEPARTMENTS_TABLE = "CREATE TABLE " + TABLE_DEPARTMENTS
+ "(" + KEY_DEPARTMENTID + " INTEGER PRIMARY KEY autoincrement,"
+ KEY_DEPARTMENTNAME + " TEXT not null"
+ ")";
db.execSQL(CREATE_DEPARTMENTS_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_EMPLOYEES);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DEPARTMENTS);
// Create tables again
onCreate(db);
}`
For the login, try this:
#Override
public void onClick(View v) {
if(et1.getText().toString().equals("admin") &&
et2.getText().toString().equals("admin")) {
Toast.makeText(getApplicationContext(),
"Redirecting...",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Login.this, AdminHome.class);
startActivity(intent);
finish();
}else{
Toast.makeText(getApplicationContext(), "Wrong Credentials",Toast.LENGTH_SHORT).show();
}
}
});

Related

How to draw or write text by hand on image selected from gallery in android?

Actually I have written a code to select image from gallery,but I dont know how to draw or write a text by hand on it.and Edited image should be saved separately in sdcard.Basically I have to make basic paint app where canvas will be my selected image,and my touch is input to draw a circle or anything.
package listdisplay.example.com.photoedit;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.FileDescriptor;
import java.io.IOException;
public class MainActivity_photoedit extends AppCompatActivity {
private static final int RORC =0;
ImageView iview;
Button button,button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_photoedit);
iview= (ImageView) findViewById(R.id.imageView);
button =(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent,RORC);
}
}
);
}
#Override
public void onActivityResult(int requestCode,int resultCode,Intent resultData){
if(requestCode==RORC && resultCode==RESULT_OK){
Uri uri =null;
if(resultData!=null){
uri=resultData.getData();
try {
Bitmap bitmap= getBitmapFromUri(uri);
iview.setImageBitmap(bitmap);
}
catch (IOException e){
e.printStackTrace();
}
}
}
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException{
ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(uri,"r");
FileDescriptor fileDescriptor= parcelFileDescriptor.getFileDescriptor();
Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return bitmap;
}
}
Also, there is another way to do like this is using FingerPaint Api.
For that download code from here,
"https://github.com/nikt/Finger-Paint"
Yes,It also not using Image-view, But it will pick image from gallery and set it into Draw-view and paint on that image.You can also try this.
I have find solution for your requirement . So try this,But for that you have to take Drawing-view instead of Image-view to draw or write text on Image which is picked from Gallery.
Hereby, I am posting code.
activity_main.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:paddingBottom="5dp"
android:paddingTop="5dp"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:id="#+id/buttonNew"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:contentDescription="#string/start_new"
android:src="#drawable/new_pic" />
<ImageButton
android:id="#+id/buttonBrush"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:contentDescription="#string/brush"
android:src="#drawable/brush" />
<ImageButton
android:id="#+id/buttonErase"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:contentDescription="#string/erase"
android:src="#drawable/eraser" />
<ImageButton
android:id="#+id/buttonSave"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:contentDescription="#string/save"
android:src="#drawable/save" />
<ImageButton
android:id="#+id/buttonPickImage"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:contentDescription="#string/save"
android:src="#drawable/save" />
</LinearLayout>
<com.wordpress.priyankvex.paintapp.DrawingView
android:id="#+id/drawing"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="3dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="3dp"
android:layout_weight="1"
android:background="#color/white" />
<!-- Color pallet -->
<LinearLayout
android:id="#+id/paint_colors"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:layout_width="#dimen/large_brush"
android:layout_height="#dimen/large_brush"
android:layout_margin="2dp"
android:background="#color/skin"
android:contentDescription="#string/paint"
android:onClick="paintClicked"
android:src="#drawable/pallet"
android:tag="#color/skin" />
<ImageButton
android:layout_width="#dimen/large_brush"
android:layout_height="#dimen/large_brush"
android:layout_margin="2dp"
android:background="#color/black"
android:contentDescription="#string/paint"
android:onClick="paintClicked"
android:src="#drawable/pallet"
android:tag="#color/black" />
<ImageButton
android:layout_width="#dimen/large_brush"
android:layout_height="#dimen/large_brush"
android:layout_margin="2dp"
android:background="#color/red"
android:contentDescription="#string/paint"
android:onClick="paintClicked"
android:src="#drawable/pallet"
android:tag="#color/red" />
<ImageButton
android:layout_width="#dimen/large_brush"
android:layout_height="#dimen/large_brush"
android:layout_margin="2dp"
android:background="#color/green"
android:contentDescription="#string/paint"
android:onClick="paintClicked"
android:src="#drawable/pallet"
android:tag="#color/green" />
<ImageButton
android:layout_width="#dimen/large_brush"
android:layout_height="#dimen/large_brush"
android:layout_margin="2dp"
android:background="#color/blue"
android:contentDescription="#string/paint"
android:onClick="paintClicked"
android:src="#drawable/pallet"
android:tag="#color/blue" />
<ImageButton
android:layout_width="#dimen/large_brush"
android:layout_height="#dimen/large_brush"
android:layout_margin="2dp"
android:background="#color/yellow"
android:contentDescription="#string/paint"
android:onClick="paintClicked"
android:src="#drawable/pallet"
android:tag="#color/yellow" />
</LinearLayout>
</LinearLayout>
MainActivity.java :
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.util.UUID;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private DrawingView mDrawingView;
private ImageButton currPaint, drawButton, eraseButton, newButton, saveButton, buttonPickImage;
private float smallBrush, mediumBrush, largeBrush;
private final int RESULT_LOAD_IMAGE = 20;
private Uri pickedImage;
private String imagePath = "";
public Bitmap PaintBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawingView = (DrawingView) findViewById(R.id.drawing);
// Getting the initial paint color.
LinearLayout paintLayout = (LinearLayout) findViewById(R.id.paint_colors);
// 0th child is white color, so selecting first child to give black as initial color.
currPaint = (ImageButton) paintLayout.getChildAt(1);
currPaint.setImageDrawable(getResources().getDrawable(R.drawable.pallet_pressed));
drawButton = (ImageButton) findViewById(R.id.buttonBrush);
drawButton.setOnClickListener(this);
eraseButton = (ImageButton) findViewById(R.id.buttonErase);
eraseButton.setOnClickListener(this);
newButton = (ImageButton) findViewById(R.id.buttonNew);
newButton.setOnClickListener(this);
saveButton = (ImageButton) findViewById(R.id.buttonSave);
saveButton.setOnClickListener(this);
buttonPickImage = (ImageButton) findViewById(R.id.buttonPickImage);
buttonPickImage.setOnClickListener(this);
smallBrush = getResources().getInteger(R.integer.small_size);
mediumBrush = getResources().getInteger(R.integer.medium_size);
largeBrush = getResources().getInteger(R.integer.large_size);
// Set the initial brush size
mDrawingView.setBrushSize(mediumBrush);
}
/**
* Method is called when color is clicked from pallet.
*
* #param view ImageButton on which click took place.
*/
public void paintClicked(View view) {
if (view != currPaint) {
// Update the color
ImageButton imageButton = (ImageButton) view;
String colorTag = imageButton.getTag().toString();
mDrawingView.setColor(colorTag);
// Swap the backgrounds for last active and currently active image button.
imageButton.setImageDrawable(getResources().getDrawable(R.drawable.pallet_pressed));
currPaint.setImageDrawable(getResources().getDrawable(R.drawable.pallet));
currPaint = (ImageButton) view;
mDrawingView.setErase(false);
mDrawingView.setBrushSize(mDrawingView.getLastBrushSize());
}
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.buttonBrush:
// Show brush size chooser dialog
showBrushSizeChooserDialog();
break;
case R.id.buttonErase:
// Show eraser size chooser dialog
showEraserSizeChooserDialog();
break;
case R.id.buttonNew:
// Show new painting alert dialog
showNewPaintingAlertDialog();
break;
case R.id.buttonSave:
// Show save painting confirmation dialog.
showSavePaintingConfirmationDialog();
break;
case R.id.buttonPickImage:
// Show save painting confirmation dialog.
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK) {
pickedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// set Gallery Image to Drawing-view
if (imagePath != null) {
PaintBitmap = getResizeBitmap(imagePath);
BitmapDrawable ob = new BitmapDrawable(getResources(), PaintBitmap);
mDrawingView.setBackgroundDrawable(ob);
}
}
}
}
public static Bitmap getResizeBitmap(String path) {
BitmapFactory.Options op = new BitmapFactory.Options();
op.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bmap = BitmapFactory.decodeFile(path, op);
int nh = (int) (bmap.getHeight() * (1024.0 / bmap.getWidth()));
Bitmap bitmapThumbnail = Bitmap.createScaledBitmap(bmap, 1024, nh, true);
int bitmapWidthMain = bitmapThumbnail.getWidth();
int bitmapHeightMain = bitmapThumbnail.getHeight();
return bitmapThumbnail;
}
private void showBrushSizeChooserDialog() {
final Dialog brushDialog = new Dialog(this);
brushDialog.setContentView(R.layout.dialog_brush_size);
brushDialog.setTitle("Brush size:");
ImageButton smallBtn = (ImageButton) brushDialog.findViewById(R.id.small_brush);
smallBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawingView.setBrushSize(smallBrush);
mDrawingView.setLastBrushSize(smallBrush);
brushDialog.dismiss();
}
});
ImageButton mediumBtn = (ImageButton) brushDialog.findViewById(R.id.medium_brush);
mediumBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawingView.setBrushSize(mediumBrush);
mDrawingView.setLastBrushSize(mediumBrush);
brushDialog.dismiss();
}
});
ImageButton largeBtn = (ImageButton) brushDialog.findViewById(R.id.large_brush);
largeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawingView.setBrushSize(largeBrush);
mDrawingView.setLastBrushSize(largeBrush);
brushDialog.dismiss();
}
});
mDrawingView.setErase(false);
brushDialog.show();
}
private void showEraserSizeChooserDialog() {
final Dialog brushDialog = new Dialog(this);
brushDialog.setTitle("Eraser size:");
brushDialog.setContentView(R.layout.dialog_brush_size);
ImageButton smallBtn = (ImageButton) brushDialog.findViewById(R.id.small_brush);
smallBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawingView.setErase(true);
mDrawingView.setBrushSize(smallBrush);
brushDialog.dismiss();
}
});
ImageButton mediumBtn = (ImageButton) brushDialog.findViewById(R.id.medium_brush);
mediumBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawingView.setErase(true);
mDrawingView.setBrushSize(mediumBrush);
brushDialog.dismiss();
}
});
ImageButton largeBtn = (ImageButton) brushDialog.findViewById(R.id.large_brush);
largeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawingView.setErase(true);
mDrawingView.setBrushSize(largeBrush);
brushDialog.dismiss();
}
});
brushDialog.show();
}
private void showNewPaintingAlertDialog() {
AlertDialog.Builder newDialog = new AlertDialog.Builder(this);
newDialog.setTitle("New drawing");
newDialog.setMessage("Start new drawing (you will lose the current drawing)?");
newDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mDrawingView.startNew();
dialog.dismiss();
}
});
newDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
newDialog.show();
}
private void showSavePaintingConfirmationDialog() {
AlertDialog.Builder saveDialog = new AlertDialog.Builder(this);
saveDialog.setTitle("Save drawing");
saveDialog.setMessage("Save drawing to device Gallery?");
saveDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//save drawing
mDrawingView.setDrawingCacheEnabled(true);
String imgSaved = MediaStore.Images.Media.insertImage(
getContentResolver(), mDrawingView.getDrawingCache(),
UUID.randomUUID().toString() + ".png", "drawing");
if (imgSaved != null) {
Toast savedToast = Toast.makeText(getApplicationContext(),
"Drawing saved to Gallery!", Toast.LENGTH_SHORT);
savedToast.show();
} else {
Toast unsavedToast = Toast.makeText(getApplicationContext(),
"Oops! Image could not be saved.", Toast.LENGTH_SHORT);
unsavedToast.show();
}
// Destroy the current cache.
mDrawingView.destroyDrawingCache();
}
});
saveDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
saveDialog.show();
}
}
Manifest.xml :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Try This code, It include brush for draw text on image with different brush size,eraser and color picker to draw text in different colors on text and yes, It will save image with text in gallery.
Hereby, i am attaching screenshot,
Hope, it will help you. :)

Gaps and unexpcted moves in RecyclerView

I'm using RecyclerView along with StaggeredGridLayoutManager for showing items with slightly different appearance. in items I use AspectRatioImageView by JakeWharton (link) to maintain the imageView sizes before the image actually downloaded and shown by Picasso. RV (RecyclerView) is populated by server data in infinite scroll pattern.
The problem is (as shown in included pictures), when scolling, some gaps appear on top and bottom of RV (in picture and sometimes items moves between the columns! (taking screenshot is hard :D)
Edit 2: A really important thing I forgot, is that I use the same layout for all of the items but regarding to adapter items some part of the layouts change their visibility to Gone or vice versa.
My question: Why RV behave like this? Am I doing something wrong? Is this normal in RV?
The code is large and I don't know which part is useful to put here. If you can narrow down the cause I will put some code here.
EDIT: Code parts related to problem
xml:
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg_texture"
android:padding="#dimen/padding_lvlhalf"
android:scrollbarStyle="outsideOverlay"/>
initializing view:
#Bind(R.id.recycler_view) RecyclerView mRecyclerView;
.
.
.
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(columnCount, direction));
mRecyclerView.setAdapter(
new RecyclerViewAdapter<>(ctx, new ViewFiller<Post, DashboardPostViewHolder>() {
#Override
public void fill(Post post, DashboardPostViewHolder holder) {
holder.fill(post);
}
#Override
public DashboardPostViewHolder getViewHolder(View view) {
return new DashboardPostViewHolder(view, receiverName);
}
#Override
public int getLayoutID() {
return R.layout.post_dashboard;
}
});)
My custom Adapter:
public RecyclerViewAdapter(Context context, ViewFiller filler) {
super();
this.filler = filler;
mLayoutInflater = LayoutInflater.from(context);
items = new ArrayList<>();
}
#Override
public BaseViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = mLayoutInflater.inflate(filler.getLayoutID(), parent, false);
return filler.getViewHolder(v);
}
#Override
public void onBindViewHolder(BaseViewHolder holder, int position) {
filler.fill(getItem(position), holder);
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public long getItemId(int position) {
return position;
}
public T getItem(int position){
return items.get(position);
}
public void addItem(int position, T item){
items.add(position, item);
notifyItemInserted(position);
}
public void addItem(T item){
items.add(item);
notifyItemInserted(items.size() - 1);
}
public void addItems(List<T> data){
int oldSize = items.size();
items.addAll(data);
notifyItemRangeInserted(oldSize, data.size());
}
public void addItemsToListHead(List<T> data){
items.addAll(0, data);
notifyItemRangeInserted(0, data.size());
}
public void resetData(List<T> data) {
this.items = data;
notifyDataSetChanged();
}
public void removeItem(int position){
items.remove(position);
notifyItemRemoved(position);
}
public void clear(){
this.items.clear();
notifyDataSetChanged();
}
public List<T> getItems(){
return items;
}
ViewFiller interface
public interface ViewFiller<D, VH extends BaseViewHolder>{
void fill(D data, VH holder);
VH getViewHolder(View view);
#LayoutRes int getLayoutID();
}
Edit 2 (Cont.): My items xml and how I fill them..
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="#dimen/margin_lvlhalf"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/post"
android:background="#color/poinila_background">
<TextView
android:layout_gravity="right"
android:text="#string/test_title"
android:layout_margin="#dimen/margin_lvl1"
style="#style/match_wrap.large_text.centered_right"
android:id="#+id/post_title"
android:visibility="gone"/>
<!--Post Image-->
<com.shaya.poinila.android.presentation.view.AspectRatioImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:contentDescription="#string/post_content_description"
android:id="#+id/post_image"
android:visibility="gone"
app:aspectRatioEnabled="true"
app:dominantMeasurement="width"
/>
<!--Content-->
<TextView
android:id="#+id/post_content"
style="#style/match_wrap.medium_text.three_line.end_ellipsize"
android:layout_margin="#dimen/margin_lvl1"/>
<!--android:text="#string/test_long"-->
<include layout="#layout/horizontal_line"
/>
<!--Post Author-->
<include android:id="#+id/post_author"
layout="#layout/circle_image_title_subtitle_reverse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/margin_lvl1"/>
<include layout="#layout/horizontal_line"
/>
<!--Post Stats (favs, comments, etc) -->
<include android:id="#+id/post_stats"
layout="#layout/stats"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/margin_lvlhalf"
android:layout_marginBottom="#dimen/margin_lvlhalf"/>
<include layout="#layout/horizontal_line"/>
<!--Post Collection Info-->
<include layout="#layout/rounded_image_title_subtitle_reverse"
android:id="#+id/post_collection"/>
</LinearLayout>
</android.support.v7.widget.CardView>
PostViewHolder class
public class PostViewHolder extends RecyclerView.ViewHolder
public void fill(Post post) {
if (post.type == PostType.IMAGE) {
postImage.setVisibility(View.VISIBLE);
postName.setVisibility(TextUtils.isEmpty(post.name) ? View.VISIBLE : View.GONE);
/*if (TextUtils.isEmpty(post.summary))
postContent.setVisibility(View.GONE);*/
}else{ //post.type == PostType.TEXT
postImage.setVisibility(View.GONE);
postName.setVisibility(View.VISIBLE);
postContent.setVisibility(View.VISIBLE);
}
// contetnt
if (TextUtils.isEmpty(post.summary) && !TextUtils.isEmpty(post.contentUrl)) {
DataRepository.getInstance().getPostContent(post.contentUrl, postContent);
}
else{
setText(postContent, post.summary);
}
.
.
.
}
}
Sorry for the long post!
You probably have margins in your root ViewGroup of item.
manager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
Do this ,spacing between the grid items stay same
private boolean flagDecoration = false;
if(!flagDecoration)
{
ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(getContext(),(R.dimen.spacing));
recyclerView.addItemDecoration(itemDecoration);
flagDecoration = true;
}

Auto connecting to a BLE device

I am working on an application to coommunicate against a BLE device, currently I am trying to create a Service that starts with the application and auto connect to TI's CC2541 keyfob.
Problem is the gatt server seem to fail EVERY TIME....
I have no clue whats wrong with my code since by google API's and some tutorials I saw
It seems that all the pieces are in their place, yet still nothing works... =(
Here is my service -
package com.example.bluetoothgatt;
import java.util.UUID;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
public class BLE extends Service implements BluetoothAdapter.LeScanCallback {
private final IBinder mBinder = new BluetoothLeBinder();
private final static String TAG = "BLE";
private static final String DEVICE_NAME = "Keyfobdemo";
private BluetoothManager mBluetoothManager;
public BluetoothGatt mConnectedGatt;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothDevice mDevice;
private String mDeviceAddress;
private int mConnectionState = STATE_DISCONNECTED;
private static final int STATE_DISCONNECTED = 0;
private static final int STATE_CONNECTING = 1;
private static final int STATE_CONNECTED = 2;
/*******************************
*******************************
****** Service Inherited ****** Methods **********
*******************************/
#Override
public void onCreate() {
super.onCreate();
mBluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
mBluetoothAdapter = mBluetoothManager.getAdapter();
Thread discoverDevices = new Thread(mStartRunnable);
discoverDevices.setPriority(discoverDevices.MAX_PRIORITY);
discoverDevices.start();
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
close();
return super.onUnbind(intent);
}
// Implements callback methods for GATT events that the app cares about.
// For example, connection change and services discovered.
private final BluetoothGattExecutor mExecutor = new BluetoothGattExecutor() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
mConnectionState = STATE_CONNECTED;
mConnectedGatt = gatt;
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
mConnectionState = STATE_DISCONNECTED;
Log.i(TAG, "Disconnected from GATT server.");
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
#Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
}
}
#Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
}
};
/**
* Return a reference for the current class
*/
public class BluetoothLeBinder extends Binder {
BLE getService() {
return BLE.this;
}
}
private Runnable mStartRunnable = new Runnable() {
#Override
public void run() {
startScan();
}
};
private void startScan() {
if (mConnectionState == STATE_DISCONNECTED) {
mBluetoothAdapter.startLeScan(this);
mHandler.postDelayed(mStopRunnable, 2500);
}
}
private Runnable mStopRunnable = new Runnable() {
#Override
public void run() {
stopScan();
}
};
private void stopScan() {
mBluetoothAdapter.stopLeScan(this);
}
#Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
/*
* We are looking for SensorTag devices only, so validate the name that
* each device reports before adding it to our collection
*/
if (DEVICE_NAME.equals(device.getName())) {
mDevice = device;
mDeviceAddress = mDevice.getAddress();
connect(mDeviceAddress);
mConnectionState = STATE_CONNECTING;
if(device.getBondState() == BluetoothDevice.BOND_BONDED) {
} else if (device.getBondState() == BluetoothDevice.BOND_BONDING) {
} else if(device.getBondState() == BluetoothDevice.BOND_NONE) {
connect(device.getAddress());
}
}
}
/**
* Connects to the GATT server hosted on the Bluetooth LE device.
*
* #param address
* The device address of the destination device.
*
* #return Return true if the connection is initiated successfully. The
* connection result is reported asynchronously through the
* {#code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
Log.w(TAG,
"BluetoothAdapter not initialized or unspecified address.");
return false;
}
// Previously connected device. Try to reconnect.
if (mDeviceAddress != null && address.equals(mDeviceAddress)
&& mConnectedGatt != null) {
Log.d(TAG,
"Trying to use an existing BluetoothGatt for connection.");
if (mConnectedGatt.connect()) {
mConnectionState = STATE_CONNECTING;
return true;
} else {
return false;
}
}
final BluetoothDevice device = mBluetoothAdapter
.getRemoteDevice(address);
if (device == null) {
Log.w(TAG, "Device not found. Unable to connect.");
return false;
}
// We want to directly connect to the device, so we are setting the
// autoConnect
// parameter to false.
mConnectedGatt = device.connectGatt(this, false, mExecutor);
Log.d(TAG, "Trying to create a new connection.");
mDeviceAddress = address;
mConnectionState = STATE_CONNECTING;
return true;
}
/**
* Disconnects an existing connection or cancel a pending connection. The
* disconnection result is reported asynchronously through the
* BluetoothGattCallback >>
* onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)
* callback.
*/
public void disconnect() {
if (mBluetoothAdapter == null || mConnectedGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mConnectedGatt.disconnect();
}
/**
* After using a given BLE device, the app must call this method to ensure
* resources are released properly.
*/
public void close() {
if (mConnectedGatt == null) {
return;
}
mConnectedGatt.close();
mConnectedGatt = null;
}
private final UUID IMMEDIATE_ALERT_UUID = UUID
.fromString("00001802-0000-1000-8000-00805f9b34fb");
private final UUID ALERT_LEVEL_UUID = UUID
.fromString("00002a06-0000-1000-8000-00805f9b34fb");
public void Buzz(BluetoothGatt gatt, int level) {
BluetoothGattService alertService = gatt
.getService(IMMEDIATE_ALERT_UUID);
if (alertService == null) {
Log.d(TAG, "Immediate Alert service not found!");
return;
}
BluetoothGattCharacteristic alertLevel = alertService
.getCharacteristic(ALERT_LEVEL_UUID);
if (alertLevel == null) {
Log.d(TAG, "Alert Level charateristic not found!");
return;
}
alertLevel.setValue(level, BluetoothGattCharacteristic.FORMAT_UINT8, 0);
gatt.writeCharacteristic(alertLevel);
Log.d(TAG, "Alert");
}
private final UUID BATTERY_SERVICE_UUID = UUID
.fromString("0000180F-0000-1000-8000-00805f9b34fb");
private final UUID BATTERY_LEVEL_UUID = UUID
.fromString("00002a19-0000-1000-8000-00805f9b34fb");
public int getbattery(BluetoothGatt mBluetoothGatt) {
BluetoothGattService batteryService = mConnectedGatt
.getService(BATTERY_SERVICE_UUID);
if (batteryService == null) {
Log.d(TAG, "Battery service not found!");
return 0;
}
BluetoothGattCharacteristic batteryLevel = batteryService
.getCharacteristic(BATTERY_LEVEL_UUID);
if (batteryLevel == null) {
Log.d(TAG, "Battery level not found!");
return 0;
}
mBluetoothGatt.readCharacteristic(batteryLevel);
return batteryLevel.getIntValue(
BluetoothGattCharacteristic.FORMAT_SINT8, 0);
}
/*
* We have a Handler to process event results on the main thread
*/
private static final int MSG_PROGRESS = 201;
private static final int MSG_DISMISS = 202;
private static final int MSG_CLEAR = 301;
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
BluetoothGattCharacteristic characteristic;
switch (msg.what) {
case MSG_PROGRESS:
break;
case MSG_DISMISS:
break;
case MSG_CLEAR:
break;
}
}
};
public void MakeBuzz() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
mConnectedGatt = mDevice.connectGatt(getApplicationContext(),
true, mExecutor);
BluetoothGattService alertService = mConnectedGatt
.getService(IMMEDIATE_ALERT_UUID);
int x = getbattery(mConnectedGatt);
Buzz(mConnectedGatt, 2);
}
});
t.start();
}
}
This it the Application class -
package com.example.bluetoothgatt;
import android.app.Application;
import android.content.Intent;
public class ApplicationBleTest extends Application {
// Application variables
public final String SMOKE_TALK_PACKAGE_NAME = "com.smoketalk";
private BluetoothLEService mBleService;
private static int MODE_PRIVATE;
/**
* Application OnCreate event initiate the class parameters
*/
public void onCreate() {
super.onCreate();
getApplicationContext().startService(new Intent(this, BLE.class));
}
}
And this is the main activity (I am trying to make the keyfob alaram buzz on a button click)
package com.example.bluetoothgatt;
import com.example.bluetoothgatt.BluetoothLowEnergyService.BluetoothLeBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* Created by Dave Smith Double Encore, Inc. MainActivity
*/
public class MainActivity extends Activity {
BluetoothLowEnergyService mBluetoothService;
boolean isBound = false;
Button buzz;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, BluetoothLowEnergyService.class);
bindService(intent, mBleServiceConnection, Context.BIND_AUTO_CREATE);
buzz = (Button) findViewById(R.id.btn1);
buzz.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mBluetoothService.MakeBuzz();
}
});
}
private ServiceConnection mBleServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
BluetoothLeBinder binder = (BluetoothLeBinder) service;
mBluetoothService = binder.getService();
isBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
isBound = false;
}
};
}
And the menifest file -
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetoothgatt"
android:versionCode="1"
android:versionName="1.0" >
<uses-feature
android:name="android.hardware.bluetooth_le"
android:required="true" />
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED"/>
<application
android:name="com.example.bluetoothgatt.ApplicationBleTest"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="SensorTag Weather" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.bluetoothgatt.BLE" />
</application>
</manifest>
and last one the layout for the main activity -
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:padding="#dimen/activity_horizontal_margin"
android:text="Android BLE Test"
android:textSize="42sp" />
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="56dp"
android:text="Buzz" />
</RelativeLayout>
ANY help will be appreciated since I rellay have no clue what goes wrong... =(
For starters, I would recommend commenting out the bond code (Everything after if(device.getBondState().. in the onLeScan method) The whole bonding process was unstable on 4.3 (Nexus devices at least) and became more stable on 4.4.
You should be able to discover devices, and with the BluetoothDevice the user selects you should call ConnectGatt after stopping discovery. This will attempt to connect to the Gatt server on the device. If the connection is successful, you should receive a callback on your connectionStateChange indicating that the connection was successful.
The concept behind bonding is related to pairing with the device and exchanging keys if your characteristics are encrypted. Normally you should be able to connect to the Gatt server without needing to bond, but once you are connected, if you do try to read an encrypted characteristic, it will fail.
I tried your code and it works. you need to follow this process:
BluetoothAdapter.startLeScan(leCallback)
In the onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) in leCallback, call btDevice.connectGatt(Context context, Boolean autoConnect, BluetoothGattCallback gattCallback);
In the onConnectionStateChange(BluetoothGatt gatt, int status, int newState) in gattCallBack, check if newState is BluetoothProfile.STATE_CONNECTED, if yes, call gatt.discoverServices();
In the onServicesDiscovered(BluetoothGatt gatt, int status) in gattCallBack, check if status is BluetoothGatt.GATT_SUCCESS, if yes, get the service by UUID like this: BluetoothGattService service = gatt.getService(YOUR_SERVICE_UUID);
If the service is null, it means the service has not yet been discovered, you need to check again when the next service is discovered and the onServicesDiscovered will be called again.
By the time all the services has been discovered, you should already got your service, unless the device does not support it.
Now you can use your service in your Buzz method.
Also worth noting is that the BLE actions must all be serialized by you. Eg, if you made a read/write to a characteristic you need to wait for the callback before doing another. If not, this will result in an error.
Since you are running from a service you can try running connect on the main thread like this:
public void connectToDevice( String deviceAddress) {
mDeviceAddress = deviceAddress;
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mDeviceAddress);
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
if (device != null) {
mGatt = device.connectGatt(getApplicationContext(), true, mGattCallback);
scanLeDevice(false);// will stop after first device detection
}
}
});
}
Hope it helps.

SQLite >1 Column Table errorcode = 1

I have a problem creating a database with 2 columns.
In the first one there should be a name and in the second one a number.
Creating the name database is no problem, but when I try to add the second column I get the error message "I/Database(13531): sqlite returned: error code = 1, msg = no such column: zahl"
my code is here
first the Manager
package my.studienarbeit.bestimmung.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatenbankManager extends SQLiteOpenHelper {
private static final String DB_NAME = "carbohydrates.db";
private static final int DB_VERSION = 1;
private static final String WEIGHT_CREATE =
"CREATE TABLE weight ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "name TEXT NOT NULL, " +
// + "zahl INTEGER" +
")";
public DatenbankManager(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(WEIGHT_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DatenbankManager.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS SCANITEM");
onCreate(db);
}
}
and my database:
package my.studienarbeit.bestimmung.database;
import my.studienarbeit.bestimmung.R;
import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class Datenbanken extends ListActivity {
private SQLiteDatabase mDatenbank;
private DatenbankManager mHelper;
/*/ private static final String WEIGHT_SELECT_RAW =
"SELECT _id, name, zahl FROM weight" ; //*/
//*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.daten_datenbanken);
mHelper = new DatenbankManager(this);
mHelper.getWritableDatabase();
}
#Override
protected void onPause() {
super.onPause();
mDatenbank.close();
Toast.makeText(this,
getResources().getString(R.string.tx_daten_datenbanken_db_geschlossen),
Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
mDatenbank = mHelper.getWritableDatabase();
Toast.makeText(
this,
getResources().getString(
R.string.tx_daten_datenbanken_db_geoeffnet
),
Toast.LENGTH_SHORT)
.show();
ladeDaten();
}
private void ladeDaten() {
// Cursor weightCursor = mDatenbank.rawQuery(WEIGHT_SELECT_RAW, null);
Cursor weightCursor = mDatenbank.query("weight",
new String [] {
"_id",
"name",
// "zahl",
},
null, null, null, null, null
);
startManagingCursor(weightCursor);
SimpleCursorAdapter weightAdapter =
new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2,
weightCursor,
new String [] {
"name",
// "zahl"
},
new int[] {
android.R.id.text1
}
);
setListAdapter(weightAdapter);
}
public void onNavButtonClick(View view) {
EditText et_c =
(EditText) findViewById(R.id.editText_name_c);
// EditText et_w =
// (EditText) findViewById(R.id.editText_weight_c);
ContentValues werte = new ContentValues();
werte.put("name", et_c.getText().toString());
// werte.put("zahl", et_w.getText().toString());
mDatenbank.insert("weight", null, werte);
ladeDaten();
et_c.setText("");
// et_w.setText("");
The 2nd column is not active right now for debug functions.
If you first created your table without the "zahl" column, then added the "zahl" column and rerun your application, the OpenHelper did not do the "onCreate" again with the new values. My suggestion is that you first drop the table (on emulator, go to Settings > Applications > Yourapp > Click "Clear Data" button), then uncomment the "zahl" lines (especially in DatenbankManager.java), then recompile + run. Running your app again, with an empty database, will recreate the table with column "zahl".

SQLite android login and register

From the previous question I asked, I am still having the same question. I do not know how to use database (SQLite) to 'sync' with my application to log in or register
package log1.log2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Login extends Activity {
UserDB db = new UserDB(this);
/** Called when the activity is first created. */
private EditText etUsername;
private EditText etPassword;
private Button btnLogin;
private Button btnRegister;
private TextView lblResult;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the EditText and Button References
etUsername = (EditText)findViewById(R.id.usernametxt);
etPassword = (EditText)findViewById(R.id.passwordtxt);
btnLogin = (Button)findViewById(R.id.btnLogin);
btnRegister = (Button)findViewById(R.id.btnRegister);
lblResult = (TextView)findViewById(R.id.msglbl);
//Cursor c = (Cursor) db.getAllTitles();
//Button btnArrival = (Button) findViewById(R.id.btnRegister);
//btnArrival.setOnClickListener(this);
// Set Click Listener
btnRegister.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(Login.this,Register.class);
startActivity(intent);
}
});
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
db.open();
// Check Login
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
if(username.equals("select username from Users")){
if(password.equals("select password from users where username = username"))
{
Intent intent=new Intent(Login.this,Test.class);
startActivity(intent);
}
else
{
lblResult.setText("Wrong password");
}
} else {
lblResult.setText("Username does not exist. Please register.");
}
db.close();
}
});
}
}
Should I use the 'select' 'from' 'where' statement? Or there is another way?
Where you have
username.equals("select username from Users")
you are actually testing if what the user entered is literally the same object (which it is not). To authenticate against a local database of Users, you would want to try something more like this:
Cursor c = db.rawQuery("SELECT username FROM Users WHERE username='?' AND password='?'", new String[] {username, password});
if(c.moveToFirst()) {
// at least one row was returned, this should signal success
} else {
// authentication failed
}
Where 'db' is the SQLiteDatabase object you are working with. If you need any kind of security, I would also hash the password before you store it in the database!