Create table Agent and insert values to sqlite table in Android - java

I am new in android app developement. I tried to insert values to SQLite database through the code below ; and it is not working. I'm desperate!
Can anyone pleaaaaase help me???
this is DatabaseHelper.JAVA
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "agents.db";
private static final String TABLE_NAME = "agents";
private static final String COLUMN_ID = "id";
private static final String COLUMN_MATRICULE = "matricule";
private static final String COLUMN_NOM = "nom";
private static final String COLUMN_PRENOM = "prenom";
private static final String COLUMN_FONCTION = "fonction";
private static final String COLUMN_EMAIL = "email";
private static final String COLUMN_PASS = "pass";
private static final String COLUMN_ADDRESS = "address";
private static final String COLUMN_CIN = "cin";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table agents (id integer primary key not null , " +
", matricule integer not null , nom text not null , prenom text not null , fonction text not null , email text not null , pass text not null , address text not null);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
this.db = db;
}
public void insertAgent(Agent a) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from agents";
Cursor cursor = db.rawQuery(query , null);
int count = cursor.getCount();
values.put(COLUMN_ID , count);
values.put(COLUMN_MATRICULE, a.getMatricule());
values.put(COLUMN_NOM, a.getNom());
values.put(COLUMN_PRENOM, a.getPrenom());
values.put(COLUMN_FONCTION, a.getFonction());
values.put(COLUMN_EMAIL, a.getEmail());
values.put(COLUMN_PASS, a.getPass());
values.put(COLUMN_ADDRESS, a.getAddress());
values.put(COLUMN_CIN, a.getCin());
db.insert(TABLE_NAME, null, values);
db.close();
}
public String searchPass(String matricule)
{
db = this.getReadableDatabase();
String query = "select matricule, pass from "+TABLE_NAME;
Cursor cursor = db.rawQuery(query , null);
String a, b;
b = "not found";
if(cursor.moveToFirst())
{
do{
a = cursor.getString(0);
if(a.equals(matricule))
{
b = cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return b;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS "+TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
}
Agent.JAVA
public class Agent {
String matricule,nom,prenom,fonction,email,pass,address,cin;
public String getMatricule() {
return matricule;
}
public void setMatricule(String matricule) {
this.matricule = matricule;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getFonction() {
return fonction;
}
public void setFonction(String fonction) {
this.fonction = fonction;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCin() {
return cin;
}
public void setCin(String cin) {
this.cin = cin;
}
}
InscRire.JAVA
public class InscRire extends Activity {
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sinscrire);
}
public void onSignUpClick(View v)
{
if(v.getId()== R.id.Bsinscrire)
{
EditText matricule = (EditText)findViewById(R.id.TFmatricule);
EditText nom = (EditText)findViewById(R.id.TFnom);
EditText prenom = (EditText)findViewById(R.id.TFprenom);
EditText fonction = (EditText)findViewById(R.id.TFfonction);
EditText email = (EditText)findViewById(R.id.TFemail);
EditText pass1 = (EditText)findViewById(R.id.TFpass1);
EditText pass2 = (EditText)findViewById(R.id.TFpass2);
EditText address = (EditText)findViewById(R.id.TFaddress);
EditText cin = (EditText)findViewById(R.id.TFcin);
String matriculestr = matricule.getText().toString();
String nomstr = nom.getText().toString();
String prenomstr = prenom.getText().toString();
String fonctionstr = fonction.getText().toString();
String emailstr = email.getText().toString();
String pass1str = pass1.getText().toString();
String pass2str = pass2.getText().toString();
String addressstr = address.getText().toString();
String cinstr = cin.getText().toString();
if(!pass1str.equals(pass2str))
{
//popup msg
Toast pass = Toast.makeText(InscRire.this , "Mot de passe incorrect!" , Toast.LENGTH_SHORT);
pass.show();
}
else
{
//insert the detailes in database
Agent a = new Agent();
a.setMatricule(matriculestr);
a.setNom(nomstr);
a.setPrenom(prenomstr);
a.setFonction(fonctionstr);
a.setEmail(emailstr);
a.setPass(pass1str);
a.setAddress(addressstr);
a.setCin(cinstr);
helper.insertAgent(a);
}
}
}
}
Main.JAVA
public class MainActivity extends ActionBarActivity {
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void onButtonClick(View v)
{
if(v.getId() == R.id.Bconnexion)
{
EditText a = (EditText)findViewById(R.id.TFmatricule);
String mat = a.getText().toString();
EditText b = (EditText)findViewById(R.id.TFpass);
String pass = b.getText().toString();
String mot_de_pass = helper.searchPass(mat);
if(pass.equals(mot_de_pass))
{
Intent i = new Intent(MainActivity.this, Display.class);
i.putExtra("Matricule",mat);
startActivity(i);
}
else
{
Toast temp = Toast.makeText(MainActivity.this , "Matricule et mot de passe incorrect!" , Toast.LENGTH_SHORT);
temp.show();
}
}
if(v.getId() == R.id.Binscrire)
{
Intent i = new Intent(MainActivity.this, InscRire.class);
startActivity(i);
}
}
#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);
}
}
Display.JAVA
public class Display extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
String matricule = getIntent().getStringExtra("Matricule");
TextView tv = (TextView)findViewById(R.id.TVmatricule);
tv.setText(matricule);
}
}
sinscrire.XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Matricule "
android:id="#+id/textView1" />
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/TFmatricule"
android:inputType="number"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Nom"
android:id="#+id/textView2" />
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/TFnom" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Prenom"
android:id="#+id/textView3" />
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/TFprenom" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Fonction"
android:id="#+id/textView4" />
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ems="10"
android:id="#+id/TFfonction" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Email"
android:id="#+id/textView5" />
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/TFemail" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Mot de passe"
android:id="#+id/textView6" />
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/TFpass1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Confirmer mot de passe"
android:id="#+id/textView7" />
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/TFpass2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Address"
android:id="#+id/textView8" />
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ems="10"
android:id="#+id/TFaddress" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Cin"
android:id="#+id/textView9" />
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="number"
android:ems="10"
android:id="#+id/TFcin" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Sinscrire"
android:id="#+id/Bsinscrire"
android:onClick="onSignUpClick" />
</LinearLayout>
</ScrollView>
</LinearLayout>
Main.XML
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Connexion"
android:id="#+id/Bconnexion"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="onButtonClick" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Matricule"
android:id="#+id/textView2"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/TFmatricule"
android:layout_below="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Mot de passe"
android:id="#+id/textView3"
android:layout_below="#+id/TFmatricule"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/TFpass"
android:layout_below="#+id/textView3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="S'inscrire ici"
android:id="#+id/Binscrire"
android:layout_below="#+id/Bconnexion"
android:layout_toRightOf="#+id/textView3"
android:layout_toEndOf="#+id/textView3"
android:onClick="onButtonClick" />
</RelativeLayout>
Display.XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Welcome,"
android:id="#+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/emptyString"
android:id="#+id/TVmatricule" />
</LinearLayout>

