i'm trying to get value from 2nd column in the database and put it into textview by clicking listview item.
DBConnection class
package com.prodev;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
/**
* Created by Dev_Mohamed_Sayed on 7/21/2017.
*/
public class DBConnection extends SQLiteOpenHelper {
public static final String DbName="azkar.db";
public static final int Version=1;
public DBConnection(Context context){
super(context,DbName,null,Version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS azkar_main ( ID INTEGER, Name TEXT, Number INTEGER, PRIMARY KEY(ID) )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS azkar_main");
onCreate(db);
}
public void InsertRowAdmin(String Name,Integer Number){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Name", Name);
contentValues.put("Number", Number);
db.insert("azkar_main", null, contentValues);
}
public ArrayList getAllRecord2(){
ArrayList array_list2 = new ArrayList();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from azkar_main", null);
res.moveToFirst();
while (res.isAfterLast() == false){
array_list2.add(res.getString(res.getColumnIndex("ID"))+ " - " + res.getString(res.getColumnIndex("Name"))+ " .. " + res.getString(res.getColumnIndex("Number")));
res.moveToNext();
}
return array_list2;
}
public void delete(Integer ID){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from azkar_main where ID="+ Integer.toString(ID));
}
}
and here is my Acivity where we should work in.
package com.prodev;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.R.layout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import java.util.ArrayList;
public class ListActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
setContentView(R.layout.activity_list);
DBConnection db = new DBConnection(this);
ListView ls =(ListView)findViewById(R.id.ls);
ArrayList<String> arrlist = db.getAllRecord2();
ls.setAdapter(new ArrayAdapter<>(this, layout.simple_list_item_1, arrlist));
ListView lv = (ListView) findViewById(R.id.ls);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(ListActivity.this, MainActivity.class);
startActivity(i);
ListView lv = (ListView) findViewById(R.id.ls);
TextView tv = (TextView) findViewById(R.id.textView);
// The Missing Part
}
});
}
public void btn_save(View view){
EditText editText =(EditText)findViewById(R.id.editText);
ListView ls =(ListView)findViewById(R.id.ls);
DBConnection db = new DBConnection(this);
db.InsertRowAdmin(editText.getText().toString(), 0);
ArrayList<String> arrlist = db.getAllRecord2();
ls.setAdapter(new ArrayAdapter<>(this, layout.simple_list_item_1, arrlist));
editText.setText("");
}
public void btn_delete(View view){
EditText txt = (EditText)findViewById(R.id.del);
ListView ls = (ListView)findViewById(R.id.ls);
DBConnection db = new DBConnection(this);
db.delete(Integer.parseInt(txt.getText().toString()));
ArrayList<String> arrlist=db.getAllRecord2();
ls.setAdapter(new ArrayAdapter<>(this, layout.simple_list_item_1, arrlist));
txt.setText("");
}
}
MainActivity
package com.prodev;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.crash.FirebaseCrash;
public class MainActivity extends AppCompatActivity {
private FirebaseAnalytics mFirebaseAnalytics;
private static final String TAG = "MainActivity";
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
FirebaseCrash.log("Activity created");
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
setContentView(R.layout.activity_main);
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// action with ID action_refresh was selected
case R.id.action_azkar:
Intent i = new Intent(MainActivity.this, ListActivity.class);
startActivity(i);
break;
case R.id.action_settings:
break;
default:
break;
}
return true;
}
}
Also i want to save number from variable will be declared later into database col Number..
i don't know how but i'll worry about that later..
On you list item click event,
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(ListActivity.this, MainActivity.class);
i.putExtra("keyText","value to be passed!");
startActivity(i);
}
and in you main activity,
Intent i = getIntent();
String text = i.getStringExtra("keyText");
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(text);
Related
when I click delete it doesn't delete or edit the row I created
so my MainActivity is
package com.frolicfreak.bhushan.memo;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static com.frolicfreak.bhushan.memo.DatabaseHelper.Table_Name;
import static com.frolicfreak.bhushan.memo.DatabaseHelper.col1;
import static com.frolicfreak.bhushan.memo.DatabaseHelper.col2;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener{
FloatingActionButton fab;
DatabaseHelper mydb;
ListView listView;
ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb =new DatabaseHelper(this);
fab= (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(this);
ListView listView = (ListView)findViewById(R.id.list);
registerForContextMenu(listView);
}
#Override
public void onResume() {
super.onResume();
ArrayList<String> theList =new ArrayList<>();
Cursor data= mydb.getAllData();
listView = (ListView)findViewById(R.id.list);
listView.setAdapter(null);
if (data.getCount()==0){
Toast.makeText(MainActivity.this,"data not inserted",Toast.LENGTH_LONG).show();
}
else
{
while(data.moveToNext()){
theList.add(data.getString(1));
ListAdapter listAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.list) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()) {
case R.id.edit:
// int count= mydb.updaterow(getString(col2),EditText.)
return true;
case R.id.delete:
int count=mydb.deleterow(getString(item.getItemId()));
onResume();
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public void onClick(View v) {
Intent intent= new Intent(this,Main2Activity.class);
startActivity(intent);
}
}
My DataBasehelper class
package com.frolicfreak.bhushan.memo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.EditText;
import java.util.ArrayList;
/**
* Created by BHUSHAN on 24-08-2017.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String Database_Name = "Memo.db";
public static final String Table_Name = "Memo";
public static final String col1 = "ID";
public static final String col2 = "data";
//DatabaseHelper mydb;
public DatabaseHelper(Context context) {
super(context, Database_Name, null, 1);
//mydb=new DatabaseHelper(context);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + Table_Name + "(ID integer primary key autoincrement, data text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + Table_Name);
onCreate(db);
}
public boolean insertData(String data, String Data) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col2, Data);
long result = db.insert(Table_Name, null, contentValues);
if (result==-1)
return false;
else
return true;
}
public ArrayList<String> getList(){
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.query(Table_Name,new String[]{col1},new String(col2),null,null,null,null);
while (cursor.moveToNext()){
int index= cursor.getColumnIndex(col1);
taskList.add(cursor.getString(index));
}
cursor.close();
db.close();
return taskList;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM " + Table_Name, null);
return res;
}
public int deleterow(String col1) {
String whereClause = "ID = ?";
String[] whereArgs = {String.valueOf(col1)};
SQLiteDatabase db = this.getWritableDatabase();
int count = db.delete(Table_Name, whereClause, whereArgs);
db.close();
return count;
}
/* public int updaterow(String oldname, String newdata){
SQLiteDatabase db= mydb.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(DatabaseHelper.col2,newdata);
String[] whereargs={oldname};
int count = db.update(Table_Name,cv, DatabaseHelper.col2+"=?" , whereargs);
return count;
}*/
}
my Main2Activity class where I edit and insert data
package com.frolicfreak.bhushan.memo;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Main2Activity extends AppCompatActivity {
DatabaseHelper db;
EditText Data;
FloatingActionButton add;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
db = new DatabaseHelper(this);
Data = (EditText)findViewById(R.id.edit);
add =(FloatingActionButton)findViewById(R.id.add);
AddData();
}
public void AddData(){
add.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted =
db.insertData(Data.getText().toString(),
Data.getText().toString() );
if (isInserted==true)
Toast.makeText(Main2Activity.this,"data
inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(Main2Activity.this,"data not
inserted",Toast.LENGTH_LONG).show();
}
}
);
}
}
please help me I'm new to programming so I'm trying to learn here
thankyou in advance
and I actually need help with editing and saving the data too I wrote the code but I saved it in the comments
Your delete function is working fine according to the code. Check the return is greater than 0 or not.
But you won't be able to see the changes in the ListView because you have to populate the list again.
Set an CursorAdapter since you're using a database to link to the listview and use CursorAdapter.notifyDataSetChanged()
Or create a method that will recreate the listview when a delete occurs.
ArrayList<String> COUNTRIES = new ArrayList<>();
public void refreshView() {
MyDatabase database = new MyDatabase(ViewList.this);
Cursor cursor = database.fetchAllData();
COUNTRIES.clear();
while (cursor.moveToNext()) {
String temp = cursor.getString(cursor.getColumnIndex(database.COL1));
COUNTRIES.add(temp);
}
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, COUNTRIES);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(arrayAdapter);
}
When deleting, you are calling this
int count=mydb.deleterow(getString(item.getItemId()));
onResume();
You are not passing the id of selected item, but you are passing menu item's string fetched by getString(...) method, which is weird. There are so much unused code in your class.
I advice you to work on BaseAdapter and ListView.
It's not a good programming pattern to call onResume() method. You should extract it to different method and call it in onResume().
Anyway, in this case notifyDataSetChanged() is a solution what you are looking for.
I am pretty new to this whole android development but I am looking to create a simple android app making use of a sql database, cardViews and a RecycleView.
The app I have so far works but I am trying to add a button to the DetailedActivity which will allow me to remove the entry from the database.
The desired workflow would be:
Get Data
Select a CardView
Click New Button (will be
delete)
Go back to CardView, Remove entry on which the button has
been pressed and populate the CardView.
RecyclerAdapter.java
package com.example.prabhu.databasedemo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
static List<DatabaseModel> dbList;
static Context context;
RecyclerAdapter(Context context, List<DatabaseModel> dbList ){
this.dbList = new ArrayList<DatabaseModel>();
this.context = context;
this.dbList = dbList;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_row, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, int position) {
holder.name.setText(dbList.get(position).getName());
holder.email.setText(dbList.get(position).getEmail());
}
#Override
public int getItemCount() {
return dbList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView name,email;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
name = (TextView) itemLayoutView
.findViewById(R.id.rvname);
email = (TextView)itemLayoutView.findViewById(R.id.rvemail);
itemLayoutView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailsActivity.class);
Bundle extras = new Bundle();
extras.putInt("position",getAdapterPosition());
intent.putExtras(extras);
/*
int i=getAdapterPosition();
intent.putExtra("position", getAdapterPosition());*/
context.startActivity(intent);
Toast.makeText(RecyclerAdapter.context, "you have clicked Row " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
}
}
DatabaseHelper.java
package com.example.prabhu.databasedemo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
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)";
Context context;
public DatabaseHelpher(Context context) {
super(context, 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);
}
/* Insert into database*/
public void insertIntoDB(String name,String email,String roll,String address,String branch){
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);
// 3. insert
db.insert(STUDENT_TABLE, null, values);
// 4. close
db.close();
Toast.makeText(context, "insert value", Toast.LENGTH_SHORT);
Log.i("insert into DB", "After insert");
}
/* Retrive data from database */
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));
modelList.add(model);
}while (cursor.moveToNext());
}
Log.d("student data", modelList.toString());
return modelList;
}
/*delete a row from database*/
public void deleteARow(String email){
SQLiteDatabase db= this.getWritableDatabase();
db.delete(STUDENT_TABLE, "email" + " = ?", new String[] { email });
db.close();
}
}
DatabaseModel.java
package com.example.prabhu.databasedemo;
public class DatabaseModel {
private String name;
private String roll;
private String address;
private String branch;
private String email;
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;
}
}
MainActivity.java
package com.example.prabhu.databasedemo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
EditText etName,etRoll,etAddress,etBranch,etEmail;
Button btnSubmit,btngetdata;
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);
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();
if(name.equals("") || email.equals("") || roll.equals("") ||address.equals("")||branch.equals("")){
Toast.makeText(MainActivity.this,"Please fill all the fields",Toast.LENGTH_SHORT).show();
}else {
helpher = new DatabaseHelpher(MainActivity.this);
helpher.insertIntoDB(name, email, roll, address, branch);
}
etName.setText("");
etRoll.setText("");
etAddress.setText("");
etBranch.setText("");
etEmail.setText("");
Toast.makeText(MainActivity.this, "insert value", Toast.LENGTH_SHORT);
}
});
}
}
SecondActivity.java
package com.example.prabhu.databasedemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
public class SecondActivity extends AppCompatActivity {
DatabaseHelpher helpher;
List<DatabaseModel> dbList;
RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
helpher = new DatabaseHelpher(this);
dbList= new ArrayList<DatabaseModel>();
dbList = helpher.getDataFromDB();
mRecyclerView = (RecyclerView)findViewById(R.id.recycleview);
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
// specify an adapter (see also next example)
mAdapter = new RecyclerAdapter(this,dbList);
mRecyclerView.setAdapter(mAdapter);
}
#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_second, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
DetailedActivity.java
package com.example.prabhu.databasedemo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class DetailsActivity extends AppCompatActivity {
DatabaseHelpher helpher;
List<DatabaseModel> dbList;
int position;
TextView tvname,tvemail,tvroll,tvaddress,tvbranch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
// 5. get status value from bundle
position = bundle.getInt("position");
tvname =(TextView)findViewById(R.id.name);
tvemail =(TextView)findViewById(R.id.email);
tvroll =(TextView)findViewById(R.id.roll);
tvaddress =(TextView)findViewById(R.id.address);
tvbranch =(TextView)findViewById(R.id.branch);
helpher = new DatabaseHelpher(this);
dbList= new ArrayList<DatabaseModel>();
dbList = helpher.getDataFromDB();
if(dbList.size()>0){
String name= dbList.get(position).getName();
String email=dbList.get(position).getEmail();
String roll=dbList.get(position).getRoll();
String address=dbList.get(position).getAddress();
String branch=dbList.get(position).getBranch();
tvname.setText(name);
tvemail.setText(email);
tvroll.setText(roll);
tvaddress.setText(address);
tvbranch.setText(branch);
}
Toast.makeText(DetailsActivity.this, dbList.toString(), Toast.LENGTH_SHORT);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_details, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
I had added a button (findViewByID) in the DetailedAvtivity.java with an OnClickListener. Initially to only show a toast, however, when the button on any detailed view is clicked, nothing happens - no toast.
So really, questions are:
Where do I have to define the button and where do I implement the onClickListener?
How do I make the button delete the entry? For now I am happy to use the email from the email TextView (tvemail) but I will have to go back and refresh the cards as well.
Thanks all in advance
After some time I found the answer. What I was doing was correct but messed the toast command.
Basically what needs to be done is
delButton = (Button) findViewById(R.id.button);
delButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), tvemail.getText() + " deleted", Toast.LENGTH_SHORT).show();
startActivity(new Intent(DetailsActivity.this, MainActivity.class));
helpher.deleteARow((String) tvemail.getText());
}
});
I am working on a sql listview , however I want to display the listview which is in an activity class (CountryListActivity.java) as a fragment in a tablayout . dbManager=newDBManager(this) gives an error when I change it to getActivity , how do I fix this?
package com.trinitytabnavigationdrawer;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
public class CountryListActivity extends ActionBarActivity {
private DBManager dbManager;
private ListView listView;
private SimpleCursorAdapter adapter;
final String[] from = new String[] {
DatabaseHelper._ID,
DatabaseHelper.SUBJECT, DatabaseHelper.DESC
};
final int[] to = new int[] {
R.id.id, R.id.title, R.id.desc
};
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_emp_list);
dbManager = new DBManager(this);
dbManager.open();
Cursor cursor = dbManager.fetch();
listView = (ListView) findViewById(R.id.list_view);
listView.setEmptyView(findViewById(R.id.empty));
adapter = new SimpleCursorAdapter(this, R.layout.activity_view_record, cursor, from, to, 0);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
// OnCLickListiner For List Items
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {#
Override
public void onItemClick(AdapterView <? > parent, View view, int position, long viewId) {
TextView idTextView = (TextView) view.findViewById(R.id.id);
TextView titleTextView = (TextView) view.findViewById(R.id.title);
TextView descTextView = (TextView) view.findViewById(R.id.desc);
String id = idTextView.getText().toString();
String title = titleTextView.getText().toString();
String desc = descTextView.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(), ModifyCountryActivity.class);
modify_intent.putExtra("title", title);
modify_intent.putExtra("desc", desc);
modify_intent.putExtra("id", id);
startActivity(modify_intent);
}
});
}
#
Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#
Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.add_record) {
Intent add_mem = new Intent(this, AddCountryActivity.class);
startActivity(add_mem);
}
return super.onOptionsItemSelected(item);
}
}
And the database manager class is as follows :
package com.trinitytabnavigationdrawer;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DBManager {
private DatabaseHelper dbHelper;
private Context context;
private SQLiteDatabase database;
public DBManager(Context c) {
context = c;
}
public DBManager open() throws SQLException {
dbHelper = new DatabaseHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
public void insert(String name, String desc) {
ContentValues contentValue = new ContentValues();
contentValue.put(DatabaseHelper.SUBJECT, name);
contentValue.put(DatabaseHelper.DESC, desc);
database.insert(DatabaseHelper.TABLE_NAME, null, contentValue);
}
public Cursor fetch() {
String[] columns = new String[] {
DatabaseHelper._ID, DatabaseHelper.SUBJECT, DatabaseHelper.DESC
};
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public int update(long _id, String name, String desc) {
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.SUBJECT, name);
contentValues.put(DatabaseHelper.DESC, desc);
int i = database.update(DatabaseHelper.TABLE_NAME, contentValues, DatabaseHelper._ID + " = " + _id, null);
return i;
}
public void delete(long _id) {
database.delete(DatabaseHelper.TABLE_NAME, DatabaseHelper._ID + "=" + _id, null);
}
}
Please I have no clue what else to do ! Been trying for a week now , sorry I'm not good at this , just following some tutorials ! :(
Initialize the dbManager and other objects which require context inside onAttach (Context context) rather than onCreateView() method of Fragment.
i have a Activity Called "SecondActivity" below is full code
package br.exemplosqlite;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import org.w3c.dom.Text;
public class SecondActivity extends Activity implements AdapterView.OnItemSelectedListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//referencia a Spinner
//Spinner coligada;
//final TextView nome = (TextView)findViewById(R.id.txvNome);
//final TextView sobrenome = (TextView)findViewById(R.id.txvSobrenome);
//final Spinner pday = (Spinner)findViewById(R.id.spinner);
final Spinner spcoligada = (Spinner) findViewById(R.id.coligada);
//spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter adaptercoligada = ArrayAdapter.createFromResource(this, R.array.coligada, android.R.layout.simple_spinner_item);
spcoligada.setAdapter(adaptercoligada);
Button ok = (Button)findViewById(R.id.btnok);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//chamada para a nova Activity
Intent intent = new Intent(SecondActivity.this, ListUsersActivity.class);
intent.putExtra("coligada", spcoligada.getSelectedItem().toString());
//intent.putExtra("nomePessoa", nome.getText().toString());
//intent.putExtra("sobrenomePessoa", sobrenome.getText().toString());
//intent.putExtra("day", pday.getSelectedItem().toString());
startActivity(intent);
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
But , what i really want is , pass the item selected on Spinner , go to my BD.class on query , below is my "BD.class"
package br.exemplosqlite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.SyncStateContract;
import android.widget.Spinner;
public class BD {
private SQLiteDatabase bd;
public BD(Context context){
BDCore auxBd = new BDCore(context);
bd = auxBd.getWritableDatabase();
}
public void inserir(Produtos produtos){
ContentValues valores = new ContentValues();
valores.put("item", produtos.getItem());
valores.put("coligada", produtos.getColigada());
valores.put("filial", produtos.getFilial());
bd.insert("produtos2", null, valores);
}
public void atualizar(Produtos produtos){
ContentValues valores = new ContentValues();
valores.put("item", produtos.getItem());
valores.put("coligada", produtos.getColigada());
valores.put("filial", produtos.getFilial());
bd.update("produtos2", valores, "_id = ?", new String[]{""+produtos.getId()});
}
public void deletar(Produtos produtos){
bd.delete("produtos2", "_id = "+produtos.getId(), null);
}
public List<Produtos> buscar(){
List<Produtos> list = new ArrayList<Produtos>();
String[] colunas = new String[]{"_id", "item", "coligada","filial"};
Cursor cursor = bd.rawQuery("select * from produtos2",null);
if(cursor.getCount() > 0){
cursor.moveToFirst();
do {
Produtos p = new Produtos();
p.setId(cursor.getLong(0));
p.setItem(cursor.getString(1));
p.setColigada(cursor.getString(2));
p.setFilial(cursor.getString(3));
list.add(p);
} while(cursor.moveToNext());
}
return(list);
}
}
so , i want change this : Cursor cursor = bd.rawQuery("select * from produtos2",null);
to this :
Cursor cursor = bd.rawQuery("select * from "+itemselected,null);
That is the code for your solution.
Spinner spcoligada = (Spinner) findViewById(R.id.coligada);
private static final String itemSelected=spcoligada.getSelectedItem();
Cursor cursor = bd.query(itemSelected, new String[]{ColumnName1, ColumnName2, Column2,ColumnName3,ColumnName4},
null, null, null, null, null);
I have found the Solution.
I create a class Global , and after this i assing the value of global variable to my Spiner on Select .
I'm making an app that will let users add their school subjects.
Before i continue let me give you my code:
MainActivity:
package cannon.gaming.mymarks;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends ActionBarActivity {
TextView textSubject;
String SUBJECT, PASS;
Context ctx = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
/*Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), RegisterActivity.class);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivityForResult(intent, 0);
}
});*/
Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
textSubject = (TextView) findViewById(R.id.textSubject);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showInputDialog();
}
});
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.activity_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SUBJECT = editText.getText().toString();
PASS = "0";
DatabaseOperations DB = new DatabaseOperations(ctx);
DB.putInformation(DB, SUBJECT, PASS);
Toast.makeText(getBaseContext(), "Subject added", Toast.LENGTH_SHORT).show();
finish();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
#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;
}
#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);
}
}
TableData:
package cannon.gaming.mymarks;
import android.provider.BaseColumns;
/**
* Created by Asuspc on 01/07/2015.
*/
public class TableData {
public TableData()
{
}
public static abstract class TableInfo implements BaseColumns
{
public static final String USER_NAME = "user_name";
public static final String USER_PASS = "user_pass";
public static final String DATABASE_NAME = "user_info";
public static final String TABLE_NAME = "reg_info";
}
}
DatabaseOperations:
package cannon.gaming.mymarks;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by Asuspc on 01/07/2015.
*/
public class DatabaseOperations extends SQLiteOpenHelper {
public static final int database_version = 1;
public String CREATE_QUERY = "CREATE TABLE "+ TableData.TableInfo.TABLE_NAME+"("+ TableData.TableInfo.USER_NAME+" TEXT,"+ TableData.TableInfo.USER_PASS+" TEXT);";
public DatabaseOperations(Context context) {
super(context, TableData.TableInfo.DATABASE_NAME, null, database_version);
Log.d("Database Operations", "Database created");
}
#Override
public void onCreate(SQLiteDatabase sdb)
{
sdb.execSQL(CREATE_QUERY);
Log.d("Database Operations", "Table created");
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2)
{
}
public void putInformation(DatabaseOperations dop,String name, String pass)
{
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_NAME, name);
cv.put(TableData.TableInfo.USER_PASS, pass);
long k = SQ.insert(TableData.TableInfo.TABLE_NAME, null, cv);
Log.d("Database Operations", "One row inserted");
}
public Cursor getInformation(DatabaseOperations dop)
{
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] columns = {TableData.TableInfo.USER_NAME, TableData.TableInfo.USER_PASS};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, columns, null, null, null, null, null);
return CR;
}
}
Now let me explain.
When I press the "buttonAdd" button it will let me enter the subject name obviously, and save it in database.
But what I can't make is, I want to display all database on MainActivity.
And it should be like this:
names of subjects on the left side,
average of those subjects on the right side (the string PASS should be that average, that's why it is 0 when you first add the subject).
And I want to make each of those subjects clickable, so when you click it it should show you all marks from that subject and let you add or remove them.
Now, I guess, displaying data shouldn't be so hard, but still I need your help.
But making each subject clickable I really have no idea how.
And each subject having its own marks, I don't know, does it mean new activity for every new subject or new database or what?
EDIT:
MainActivity now:
package cannon.gaming.mymarks;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends ActionBarActivity {
String SUBJECT, PASS;
Context CTX = this;
private SimpleCursorAdapter adapter;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
/*Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), RegisterActivity.class);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivityForResult(intent, 0);
}
});*/
Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
displayListView();
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showInputDialog();
}
});
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.activity_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SUBJECT = editText.getText().toString();
PASS = "0";
DatabaseOperations DB = new DatabaseOperations(CTX);
DB.putInformation(DB, SUBJECT, PASS);
Toast.makeText(getBaseContext(), "Subject added", Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
displayListView();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
#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;
}
#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);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void displayListView()
{
DatabaseOperations DOP = new DatabaseOperations(CTX);
Cursor CR = DOP.getInformation(DOP);
CR.moveToFirst();
// The desired columns to be bound
String[] columns = new String[]{
TableData.TableInfo.USER_NAME,
TableData.TableInfo.USER_PASS
};
// the XML defined views which the data will be bound to
int[] to = new int[]{
R.id.code,
R.id.name,
};
adapter = new SimpleCursorAdapter(
this, R.layout.activity_login,
CR,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listView);
// Assign adapter to ListView
listView.setAdapter(adapter);
}
}
To display data, you should use ListView and CursorAdapter.
Here is sample code for you: http://www.mysamplecode.com/2012/07/android-listview-cursoradapter-sqlite.html
In that sample code, you can see:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String countryCode =
cursor.getString(cursor.getColumnIndexOrThrow("code"));
Toast.makeText(getApplicationContext(),
countryCode, Toast.LENGTH_SHORT).show();
}
});
OnItemClickListener will help you to handle when a item in the listview is clicked.
Hope this will help you.