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.
Related
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);
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 recently wanted to develop a shopping list app and i followed this tutorial, but in this tutorial the tutor shows that his added items are stored but I followed the same process but when I close and reopen the app the added items are gone. what can be done to fix this?
here is my program code:
package com.dopenets.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import android.app.AlertDialog;
import android.widget.EditText;
import android.content.DialogInterface;
import android.content.Context;
import android.content.SharedPreferences;
import android.app.Activity;
import android.widget.Toast;
import android.widget.AdapterView;
import android.widget.TextView;
import android.view.View;
public class MainActivity extends AppCompatActivity {
ArrayList<String> shoppingList = null;
ArrayAdapter<String> adapter = null;
ListView lv = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
shoppingList = getArrayVal(getApplicationContext());
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, shoppingList);
lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, final int position, long id) {
String selectedItem = ((TextView) view).getText().toString();
if (selectedItem.trim().equals(shoppingList.get(position).trim())) {
removeElement(selectedItem, position);
} else {
Toast.makeText(getApplicationContext(),"Error Removing Element", Toast.LENGTH_LONG).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();
if (id == R.id.action_add){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add Item");
final EditText input = new EditText(this);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
shoppingList.add(preferredCase(input.getText().toString()));
Collections.sort(shoppingList);
lv.setAdapter(adapter);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
return true;
}
return super.onOptionsItemSelected(item);
}
public static String preferredCase(String original)
{
if (original.isEmpty())
return original;
return original.substring(0, 1).toUpperCase() + original.substring(1).toLowerCase();
}
public static void storeArrayVal( ArrayList<String> inArrayList, Context context)
{
Set<String> WhatToWrite = new HashSet<String>(inArrayList);
SharedPreferences WordSearchPutPrefs = context.getSharedPreferences("dbArrayValues", Activity.MODE_PRIVATE);
SharedPreferences.Editor prefEditor = WordSearchPutPrefs.edit();
prefEditor.putStringSet("myArray", WhatToWrite);
prefEditor.commit();
}
public static ArrayList getArrayVal( Context dan)
{
SharedPreferences WordSearchGetPrefs = dan.getSharedPreferences("dbArrayValues",Activity.MODE_PRIVATE);
Set<String> tempSet = new HashSet<String>();
tempSet = WordSearchGetPrefs.getStringSet("myArray", tempSet);
return new ArrayList<String>(tempSet);
}
public void removeElement(String selectedItem, final int position){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Remove " + selectedItem + "?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
shoppingList.remove(position);
Collections.sort(shoppingList);
storeArrayVal(shoppingList, getApplicationContext());
lv.setAdapter(adapter);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
}
It appears that you are not calling the storeArrayVal method when an item is added, so nothing is ever stored.
I am making an app in android Studio and if you open the app on your phone you see the Launcer activity. I have a button that sends you to a new activity where te game is located. Once i click the Start button, The app closes and doesn't goes to the other activity. Why is that?
This is my code of the Launcher activity:
package joenio.sirname;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class SirName_launcher extends AppCompatActivity {
public static Button button_start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sir_name_launcher);
StartButton();
}
public void StartButton(){
button_start = (Button) findViewById(R.id.button_start);
button_start.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent("joenio.sirname.Game");
startActivity(intent1);
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_sir_name_launcher, 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);
}
}
And this is the code of the second activity:
package joenio.sirname;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import android.widget.Toast;
public class Game extends AppCompatActivity {
public static EditText editText_surname;
public static TextView textView_name;
public static Button button_check;
int x =0; //to keep track of qustions
//Context editText_this = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Displayquestions();
}
public void Displayquestions(){
final ArrayList<String> mQuestionList = new ArrayList<>();
mQuestionList.add("1+2");
mQuestionList.add("6+8");
mQuestionList.add("5 * 6");
mQuestionList.add("8*5");
mQuestionList.add("6+16");
mQuestionList.add("18-5");
textView_displayquestion.setText((mQuestionList.get(x)));//displayquestion is textview
final ArrayList<String> mAnswerList=new ArrayList<>();
mAnswerList.add("3");
mAnswerList.add("14");
mAnswerList.add("30");
mAnswerList.add("40");
mAnswerList.add("22");
mAnswerList.add("13");
//button_check is the button when user click it will first check answer and than move to next question if answer is correct
button_check.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//editText_this;
String answer = editText_ans.getText().toString();
if (answer.equals(mAnswerList.get(x))) {
x = x + 1;
textView_displayquestion.setText(mQuestionList.get(x)); //answer is correct display next quesion
Toast.makeText(getApplication().getBaseContext(),
(R.string.Nice), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(),
(R.string.tryagain), Toast.LENGTH_SHORT).show();
}
}
});
}
}
You are no where initializing your TextView and Button which must be causing NullPointerException.
Change your Game activity like this
TextView textView_displayquestion;
Button button_check;
EditText editText_ans;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
textView_displayquestion = (TextView)findViewById(R.id.displayquestion); //change as per your id
button_check = (Button)findViewById(R.id.buttoncheck); //change as per your id
editText_ans = (EditText)findViewById(R.id.answer); //change as per your id
Displayquestions();
}
In your button click , change the code as below.
Intent intent1 = new Intent(SirName_launcher.this, Game.class);
startActivity(intent1);
And also add the new Game Activity in your Manifest file too.
I am making a simple application, you put your name, click in a button, select a hobby and then it returns to the main layout your name and hobby together. I am having a problem when i click in the "Cancelar (Cancel)" button the application keeps getting a fatal error. What do you thing it could be?
MainActivity:
package com.example.holaamigos;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static String EXTRA_SALUDO = "com.example.holaamigos.SALUDO";
TextView txtfinal;
String saludo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtNombre = (EditText)findViewById(R.id.TxtNombre);
final Button btnHola = (Button)findViewById(R.id.BtnHola);
final CheckBox checkbox1 =(CheckBox)findViewById(R.id.checkBox1);
txtfinal=(TextView)findViewById(R.id.textView1);
checkbox1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0,
boolean checked) {
if (checked)
{
Toast.makeText(checkbox1.getContext(), "Activo", Toast.LENGTH_LONG).show();
btnHola.setVisibility(0);
btnHola.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ActivitySaludo.class);
saludo = txtNombre.getText().toString();
intent.putExtra(EXTRA_SALUDO, saludo);
startActivityForResult(intent, 1);
}
});
}
else
{
Toast.makeText(checkbox1.getContext(), "Inactivo", Toast.LENGTH_SHORT).show();
btnHola.setVisibility(View.INVISIBLE);
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK);
String string= data.getStringExtra("HOBBY");
txtfinal.setText("Nombre:" + saludo + " " + "Hobby:" + string);
if (resultCode == RESULT_CANCELED){
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
ActivitySaludo:
package com.example.holaamigos;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class ActivitySaludo extends Activity {
String myspinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saludo);
Intent intent = getIntent();
String saludo = intent.getStringExtra(MainActivity.EXTRA_SALUDO);
TextView txtCambiado = (TextView) findViewById(R.id.TxtSaludo);
txtCambiado.setText(getString(R.string.hola_saludo) + " " + saludo);
final Spinner spinner = (Spinner)findViewById(R.id.SpinnerSaludo);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.hobby, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener () {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
parent.getItemAtPosition(pos);
myspinner = spinner.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
//another call
}
});
final Button BtnAceptar=(Button) findViewById(R.id.buttonAceptar);
BtnAceptar.setOnClickListener(new OnClickListener (){
#Override
public void onClick(View v) {
Intent iboton = new Intent();
iboton.putExtra("HOBBY", myspinner);
setResult(RESULT_OK, iboton);
finish();
}
});
final Button BtnCancelar=(Button) findViewById(R.id.buttonCancelar);
BtnCancelar.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Intent iboton2 = new Intent();
iboton2 = null;
setResult(RESULT_CANCELED, iboton2);
finish();
}
});
}
}
if (resultCode == RESULT_OK);
String string= data.getStringExtra("HOBBY");
txtfinal.setText("Nombre:" + saludo + " " + "Hobby:" + string);
this is where the error is.. you need to remove the ; from the end of if statement and put { there and similarly end the block with }