Related

Firestore data can't display on RecyclerView

The app quit when I change the line I am facing a problem when I try to develop an Android App that display the data from Firestore.
.
Can I know why it is not displaying the data on my RecyclerView and EventPage? I have rechecked everything, but I still can't find out why data doesn't show on EventPage.
EventPage.java
public class EventPage extends AppCompatActivity {
private static final String TAG = "DashboardFragment";
private FirestoreRecyclerAdapter<EventModel, EventViewHolder> adapter;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_page);
//Set recyclerView
recyclerView = findViewById(R.id.recyclerEventCard);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference cRef = db.collection("event");
Query query = db.collection("event").orderBy("ASC").limit(10);
FirestoreRecyclerOptions<EventModel> options = new FirestoreRecyclerOptions.Builder<EventModel>()
.setQuery(query, EventModel.class)
.build();
adapter = new FirestoreRecyclerAdapter<EventModel, EventViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull EventViewHolder holder, int position, #NonNull EventModel model) {
holder.textViewEName.setText(model.getEName());
holder.textViewEDate.setText(model.getEDate());
holder.textViewEVenue.setText(model.getEVenue());
holder.textViewEDesc.setText(model.getEDesc());
}
#NonNull
#Override
public EventViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//Changes on XML file. Try it.
View v=LayoutInflater.from(parent.getContext()).inflate(R.layout.event_card_list, parent, false);
return new EventViewHolder(v);
}
};
adapter.startListening();
recyclerView.setAdapter(adapter);
}
}
EventModel.java
package com.example.myvolunteer;
public class EventModel {
private String EName;
private String EDate;
private String EVenue;
private String EDesc;
//Constructor
public EventModel(){}
public EventModel(String EName, String EDate, String EVenue, String EDesc){
this.EName = EName;
this.EDate = EDate;
this.EVenue = EVenue;
this.EDesc = EDesc;
}
public String getEName() {
return EName;
}
public void setEName(String EName) {
this.EName = EName;
}
public String getEDate() {
return EDate;
}
public void setEDate(String EDate) {
this.EDate = EDate;
}
public String getEVenue() {
return EVenue;
}
public void setEVenue(String EVenue) {
this.EVenue = EVenue;
}
public String getEDesc() {
return EDesc;
}
public void setEDesc(String EDesc) {
this.EDesc = EDesc;
}
}
EventViewHolder.java
package com.example.myvolunteer;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import org.jetbrains.annotations.NotNull;
class EventViewHolder extends RecyclerView.ViewHolder{
TextView textViewEName, textViewEVenue, textViewEDate, textViewEDesc;
public EventViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
textViewEName = itemView.findViewById(R.id.textEventName);
textViewEDate = itemView.findViewById(R.id.textEventDate);
textViewEVenue = itemView.findViewById(R.id.textEventVenue);
textViewEDesc = itemView.findViewById(R.id.textEventDesc);
}
}
activity_event_page.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".EventPage">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerEventCard"
android:layout_width="351dp"
android:layout_height="663dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
event_card_list.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:orientation="vertical"
android:layout_height="wrap_content"
>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="250dp"
app:cardBackgroundColor="#B7F1FE"
app:cardCornerRadius="10dp"
app:cardElevation="10dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="432dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/textEventName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:text="Event Name"
android:textColor="#color/black"
android:textSize="25sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textEventDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:text="Date"
android:textColor="#color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/textEventVenue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:text="Venue"
android:textColor="#color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/textEventDesc"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:text="Description"
android:textColor="#color/black"
android:textSize="20sp" />
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp">
<TextView
android:id="#+id/createText"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:text="Created By: "
android:textColor="#color/black"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textEventCreatedBy"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:text="Leader Name"
android:textColor="#color/black"
android:textSize="15sp"
app:layout_constraintStart_toEndOf="#+id/createText"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:backgroundTint="#adcae6"
android:text="More Info"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:textColor="#color/black">
</Button>
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
make Sure your model class String variables are equal to your firestore data feild because it is very important to retrieve data from firestore
private String eventName;
private String eventDate;
private String eventVenue;
private String eventDescription;
//Constructor
public EventModel(){}
public EventModel(String eventName, String eventDate, String eventVenue, String eventDescription){
this.eventName = eventName;
this.eventDate = eventDate;
this.eventVenue = eventVenue;
this.eventDescription = eventDescription;
}
public String geteventName() {
return eventName;
}
public void seteventName(String eventName) {
this.eventName = eventName;
}
public String geteventDate() {
return eventDate;
}
public void seteventDate(String eventDate) {
this.eventDate = eventDate;
}
public String geteventVenue() {
return eventVenue;
}
public void seteventVenue(String eventVenue) {
this.eventVenue = eventVenue;
}
public String geteventDescription() {
return eventDescription;
}
public void seteventDescription(String eventDescription) {
this.eventDescription = eventDescription;
}
This looks wrong:
Query query = db.collection("event").orderBy("ASC").limit(10);
You are telling Firestore to sort by a field called ASC, which doesn't exist in your screenshot, so no documents are returned.
You probably want to sort on the ascending date, which you can do with:
Query query = db.collection("event").orderBy("eventDate", Direction.ASCENDING).limit(10);
Note that while the above will fix the problem of the documents not showing, they will still show up in the wrong order. This is because your eventDate field is not useful for sorting dates.
Strings in Firestore are sorted lexicographically, and in that order, "12/7/2021" becomes before "13/6/2021".
If you want to fix this problem, you can either store the dates as Firestore's built-in Timestamp type, or use a string format that allows sorting, like "2021-07-12" (which is *after* "2021-07-13"`.

Dispaying slitedata in edittext and textview in profileactivity and updating the data in profile

I have a login activity, registration activity, and profile activity. After I press the profile activity i want it to display user data in the profile.
I am trying to display data of sqlite database in profile activity in text view and edit text and update the data in the profile activity. Here is the code.
Here is my user profile xml.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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"
tools:context=".UserProfile">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="#fece2f"
android:padding="20dp">
<ImageView
android:id="#+id/profile_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerVertical="true"
android:src="#drawable/profile_image" />
<TextView
android:id="#+id/Username_profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#id/profile_image"
android:fontFamily="#font/alfa_slab_one"
android:includeFontPadding="false"
android:text="Ian Kipchumba"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="#+id/username_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/Username_profile"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/profile_image"
android:includeFontPadding="false"
android:text="ian kipchumba"
android:textSize="14sp" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/full_name_profile"
android:hint="User Name"
android:drawableLeft="#drawable/profile_icon"
android:drawablePadding="10dp"
android:layout_marginBottom="10dp"
android:text=""
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/admission_profile"
android:hint="Admission"
android:drawableLeft="#drawable/ic_adm"
android:drawablePadding="10dp"
android:layout_marginBottom="10dp"
android:text=""
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/password_profile"
android:hint="Password"
android:drawableLeft="#drawable/ic_lock"
android:drawablePadding="10dp"
android:layout_marginBottom="10dp"
android:text=""
/>
<Button
android:id="#+id/button_update"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fece2f"
android:fontFamily="#font/alfa_slab_one"
android:text="UPDATE"
android:onClick="run"/>
</LinearLayout>
</LinearLayout>
Here is my USERPROFILE.class
public class UserProfile extends AppCompatActivity {
DatabaseHelper db;
EditText name, admission, password;
TextView Username_profile, username_field;
Button btnviewUpdate;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
db = new DatabaseHelper(this);
//Hooks
name = (EditText) findViewById(R.id.full_name_profile);
admission = (EditText) findViewById(R.id.admission_profile);
password = (EditText) findViewById(R.id.password_profile);
Username_profile = (TextView) findViewById(R.id.Username_profile);
username_field = (TextView) findViewById(R.id.username_field);
btnviewUpdate = (Button) findViewById(R.id.button_update);
}
}
Here is my DATABASEHELPER.class
public class DatabaseHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME ="register.db";
public static final String TABLE_NAME ="registeruser";
public static final String COL_1 ="ID";
public static final String COL_2 ="username";
public static final String COL_3 ="admission";
public static final String COL_4 ="password";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE registeruser (ID INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT,admission TEXT, password TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL(" DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
public long addUser(String username, String admission, String password){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("username",username);
contentValues.put("admission",admission);
contentValues.put("password",password);
long res = db.insert("registeruser",null,contentValues);
db.close();
return res;
}
public boolean checkUser(String username, String password){
String[] columns = { COL_1, COL_3};
SQLiteDatabase db = getReadableDatabase();
String selection = COL_2 + "=?" + " and " + COL_4 + "=?";
String[] selectionArgs = { username, password };
Cursor cursor = db.query(TABLE_NAME,columns,selection,selectionArgs,null,null,null);
int count = cursor.getCount();
cursor.close();
db.close();
if(count>0)
return true;
else
return false;
}
}

databasehelper CRUD function

I am a newbie to android studio and have replicated sample code samples to fit my application. The purpose is to read all my company records. I have tried a couple variations without success. The error I get indicates Customers() can not be applied to: with a list of the fields beneath. I have 12 tables with CRUD methods for each. The same error for all tables is the same.
I have all the individual table.java files built and want to finish all the CRUD functions without errors before moving on to the main activity.java file.
// Get All CompanyData =========================================================
public List<CompanyData> GetAllCompanyData() {
List<CompanyData> compdataList = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_CompanyData;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
CompanyData compdata;
compdata = new CompanyData();
compdata.setcompanyid(Long.parseLong(cursor.getString(0))); // <==============================================================
compdata.setcompanyname(cursor.getString(1));
compdata.setcompanyaddress1(cursor.getString(2));
compdata.setcompanyaddress2(cursor.getString(3));
compdata.setcompanycity(cursor.getString(4));
compdata.setcompanystate(cursor.getString(5));
compdata.setcompanyzipcode(cursor.getString(6));
compdata.setcompanyphone(cursor.getString(7));
compdata.setcompanyemail(cursor.getString(8));
compdata.setcompanybusinesslicense(cursor.getString(9));
compdata.setcompanytype(cursor.getString(10));
compdataList.add(compdata);
} while (cursor.moveToNext());
}
return compdataList;
}
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="12dp"
android:gravity="center"
android:text="Username"
android:textSize="18sp"
android:textStyle="bold|italic" />
<EditText
android:id="#+id/editName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView"
android:ems="10"
android:gravity="center_vertical|center"
android:hint="Enter Name"
android:inputType="textPersonName"
android:textStyle="bold|italic" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/editName"
android:layout_marginTop="13dp"
android:gravity="center"
android:hint="Enter Password"
android:text="password"
android:textSize="18sp"
android:textStyle="bold|italic" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button"
android:layout_alignBottom="#+id/button"
android:layout_alignEnd="#+id/button4"
android:layout_alignRight="#+id/button4"
android:onClick="viewdata"
android:text="view data"
android:textSize="18sp"
android:textStyle="bold|italic" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/editPass"
android:layout_marginLeft="28dp"
android:layout_marginStart="28dp"
android:layout_marginTop="23dp"
android:onClick="addUser"
android:text="add user"
android:textSize="18sp"
android:textStyle="bold|italic" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button4"
android:layout_alignStart="#+id/button4"
android:layout_below="#+id/editText3"
android:layout_marginTop="13dp"
android:onClick="update"
android:text="Update"
android:textStyle="normal|bold" />
<EditText
android:id="#+id/editText6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/button4"
android:layout_toLeftOf="#+id/button2"
android:layout_toStartOf="#+id/button2"
android:ems="10"
android:freezesText="false"
android:hint="Enter Name to Delete Data"
android:inputType="textPersonName" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="41dp"
android:layout_marginEnd="21dp"
android:layout_marginRight="21dp"
android:onClick="delete"
android:text="delete"
android:textStyle="normal|bold"
tools:ignore="RelativeOverlap" />
<EditText
android:id="#+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/button"
android:layout_marginLeft="7dp"
android:layout_marginStart="7dp"
android:layout_marginTop="47dp"
android:ems="10"
android:hint="Current Name"
android:inputType="textPersonName"
android:textSize="14sp"
android:textStyle="bold|italic" />
<EditText
android:id="#+id/editPass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/textView2"
android:layout_marginTop="11dp"
android:ems="10"
android:gravity="center_vertical|center"
android:hint="Enter Password"
android:inputType="textPassword"
android:textAllCaps="false"
android:textSize="18sp"
android:textStyle="normal|bold" />
<EditText
android:id="#+id/editText5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText3"
android:layout_alignStart="#+id/editText3"
android:layout_alignTop="#+id/button3"
android:layout_marginTop="32dp"
android:ems="10"
android:hint="New Name"
android:inputType="textPersonName"
android:textSize="14sp"
android:textStyle="bold|italic" />
</RelativeLayout>'
main activityjava
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText Name, Pass , updateold, updatenew, delete;
DbAdapter helper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name= (EditText) findViewById(R.id.editName);
Pass= (EditText) findViewById(R.id.editPass);
updateold= (EditText) findViewById(R.id.editText3);
updatenew= (EditText) findViewById(R.id.editText5);
delete = (EditText) findViewById(R.id.editText6);
helper = new DbAdapter(this);
}
public void addUser(View view)
{
String t1 = Name.getText().toString();
String t2 = Pass.getText().toString();
if(t1.isEmpty() || t2.isEmpty())
{
Message.message(getApplicationContext(),"Enter Both Name and Password");
}
else
{
long id = helper.insertData(t1,t2);
if(id<=0)
{
Message.message(getApplicationContext(),"Insertion Unsuccessful");
Name.setText("");
Pass.setText("");
} else
{
Message.message(getApplicationContext(),"Insertion Successful");
Name.setText("");
Pass.setText("");
}
}
}
public void viewdata(View view)
{
String data = helper.getData();
Message.message(this,data);
}
public void update( View view)
{
String u1 = updateold.getText().toString();
String u2 = updatenew.getText().toString();
if(u1.isEmpty() || u2.isEmpty())
{
Message.message(getApplicationContext(),"Enter Data");
}
else
{
int a= helper.updateName( u1, u2);
if(a<=0)
{
Message.message(getApplicationContext(),"Unsuccessful");
updateold.setText("");
updatenew.setText("");
} else {
Message.message(getApplicationContext(),"Updated");
updateold.setText("");
updatenew.setText("");
}
}
}
public void delete( View view)
{
String uname = delete.getText().toString();
if(uname.isEmpty())
{
Message.message(getApplicationContext(),"Enter Data");
}
else{
int a= helper.delete(uname);
if(a<=0)
{
Message.message(getApplicationContext(),"Unsuccessful");
delete.setText("");
}
else
{
Message.message(this, "DELETED");
delete.setText("");
}
}
}
}'
DbAdapterjava
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbAdapter extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "myDatabase"; // Database Name
private static final String TABLE_NAME = "myTable"; // Table Name
private static final int DATABASE_Version = 1; // Database Version
private static final String UID = "_id"; // Column I (Primary Key)
private static final String NAME = "Name"; //Column II
private static final String MyPASSWORD = "Password"; // Column III
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME +
" (" + UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME + " VARCHAR(255) ," + MyPASSWORD + " VARCHAR(225));";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
private Context context;
public DbAdapter(Context context) {
super(context, DATABASE_NAME, null, DATABASE_Version);
this.context = context;
}
public long insertData(String name, String pass) {
SQLiteDatabase dbb = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME, name);
contentValues.put(MyPASSWORD, pass);
long id = dbb.insert(TABLE_NAME, null, contentValues);
return id;
}
public String getData() {
SQLiteDatabase db = getWritableDatabase();
String[] columns = {UID, NAME, MyPASSWORD};
Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext()) {
int cid = cursor.getInt(cursor.getColumnIndex(UID));
String name = cursor.getString(cursor.getColumnIndex(NAME));
String password = cursor.getString(cursor.getColumnIndex(MyPASSWORD));
buffer.append(cid + " " + name + " " + password + " \n");
}
return buffer.toString();
}
public int delete(String uname) {
SQLiteDatabase db = this.getWritableDatabase();
String[] whereArgs = {uname};
int count = db.delete(TABLE_NAME, NAME + " = ?", whereArgs);
return count;
}
public int updateName(String oldName, String newName) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME, newName);
String[] whereArgs = {oldName};
int count = db.update(TABLE_NAME, contentValues, NAME + " = ?", whereArgs);
return count;
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
} catch (Exception e) {
Message.message(context, "" + e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Message.message(context, "OnUpgrade");
db.execSQL(DROP_TABLE);
onCreate(db);
} catch (Exception e) {
Message.message(context, "" + e);
}
}
}'
Messagejava
import android.content.Context;
import android.widget.Toast;
public class Message {
public static void message(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
}'

How to work with Blob when trying to insert image into Sqlite database?

I am new in Android dev.
I am trying to create Android app with SQlite. I have a problem with inserting image in Blob. Text is easy to insert, but problem is with image. I know I need to use Blob, but question is, where to use it ? I need to use Imageview in my layout ?
I need to clic to image button, then insert image from SD card or mobile and then it save into Sqlite database with text. After it, retrive from Sqlite database.
Thank you for your attention and help.
There is my code:
MainActivity
public class MainActivity extends AppCompatActivity {
EditText etName,etRoll,etAddress,etBranch,etEmail,etImage;
Button btnSubmit,btngetdata,btndroptable;
DatabaseHelpher helpher;
List<DatabaseModel> dbList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dbList= new ArrayList<DatabaseModel>();
etName = (EditText)findViewById(R.id.etName);
etRoll = (EditText)findViewById(R.id.etRoll);
etAddress =(EditText)findViewById(R.id.etAddress);
etBranch = (EditText)findViewById(R.id.etBranch);
etEmail = (EditText)findViewById(R.id.etEmail);
etImage = (Image)findViewById(R.id.image); // ????
btnSubmit =(Button)findViewById(R.id.btnSubmit);
btngetdata =(Button)findViewById(R.id.btngetdata);
btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, SecondActivity.class));
// startActivity(new Intent(MainActivity.this, DetailsActivity.class));
}
});
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name=etName.getText().toString();
String email=etEmail.getText().toString();
String roll=etRoll.getText().toString();
String address=etAddress.getText().toString();
String branch=etBranch.getText().toString();
Blob image=etImage
if(name.equals("") || email.equals("") || roll.equals("") ||address.equals("")||branch.equals("")){
Toast.makeText(MainActivity.this,"Please fill all the fields",Toast.LENGTH_LONG).show();
}else {
helpher = new DatabaseHelpher(MainActivity.this);
helpher.insertIntoDB(name, email, roll, address, branch, image);
}
etName.setText("");
etRoll.setText("");
etAddress.setText("");
etBranch.setText("");
etEmail.setText("");
Toast.makeText(MainActivity.this, "insert value", Toast.LENGTH_LONG);
}
});
}}
DatabaseModel.java:
public class DatabaseModel {
private String name;
private String roll;
private String address;
private String branch;
private String email;
private String image;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImage() {
return image;
}
public void setImage (byte[] image) {
this.image = image;
}
}
DatabaseHelper.java:
public class DatabaseHelpher extends SQLiteOpenHelper {
private static final String DATABASE_NAME="student";
private static final int DATABASE_VERSION = 1;
private static final String STUDENT_TABLE = "stureg";
private static final String STU_TABLE = "create table "+STUDENT_TABLE +"(name TEXT,email TEXT primary key,roll TEXT,address TEXT,branch TEXT,,image BLOB)";
Context context;
public DatabaseHelpher(final Context context) {
super(context, Environment.getExternalStorageDirectory()
+ File.separator + DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(STU_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + STUDENT_TABLE);
// Create tables again
onCreate(db);
}
public void insertIntoDB(String name,String email,String roll,String address,String branch,byte[]image_data){
Log.d("insert", "before insert");
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put("name", name);
values.put("email", email);
values.put("roll", roll);
values.put("address", address);
values.put("branch", branch);
values.put("image", image_data);
// 3. insert
db.insert(STUDENT_TABLE, null, values);
// 4. close
db.close();
Toast.makeText(context, "insert value", Toast.LENGTH_LONG);
Log.i("insert into DB", "After insert");
}
public List<DatabaseModel> getDataFromDB(){
List<DatabaseModel> modelList = new ArrayList<DatabaseModel>();
String query = "select * from "+STUDENT_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);
if (cursor.moveToFirst()){
do {
DatabaseModel model = new DatabaseModel();
model.setName(cursor.getString(0));
model.setEmail(cursor.getString(1));
model.setRoll(cursor.getString(2));
model.setAddress(cursor.getString(3));
model.setBranch(cursor.getString(4));
model.setImage(cursor.getBlob(5)); //Add byte paramter in your DatabaseModel
modelList.add(model);
}while (cursor.moveToNext());
}
Log.d("student data", modelList.toString());
return modelList;
}
public void deleteARow(String email){
SQLiteDatabase db= this.getWritableDatabase();
db.delete(STUDENT_TABLE, "email" + " = ?", new String[] { email });
db.close();
}
}
activity_main.layout:
<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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="scroll|enterAlways" />
</android.support.design.widget.AppBarLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Email"/>
<EditText
android:id="#+id/etEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Branch"/>
<EditText
android:id="#+id/etBranch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Address"/>
<EditText
android:id="#+id/etAddress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Roll"/>
<EditText
android:id="#+id/etRoll"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Name"/>
<EditText
android:id="#+id/etName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/btnSubmit"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="uložit do databáze"
android:textColor="#ffffff"
android:background="#color/colorPrimary"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<Button
android:id="#+id/btngetdata"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Zobrazit seznam rumů"
android:textColor="#ffffff"
android:background="#color/colorPrimary"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
Activity_details.layout
<LinearLayout
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:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="scroll|enterAlways" />
</android.support.design.widget.AppBarLayout>
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="name"
android:paddingTop="15dp"
android:paddingLeft="20dp"
android:textSize="36sp" />
<TextView
android:id="#+id/roll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Roll"/>
<TextView
android:id="#+id/address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Address"/>
<TextView
android:id="#+id/branch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Branch"/>
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Email"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/image"/>
</LinearLayout>
Where to add the image view ? When I trying into layout, I don't know, where to impelement code into java classes ??
I need to help, now where to find how to do it. I need to hlep in my code, because it my homework. Please someone please help me.
Thank you
Save images in database is not good practice (save in folder is more beautiful).
But... How converter image view in byte[]
image = (ImageView)findViewById(R.id.qrcode);
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image=stream.toByteArray();
Then save you image byte[] in dataBase.
For #Peterr
What is wrong here ?
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name=etName.getText().toString();
String email=etEmail.getText().toString();
String roll=etRoll.getText().toString();
String address=etAddress.getText().toString();
String branch=etBranch.getText().toString();
image = (ImageView)findViewById(R.id.image); //error on image????
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap(); //error on image ????
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image=stream.toByteArray();
if(name.equals("") || email.equals("") || roll.equals("") ||address.equals("")||branch.equals("")){
Toast.makeText(MainActivity.this,"Please fill all the fields",Toast.LENGTH_LONG).show();
}else {
helpher = new DatabaseHelpher(MainActivity.this);
helpher.insertIntoDB(name, email, roll, address, branch, imageByteArray); //red is ImageByteArray ????
}
etName.setText("");
etRoll.setText("");
etAddress.setText("");
etBranch.setText("");
etEmail.setText("");
Toast.makeText(MainActivity.this, "insert value", Toast.LENGTH_LONG);
}
});
ImageView image = (ImageView)findViewById(R.id.image);
Is referent you ImageView component in XML layout.
In your second line of activity, you are declaring image EditText, this not is EditText, this is ImageView.
Steps :
obtain the image from image view.
convert image to byte array.
pass the byte array as data/parameter in your query for database

how to save spinner data and selected radio button saved to mysql database?

i cannot save selected radio buttons and spinner into mysql database? why is this?but for editText, it saves to my database.please help!
here is my submitData.php
<html>
<body>
<form action="submitData" method = "post">
Gender <input type = "radio" name="gender" value ="<?php echo $row['Gender']?>">
<input type = "radio" name="gender" value ="<?php echo $row['Gender']?>"
</form>
</body>
</html>
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Gender=$_POST['Gender'];
$Email = $_POST['Email'];
$Phone = $_POST['Phone'];
$IncidentType = $_POST['IncidentType'];
$Description = $_POST['Description'];
require_once('dbConnect.php');
$sql = "INSERT INTO user (Name,Age,Gender,Email,Phone,IncidentType,Description) VALUES ('$Name','$Age','$Gender','$Email','$Phone','$IncidentType','$Description')";
if(mysqli_query($con,$sql)){
echo "Successfully sent";
}else{
echo "Could not send";
}
}else{
echo 'error';
}
?>
here is my FormActivity.java:
public class FormActivity extends Activity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
private static final String REGISTER_URL = "http://khaty-ismail0.rhcloud.com/phptutorial/submitData.php";
private static final String SPINNER_URL = "http://khaty-ismail0.rhcloud.com/phptutorial/spinner_data.php";
public static final String KEY_NAME= "Name";
public static final String KEY_AGE = "Age";
public static final String KEY_EMAIL = "Email";
public static final String KEY_PHONE = "Phone";
public static final String KEY_DESCRIPTION = "Description";
public static final String KEY_TICKET = "ticket_id";
public static final String KEY_SOLUTION = "solution";
public static final String JSON_ARRAY = "result";
private EditText name_eT;
private EditText age_eT;
private EditText email_eT;
private EditText phone_eT;
private EditText descr_eT;
private Button subm_btn;
private Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
name_eT = (EditText) findViewById(R.id.name_eT);
age_eT = (EditText) findViewById(R.id.age_eT);
email_eT= (EditText) findViewById(R.id.email_eT);
phone_eT= (EditText) findViewById(R.id.phone_eT);
descr_eT= (EditText) findViewById(R.id.descr_eT);
subm_btn = (Button) findViewById(R.id.subm_btn);
subm_btn.setOnClickListener(this);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), spinner.getSelectedItem().toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void registerUser(){
final String Name = name_eT.getText().toString().trim();
final String Age = age_eT.getText().toString().trim();
final String Email = email_eT.getText().toString().trim();
final String Phone = phone_eT.getText().toString().trim();
final String Description = descr_eT.getText().toString().trim();
if(TextUtils.isEmpty(Name)) {
name_eT.setError("Please enter your name");
return;
}else if(TextUtils.isEmpty(Age)) {
age_eT.setError("Please enter your age");
return;
}else if(TextUtils.isEmpty(Phone)) {
phone_eT.setError("Please enter your phone");
return;
}else if(TextUtils.isEmpty(Email)) {
email_eT.setError("Please enter your email");
return;
}else if(TextUtils.isEmpty(Description)) {
descr_eT.setError("Please enter your issue");
return;
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(FormActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(FormActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_NAME,Name);
params.put(KEY_AGE,Age);
params.put(KEY_EMAIL, Email);
params.put(KEY_PHONE, Phone);
params.put(KEY_DESCRIPTION, Description);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void onCheckboxClicked(View V) {
boolean checked = ((RadioButton) V).isChecked();
switch (V.getId()) {
case R.id.male_rb:
if (checked)
break;
case R.id.female_rb:
if (checked)
break;
}
}
#Override
public void onClick(View v) {
if(v == subm_btn){
registerUser();
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void submitData(View view) {
Intent getResponse = new Intent(this,SubmitData.class);
final int result = 1;
startActivityForResult(getResponse, result);
}
}
here is my activity_form.java:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="#color/buttonFont"
tools:context="com.example.khadijah.brucertv2.FormActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/User_info"
android:id="#+id/userInfo"
android:textSize="30sp"
android:textColor="#color/colorFont"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Name:"
android:id="#+id/name_tV"
android:textColor="#color/colorFont"
android:layout_marginTop="24dp"
android:layout_below="#+id/userInfo"
android:layout_alignLeft="#+id/userInfo"
android:layout_alignStart="#+id/userInfo" />
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Age:"
android:id="#+id/age_tV"
android:textColor="#color/colorFont"
android:layout_alignBottom="#+id/age_eT"
android:layout_alignLeft="#+id/name_tV"
android:layout_alignStart="#+id/name_tV" />
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Gender"
android:id="#+id/gender_tV"
android:textColor="#color/colorFont"
android:layout_below="#+id/age_tV"
android:layout_alignLeft="#+id/age_tV"
android:layout_alignStart="#+id/age_tV"
android:layout_marginTop="24dp" />
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Email:"
android:id="#+id/email_tV"
android:textColor="#color/colorFont"
android:layout_alignBottom="#+id/email_eT"
android:layout_alignLeft="#+id/name_tV"
android:layout_alignStart="#+id/name_tV" />
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:text="Phone"
android:id="#+id/phone_tV"
android:textColor="#color/colorFont"
android:layout_alignBottom="#+id/phone_eT"
android:layout_alignLeft="#+id/gender_tV"
android:layout_alignStart="#+id/gender_tV" />
<EditText
android:layout_width="200dp"
android:layout_height="30dp"
android:layout_marginBottom="5dp"
android:inputType="textPersonName"
android:hint="#string/hint_required"
android:textColorHint="#color/buttonFont"
android:background="#drawable/border_style"
android:ems="10"
android:id="#+id/name_eT"
android:textColor="#color/inputFont"
android:layout_alignBottom="#+id/name_tV"
android:layout_alignRight="#+id/userInfo"
android:layout_alignEnd="#+id/userInfo" />
<EditText
android:layout_width="200dp"
android:layout_height="30dp"
android:inputType="number"
android:ems="10"
android:hint="#string/hint_required"
android:textColorHint="#color/buttonFont"
android:background="#drawable/border_style"
android:id="#+id/age_eT"
android:textColor="#color/inputFont"
android:layout_below="#+id/name_tV"
android:layout_alignRight="#+id/userInfo"
android:layout_alignEnd="#+id/userInfo" />
<EditText
android:layout_width="200dp"
android:layout_height="30dp"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/email_eT"
android:hint="#string/hint_required"
android:textColorHint="#color/buttonFont"
android:textColor="#color/inputFont"
android:background="#drawable/border_style"
android:layout_below="#+id/phone_eT"
android:layout_alignLeft="#+id/age_eT"
android:layout_alignStart="#+id/age_eT" />
<EditText
android:layout_width="200dp"
android:layout_height="30dp"
android:inputType="phone"
android:ems="10"
android:id="#+id/phone_eT"
android:layout_marginBottom="5dp"
android:textColor="#color/inputFont"
android:hint="#string/hint_required"
android:textColorHint="#color/buttonFont"
android:background="#drawable/border_style"
android:layout_below="#+id/gender_tV"
android:layout_alignLeft="#+id/email_eT"
android:layout_alignStart="#+id/email_eT" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/incident_info"
android:id="#+id/incidentInfo"
android:textColor="#color/colorFont"
android:textStyle="bold"
android:textSize="30sp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:prompt="#array/incident_type"
android:entries="#array/incident_type"
android:layout_below="#+id/incidentInfo"
android:layout_alignLeft="#+id/phone_eT"
android:layout_alignStart="#+id/phone_eT"
android:layout_alignRight="#+id/phone_eT"
android:layout_alignEnd="#+id/phone_eT"
android:spinnerMode="dropdown" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/incident_type_DD"
android:textColor="#color/colorFont"
android:id="#+id/incident_DD"
android:layout_below="#+id/incidentInfo"
android:layout_toLeftOf="#+id/spinner"
android:layout_toStartOf="#+id/spinner" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/description"
android:id="#+id/description_tV"
android:textColor="#color/colorFont"
android:layout_below="#+id/spinner"
android:layout_alignLeft="#+id/phone_tV"
android:layout_alignStart="#+id/phone_tV" />
<EditText
android:layout_width="300dp"
android:layout_height="80dp"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/descr_eT"
android:hint="#string/descr_hint"
android:textColorHint="#color/buttonFont"
android:gravity="top"
android:background="#drawable/border_style"
android:textColor="#color/inputFont"
android:layout_below="#+id/description_tV"
android:layout_alignLeft="#+id/description_tV"
android:layout_alignStart="#+id/description_tV" />
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_margin="5dp"
android:text="SUBMIT"
android:onClick="submitData"
android:textStyle="bold"
android:textSize="35sp"
android:id="#+id/subm_btn"
android:background="#drawable/custom_btn"
android:textColor="#color/buttonFont"
android:layout_alignParentBottom="true"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignLeft="#+id/phone_eT"
android:layout_alignStart="#+id/phone_eT"
android:layout_below="#+id/age_eT"
android:layout_alignRight="#+id/descr_eT"
android:layout_alignEnd="#+id/descr_eT"
android:layout_above="#+id/phone_eT"
android:weightSum="1"
android:id="#+id/radioGroup">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:text="Male"
android:id="#+id/male_rb"
android:onClick="onCheckboxClicked"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:checked="false"
android:id="#+id/female_rb"
android:onClick="onCheckboxClicked"/>
</RadioGroup>
</RelativeLayout>
here is my arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="incident_type">
<item>Fraud</item>
<item>Malicious Code</item>
<item>Spam</item>
<item>Intrusion</item>
<item>Not Sure</item>
</string-array>
</resources>
the form name is case sensitive.
use $_POST['gender'];
another thing is. where is your definition of $row? looks like it may be empty so you will not post any data.
enable error_reporting and display_errors while development help you to find such kind of errors much faster
another thing very important dont use mysql_* functions they are insecure and deprecated. have a look ad PDO instead
also use prepared statements and escape userinput.

Categories

Resources