ID value returning null - android

I am new to android programming and would like some help or advise as to why whenever I try and update records in the database by clicking on the update button the id that is meant to passed through is null so it wont update. How do I get it so that the Id is not null when updating.
DatabaseHelper.java
package com.example.warre.sqlliteapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "tracker.db";
public static final String TABLE_NAME = "tracker_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "SALES";
public static final String COL_3 = "FOLLOW";
public static final String COL_4 = "DONE";
public static final String COL_5 = "LEADER";
public static final String COL_6 = "TRAIN";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,SALES INTEGER,FOLLOW INTEGER,DONE INTEGER, LEADER INTEGER, TRAIN INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String sales,String follow,String done, String leader, String train) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,sales);
contentValues.put(COL_3,follow);
contentValues.put(COL_4,done);
contentValues.put(COL_5,leader);
contentValues.put(COL_6, train);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public boolean updateData(String id,String sales,String follow,String done, String leader, String train) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,id);
contentValues.put(COL_2,sales);
contentValues.put(COL_3,follow);
contentValues.put(COL_4,done);
contentValues.put(COL_5, leader);
contentValues.put(COL_6, train);
db.update(TABLE_NAME, contentValues, "ID = ?",new String[] { id });
return true;
}
public Integer deleteData (String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?",new String[] {id});
}
}
MainActivity
The problem is happening in the updateData() where editTextId is getting null or returning null.
package com.example.warre.sqlliteapp;
import android.app.Activity;
import android.database.Cursor;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends Activity {
DatabaseHelper myDb;
EditText editTextId;
TextView txtSales,txtFollow,txtDone,txtLeader,txtTrain, TimerValue;
Button btnAddData;
Button btnviewAll;
Button btnDelete;
Button SALES,FOLLOW,DONE,LEADER,TRAIN, STOP, REPORT;
int countSales = 0;
int countFollow = 0;
int countDone = 0;
int nCounter = 0;
String timeName;
TimerTask mTimerTask;
final Handler handler = new Handler();
Timer t = new Timer();
Button btnviewUpdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_money);
myDb = new DatabaseHelper(this);
TimerValue = (TextView) findViewById(R.id.tv_current_timeV2);
txtSales = (TextView) findViewById(R.id.textSales);
txtFollow = (TextView) findViewById(R.id.textFollow);
txtDone = (TextView) findViewById(R.id.textDone);
txtLeader = (TextView) findViewById(R.id.leaderTime);
txtTrain = (TextView) findViewById(R.id.trainTime);
SALES = (Button) findViewById(R.id.btnSales);
FOLLOW = (Button) findViewById(R.id.btnFollow);
DONE = (Button) findViewById(R.id.btnDone);
LEADER = (Button) findViewById(R.id.btnLeader);
TRAIN = (Button) findViewById(R.id.btnTrain);
STOP = (Button) findViewById(R.id.btnStop);
REPORT = (Button) findViewById(R.id.button_details);
editTextId = (EditText)findViewById(R.id.editText_id);
btnAddData = (Button)findViewById(R.id.button_add);
btnviewAll = (Button)findViewById(R.id.button_viewAll);
btnviewUpdate= (Button)findViewById(R.id.button_update);
btnDelete= (Button)findViewById(R.id.button_delete);
TimerValue.setText("00:00:00");
txtSales.setText("0");
txtFollow.setText("0");
txtDone.setText("0");
txtLeader.setText("00:00:00");
txtTrain.setText("00:00:00");
viewAll();
AddData();
UpdateData();
CountSales();
CountFollow();
CountDone();
TimeLeader();
TimeTrain();
StopTime();
}
public void CountSales() {
SALES.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
countSales++;
txtSales.setText(String.valueOf(countSales));
}
}
);
}
public void CountFollow() {
FOLLOW.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
countFollow++;
txtFollow.setText(String.valueOf(countFollow));
}
}
);
}
public void CountDone() {
DONE.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
countDone++;
txtDone.setText(String.valueOf(countDone));
}
}
);
}
public void TimeLeader() {
LEADER.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
SALES.setClickable(false);
FOLLOW.setClickable(false);
DONE.setClickable(false);
LEADER.setClickable(false);
TRAIN.setClickable(false);
timeName = "leader";
mTimerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
nCounter++;
TimerValue.setText("" + Utils.secToString(Integer.parseInt(String.valueOf(nCounter))));
txtLeader.setText("" + Utils.secToString(Integer.parseInt(String.valueOf(nCounter))));
}
});
}};
t.schedule(mTimerTask, 200, 1000); //
}
}
);
}
public void TimeTrain() {
TRAIN.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
SALES.setClickable(false);
FOLLOW.setClickable(false);
DONE.setClickable(false);
LEADER.setClickable(false);
TRAIN.setClickable(false);
timeName = "train";
mTimerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
nCounter++;
TimerValue.setText("" + Utils.secToString(Integer.parseInt(String.valueOf(nCounter))));
txtTrain.setText("" + Utils.secToString(Integer.parseInt(String.valueOf(nCounter))));
}
});
}};
t.schedule(mTimerTask, 200, 1000); //
}
}
);
}
public void StopTime() {
STOP.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
SALES.setClickable(true);
FOLLOW.setClickable(true);
DONE.setClickable(true);
LEADER.setClickable(true);
TRAIN.setClickable(true);
if (mTimerTask != null) {
TimerValue.setText("" + Utils.secToString(Integer.parseInt(String.valueOf(nCounter))));
mTimerTask.cancel();
if (timeName == "leader") {
TimerValue.setText(Utils.secToString(0));
txtLeader.setText("" + Utils.secToString(Integer.parseInt(String.valueOf(nCounter))));
} else if (timeName == "train") {
TimerValue.setText(Utils.secToString(0));
txtTrain.setText("" + Utils.secToString(Integer.parseInt(String.valueOf(nCounter))));
}
}
}
}
);
}
public void AddData() {
btnAddData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.insertData(txtSales.getText().toString(),
txtFollow.getText().toString(),
txtDone.getText().toString(), txtLeader.getText().toString(), txtTrain.getText().toString() );
if(isInserted == true) {
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
btnAddData.setVisibility(v.GONE);
}
else
Toast.makeText(MainActivity.this,"Data not Inserted",Toast.LENGTH_LONG).show();
}
}
);
}
public void UpdateData() {
btnviewUpdate.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isUpdate = myDb.updateData(editTextId.getText().toString(),
txtSales.getText().toString(),
txtFollow.getText().toString(),
txtDone.getText().toString(), txtLeader.getText().toString(), txtTrain.getText().toString() );
if(isUpdate == true)
Toast.makeText(MainActivity.this,"Data Update",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not Updated",Toast.LENGTH_LONG).show();
}
}
);
}
public void viewAll() {
REPORT.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
// show message
showMessage("Error","Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("Id :"+ res.getString(0)+"\n");
buffer.append("Sales :"+ res.getString(1)+"\n");
buffer.append("Follow :"+ res.getString(2)+"\n");
buffer.append("Done :"+ res.getString(3)+"\n");
buffer.append("Leader :"+ res.getString(4)+"\n");
buffer.append("Train :"+ res.getString(5)+"\n" );
}
// Show all data
showMessage("Data",buffer.toString());
}
}
);
}
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
activity_money
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:id="#+id/tv_current_timeV2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="00:00:00"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#android:color/holo_green_light"
android:textSize="38dp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/btnSales"
android:layout_width="168dp"
android:layout_height="match_parent"
android:layout_marginLeft="100dp"
android:onClick="onClick"
android:text="SALES" />
<TextView
android:id="#+id/textSales"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="0"
android:textStyle="bold"
android:textColor="#color/colorWhite"
android:gravity="center"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/btnFollow"
android:layout_width="168dp"
android:layout_height="match_parent"
android:layout_marginLeft="100dp"
android:onClick="onClick"
android:text="FOLLOW"
/>
<TextView
android:id="#+id/textFollow"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="0"
android:textStyle="bold"
android:textColor="#color/colorWhite"
android:gravity="center"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/btnDone"
android:layout_width="168dp"
android:layout_height="match_parent"
android:onClick="onClick"
android:layout_marginLeft="100dp"
android:text="DONE" />
<TextView
android:id="#+id/textDone"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="0"
android:textStyle="bold"
android:textColor="#color/colorWhite"
android:gravity="center"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/btnLeader"
android:layout_width="168dp"
android:layout_height="match_parent"
android:layout_marginLeft="100dp"
android:onClick="onClick"
android:text="LEADER" />
<TextView
android:id="#+id/leaderTime"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="00:00:00"
android:textStyle="bold"
android:textColor="#color/colorWhite"
android:gravity="center"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/btnTrain"
android:layout_width="168dp"
android:layout_height="match_parent"
android:onClick="onClick"
android:layout_marginLeft="100dp"
android:text="TRAIN" />
<TextView
android:id="#+id/trainTime"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="00:00:00"
android:textStyle="bold"
android:textColor="#color/colorWhite"
android:gravity="center"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="#+id/btnStop"
android:layout_width="168dp"
android:layout_height="match_parent"
android:layout_marginLeft="100dp"
android:onClick="onClick"
android:text="STOP" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="#+id/button_details"
android:layout_width="168dp"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:text="REPORT"
android:textColor="#color/colorBlack"
android:onClick="onClick"
android:textStyle="bold"/>
<Button
android:id="#+id/button_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/editText_Marks"
android:layout_marginTop="76dp"
android:text="Add Data" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update"
android:id="#+id/button_update"
android:layout_below="#+id/button_add"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</LinearLayout>
</ScrollView>
Error Log
Eror Log

Okay so your cause of error is because of this line
editTextId = (EditText)findViewById(R.id.editText_id);
as there is no EditText in your activity_money.xml layout and you are trying to get its reference so you are getting null reference.
First add it in xml or remove the edittext lines from your java file.

Related

cannot resolve MainActivityBinding and also binding related issues

I want to make a scientific calculator.
I found some useful code on this site: http://www.androidauthority.com/build-a-calculator-app-721910/
Then i modified it for my purpose.
In this code i found binding method was used so i made the following changes in my IDE as per the instructions on this site: https://developer.android.com/topic/libraries/data-binding/index.html
i made changes in the build.gradle(module app)
and made changes in my MainActivity.java code also.
but the following error occurred:
MainActivity.java
package com.example.anant.scientificcalculator;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import static java.lang.Math.*;
import java.text.DecimalFormat;
//import com.example.anant.scientificcalculator.databinding.MainActivityBinding;
//import android.content.DialogInterface;
//import android.text.TextUtils;
//import android.view.View;
//import android.widget.Button;
//import android.widget.EditText;
//import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private MainActivityBinding binding; //error in this line cannot resolve MainActivityBinding.
private static final char FACT = '!';
private static final char POWER = '^';
private static final String SQRT = "SQRT";
private static final String SIN = "SIN";
private static final String COS = "COS";
private static final String TAN = "TAN";
private static final String LOG = "LOG";
private static final char LEFTC = '(';
private static final char RIGHTC = ')';
private static final String EXP = "EXP";
private static final String PIE = "PIE";
private static final char ADD = '+';
private static final char SUBTRACT = '-';
private static final char MULTIPlY = '*';
private static final char DIVIDE = '/';
private char CURRENT_ACTION;
private String ADVANCE_ACTION;
private double valueOne = Double.NaN;
private double valueTwo;
private DecimalFormat decimalFormat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
decimalFormat = new DecimalFormat("#.##########");
MainActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.main_activity);
//error in all the lines below saying cannot resolve button-----(where ---- denotes the specific terms of the button)
binding.buttonDot.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + ".");
}
});
binding.buttonZero.setOnCLickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "0");
}
});
binding.buttonOne.setOnCLickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "1");
}
});
binding.buttonTwo.setOnCLickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "2");
}
});
binding.buttonThree.setOnCLickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "3");
}
});
binding.buttonFour.setOnCLickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "4");
}
});
binding.buttonFive.setOnCLickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "5");
}
});
binding.buttonSix.setOnCLickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "6");
}
});
binding.buttonSeven.setOnCLickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "7");
}
});
binding.buttonEight.setOnCLickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "8");
}
});
binding.buttonNine.setOnCLickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "9");
}
});
binding.buttonLeftC.setOnCLickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "(");
}
});
binding.buttonRightC.setOnCLickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + ")");
}
});
binding.buttonExp.setOnCLickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
computeCalculation();
ADVANCE_ACTION = EXP;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "EXP");
binding.editText.setText(null);
}
});
binding.buttonPie.setOnCLickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
computeCalculation();
ADVANCE_ACTION = PIE;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "PIE");
binding.editText.setText(null);
}
});
binding.buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = ADD;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "+");
binding.editText.setText(null);
}
});
binding.buttonSubtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = SUBTRACT;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "-");
binding.editText.setText(null);
}
});
binding.buttonMultiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = MULTIPlY;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "*");
binding.editText.setText(null);
}
});
binding.buttonDivide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = DIVIDE;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "/");
binding.editText.setText(null);
}
});
binding.buttonFact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = FACT;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "!");
binding.editText.setText(null);
}
});
binding.buttonPow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = POWER;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "^");
binding.editText.setText(null);
}
});
binding.buttonSqrt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
ADVANCE_ACTION = SQRT;
binding.infoTextView.setText("SQRT(" + decimalFormat.format(valueOne) + ")");
binding.editText.setText(null);
}
});
binding.buttonSine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
ADVANCE_ACTION = SIN;
binding.infoTextView.setText("SIN(" + decimalFormat.format(valueOne) + ")");
binding.editText.setText(null);
}
});
binding.buttonCosine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
ADVANCE_ACTION = COS;
binding.infoTextView.setText("COS(" + decimalFormat.format(valueOne) + ")");
binding.editText.setText(null);
}
});
binding.buttonTangent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
ADVANCE_ACTION = TAN;
binding.infoTextView.setText("TAN(" + decimalFormat.format(valueOne) + ")");
binding.editText.setText(null);
}
});
binding.buttonLog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
ADVANCE_ACTION = LOG;
binding.infoTextView.setText("LOG(" + decimalFormat.format(valueOne) + ")");
binding.editText.setText(null);
}
});
binding.buttonEqual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
binding.infoTextView.setText(binding.infoTextView.getText().toString() +
decimalFormat.format(valueTwo) + " = " + decimalFormat.format(valueOne));
valueOne = Double.NaN;
CURRENT_ACTION = '0';
}
});
binding.buttonClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(binding.editText.getText().length() > 0) {
CharSequence currentText = binding.editText.getText();
binding.editText.setText(currentText.subSequence(0, currentText.length()-1));
}
else {
valueOne = Double.NaN;
valueTwo = Double.NaN;
binding.editText.setText("");
binding.infoTextView.setText("");
}
}
});
}
private void computeCalculation() {
if(!Double.isNaN(valueOne)) {
valueTwo = Double.parseDouble(binding.editText.getText().toString());
binding.editText.setText(null);
if(CURRENT_ACTION == ADD)
valueOne = this.valueOne + valueTwo;
else if(CURRENT_ACTION == SUBTRACT)
valueOne = this.valueOne - valueTwo;
else if(CURRENT_ACTION == MULTIPlY)
valueOne = this.valueOne * valueTwo;
else if(CURRENT_ACTION == DIVIDE)
valueOne = this.valueOne / valueTwo;
else if(CURRENT_ACTION == FACT)
{
int i,valueThree = 1;
for(i=(int) valueOne;i>0;i--) //type conversion
{
valueThree *= i;
}
}
else if(CURRENT_ACTION == POWER)
valueOne = Math.pow(valueOne,valueTwo);
else if(ADVANCE_ACTION == SQRT)
valueOne = Math.sqrt(valueOne);
else if(ADVANCE_ACTION == SIN)
valueOne = Math.sin(valueOne);
else if(ADVANCE_ACTION == COS)
valueOne = Math.cos(valueOne);
else if(ADVANCE_ACTION == TAN)
valueOne = Math.tan(valueOne);
else if(ADVANCE_ACTION == LOG)
valueOne = Math.log(valueOne);
else if(ADVANCE_ACTION == PIE)
valueOne = Math.PI;
else if(ADVANCE_ACTION == EXP)
valueOne = Math.E;
}
else {
try {
valueOne = Double.parseDouble(binding.editText.getText().toString());
}
catch (Exception e){}
}
}
}
this is my xml file
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.anant.scientificcalculator.MainActivity">
<TextView
android:id="#+id/infoTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"
android:textSize="30sp" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/infoTextView"
android:enabled="false"
android:gravity="bottom"
android:hint="0"
android:inputType="numberDecimal"
android:lines="2"
android:maxLines="2"
android:textAlignment="textEnd"
android:textColor="#android:color/black"
android:textSize="40sp" />
<Button
android:id="#+id/buttonFact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:text="#string/buttonFact"
android:textSize="20sp" />
<Button
android:id="#+id/buttonPow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:layout_toRightOf="#id/buttonFact"
android:text="#string/buttonPow"
android:textSize="20sp" />
<Button
android:id="#+id/buttonSqrt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:layout_toRightOf="#id/buttonPow"
android:text="#string/buttonSqrt"
android:textSize="20sp" />
<Button
android:id="#+id/buttonClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/buttonSqrt"
android:layout_below="#id/editText"
android:text="#string/buttonClear"
android:textSize="20sp" />
<Button
android:id="#+id/buttonSine"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonFact"
android:text="#string/buttonSine"
android:textSize="20sp" />
<Button
android:id="#+id/buttonCosine"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonPow"
android:layout_toRightOf="#id/buttonSine"
android:text="#string/buttonCosine"
android:textSize="20sp" />
<Button
android:id="#+id/buttonTangent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonSqrt"
android:layout_toRightOf="#id/buttonCosine"
android:text="#string/buttonTangent"
android:textSize="20sp" />
<Button
android:id="#+id/buttonLog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonClear"
android:layout_toRightOf="#id/buttonTangent"
android:text="#string/buttonLog"
android:textSize="20sp" />
<Button
android:id="#+id/buttonLeftC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonSine"
android:text="#string/buttonLeftC"
android:textSize="20sp" />
<Button
android:id="#+id/buttonRightC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonCosine"
android:layout_toRightOf="#id/buttonLeftC"
android:text="#string/buttonRightC"
android:textSize="20sp" />
<Button
android:id="#+id/buttonExp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonTangent"
android:layout_toRightOf="#id/buttonRightC"
android:text="#string/buttonExp"
android:textSize="20sp" />
<Button
android:id="#+id/buttonPie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonLog"
android:layout_toRightOf="#id/buttonExp"
android:text="#string/buttonPie"
android:textSize="20sp" />
<Button
android:id="#+id/buttonSeven"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonLeftC"
android:text="#string/buttonSeven"
android:textSize="20sp" />
<Button
android:id="#+id/buttonEight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonRightC"
android:layout_toRightOf="#id/buttonSeven"
android:text="#string/buttonEight"
android:textSize="20sp" />
<Button
android:id="#+id/buttonNine"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonExp"
android:layout_toRightOf="#id/buttonEight"
android:text="#string/buttonNine"
android:textSize="20sp" />
<Button
android:id="#+id/buttonFour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonSeven"
android:text="#string/buttonFour"
android:textSize="20sp" />
<Button
android:id="#+id/buttonFive"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonEight"
android:layout_toRightOf="#id/buttonFour"
android:text="#string/buttonFive"
android:textSize="20sp" />
<Button
android:id="#+id/buttonSix"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonNine"
android:layout_toRightOf="#id/buttonFive"
android:text="#string/buttonSix"
android:textSize="20sp" />
<Button
android:id="#+id/buttonOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonFour"
android:text="#string/buttonOne"
android:textSize="20sp" />
<Button
android:id="#+id/buttonTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonFive"
android:layout_toRightOf="#id/buttonOne"
android:text="#string/buttonTwo"
android:textSize="20sp" />
<Button
android:id="#+id/buttonThree"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonSix"
android:layout_toRightOf="#id/buttonTwo"
android:text="#string/buttonThree"
android:textSize="20sp" />
<Button
android:id="#+id/buttonDot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonOne"
android:text="#string/buttonDot"
android:textSize="20sp" />
<Button
android:id="#+id/buttonZero"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonTwo"
android:layout_toRightOf="#id/buttonDot"
android:text="#string/buttonZero"
android:textSize="20sp" />
<Button
android:id="#+id/buttonEqual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#id/buttonNine"
android:layout_below="#id/buttonThree"
android:text="#string/buttonEqual"
android:textSize="20sp" />
<Button
android:id="#+id/buttonDivide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/buttonNine"
android:layout_toRightOf="#id/buttonNine"
android:text="#string/buttonDIvide"
android:textSize="20sp" />
<Button
android:id="#+id/buttonMultiply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/buttonSix"
android:layout_toRightOf="#id/buttonSix"
android:text="#string/buttonMultiply"
android:textSize="20sp" />
<Button
android:id="#+id/buttonSubtract"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/buttonThree"
android:layout_toRightOf="#id/buttonThree"
android:text="#string/buttonSubtract"
android:textSize="20sp" />
<Button
android:id="#+id/buttonAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/buttonEqual"
android:layout_toRightOf="#id/buttonEqual"
android:text="#string/buttonAdd"
android:textSize="20sp" />
</RelativeLayout>
You need to uncomment out:
//import com.example.anant.scientificcalculator.databinding.MainActivityBinding;
That is an autogenerated class for your data binding. You need it. Make it look like this:
com.example.anant.scientificcalculator.databinding.MainActivityBinding;
Secondly, your XML file isn't correct, it should have its RelativeLayout wrapped in a layout tag, like so:
<layout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.anant.scientificcalculator.MainActivity">
...
</layout>
After you do that, do a clean and rebuild, and I think you should be good to go.
Uncomment
import com.example.anant.scientificcalculator.databinding.MainActivityBinding;
And wrap your layout under <layout> tag.

Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference

i am new to android development , here i am trying to create a simple database app using sqlite
what i am trying to do is when the user selects search it will ask for the id and the corresponding data matching the id should replace the fields of editText by that particular data
ActivityMain.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ashish.project.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Personal Details"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:gravity="center" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/gridLayout"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_row="0"
android:layout_column="0">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/editText"
android:layout_weight="1"
android:hint="First Name" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/editText_LastName"
android:layout_weight="1"
android:hint="Last Name" />
</LinearLayout>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText_number"
android:layout_row="1"
android:layout_column="0"
android:hint="Contact Number" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/editText_email"
android:layout_row="2"
android:layout_column="0"
android:hint="E-mail" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_row="3"
android:layout_column="0">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit Details"
android:id="#+id/Button_Submit"
android:layout_weight="1"
android:layout_row="4"
android:layout_column="0" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Details"
android:id="#+id/button_Show_Details"
android:layout_gravity="right"
android:layout_weight="1"
android:layout_row="5"
android:layout_column="0"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_search"
android:layout_below="#id/Button_Submit"
android:text="search"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear Table"
android:id="#+id/button_clear"
android:gravity="left|center_horizontal"
android:layout_below="#+id/button_Show_Details"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</GridLayout>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText_srch"
android:hint="Enter id to search"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="search"
android:id="#+id/button_show_id_result"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</LinearLayout>
</ScrollView>
</RelativeLayout>
MainActivity.java
package com.example.ashish.project;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button button_submit,button_show_details,button_clear,button_search,button_show_id_result;
EditText firstName,lastName,number,email,editText_id_search;
String firstnameString,lastnameString,emailString,num;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_submit=(Button)findViewById(R.id.Button_Submit);
button_show_id_result=(Button) findViewById(R.id.button_show_id_result);
editText_id_search=(EditText) findViewById(R.id.editText_srch);
button_show_details=(Button)findViewById(R.id.button_Show_Details);
firstName=(EditText)findViewById(R.id.editText);
button_search=(Button) findViewById(R.id.button_search);
button_clear=(Button)findViewById(R.id.button_clear);
lastName=(EditText)findViewById(R.id.editText_LastName);
number=(EditText)findViewById(R.id.editText_number);
email=(EditText)findViewById(R.id.editText_email);
editText_id_search.setVisibility(View.GONE);
button_show_id_result.setVisibility(View.GONE);
button_clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
db.clear();
}
});
button_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*
*/
editText_id_search.setVisibility(View.VISIBLE);
button_show_id_result.setVisibility(View.VISIBLE);
button_show_id_result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String qry = editText_id_search.getText().toString();
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
db.search(qry);
}
});
}
});
button_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
firstnameString = firstName.getText().toString();
lastnameString=lastName.getText().toString();
num=number.getText().toString();
emailString=email.getText().toString();
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
db.insertData(firstnameString,lastnameString,num,emailString);
Toast.makeText(MainActivity.this,"Record Updated",Toast.LENGTH_LONG).show();
InputMethodManager input = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
input.hideSoftInputFromWindow(email.getWindowToken(),0);
firstName.setText("");
lastName.setText("");
number.setText("");
email.setText("");
db.close();
}
});
button_show_details.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,List_Result.class);
startActivity(i);
}
});
}
public void show(String string, String cString, String s, String string1) {
firstName.setText(string);
lastName.setText(cString);
number.setText(s);
email.setText(string1);
}
}
DatabaseHelper.java
package com.example.ashish.project;
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 ashis on 7/21/2016.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
private static int DATABASE_VERSION = 6;
private static String DATABSE_NAME="DATA";
private static String TABLE_NAME="PERSONAL_INFORMATION";
private static String COLUMN_ID= "_ID";
private static String COLUMN_FIRST_NAME="FIRST_NAME";
private static String COLUMN_LAST_NAME="LAST_NAME";
private static String COLUMN_NUMBER = "NUMBER";
private static String COLUMN_EMAIL="EMAIL";
public DatabaseHelper(Context context)
{
super(context,DATABSE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME + "( "
+ COLUMN_ID +" INTEGER PRIMARY KEY, "
+ COLUMN_FIRST_NAME + " TEXT, "
+ COLUMN_LAST_NAME + " TEXT, "
+ COLUMN_NUMBER + " TEXT , "
+ COLUMN_EMAIL + " TEXT"+" )";
sqLiteDatabase.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS"+TABLE_NAME);
this.onCreate(sqLiteDatabase);
}
public void insertData(String firstnameString, String lastnameString, String num, String emailString) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_FIRST_NAME,firstnameString);
values.put(COLUMN_LAST_NAME,lastnameString);
values.put(COLUMN_NUMBER,num);
values.put(COLUMN_EMAIL,emailString);
db.insertOrThrow(TABLE_NAME,null,values);
db.close();
}
public ArrayList<String> readData() {
ArrayList<String> list = new ArrayList<>();
String readQry = "SELECT * FROM "+TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(readQry,null);
if (c.moveToFirst())
{
do {
list.add(c.getString(0)+ ": "+c.getString(1) +" "+ c.getString(2)+","+c.getString(3)+","+c.getString(4));
}while (c.moveToNext());
}
c.close();
db.close();
return list;
}
public void clear() {
SQLiteDatabase db= this.getWritableDatabase();
String clrqry = "DROP TABLE " + TABLE_NAME;
db.execSQL(clrqry);
this.onCreate(db);
}
public void search(String srch) {
SQLiteDatabase db = this.getReadableDatabase();
MainActivity obj = new MainActivity();
String sqlqry = "SELECT * FROM "+TABLE_NAME +" WHERE "+ COLUMN_ID + " = ?";
Cursor c= db.rawQuery(sqlqry,new String[]{srch});
if (c.moveToFirst())
{
do {
obj.show(c.getString(1),c.getString(2),c.getString(3),c.getString(4));
}
while (c.moveToNext());
}
}
}
Activity_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ashish.project.List_Result">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView2"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#android:color/darker_gray" />
</RelativeLayout>
Activity_list.java
package com.example.ashish.project;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class List_Result extends AppCompatActivity {
ListView listview1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list__result);
listview1=(ListView) findViewById(R.id.listView2);
loadlistviewData();
}
private void loadlistviewData() {
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
ArrayList<String> list = db.readData();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,list);
adapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
listview1.setAdapter(adapter);
}
}
here is the logcat when i try to click Search after inputting id
07-25 14:27:34.033 668-668/com.example.ashish.project W/System: ClassLoader referenced unknown path: /data/app/com.example.ashish.project-2/lib/arm
07-25 14:27:34.256 668-668/com.example.ashish.project W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
07-25 14:27:34.541 668-668/com.example.ashish.project D/android.widget.GridLayout: vertical constraints: y4-y0>=864, y4-y3<=192, y3-y2<=91, y2-y1<=91, y1-y0<=100 are inconsistent; permanently removing: y4-y3<=192.
07-25 14:27:39.235 668-668/com.example.ashish.project D/AndroidRuntime: Shutting down VM
07-25 14:27:39.236 668-668/com.example.ashish.project E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ashish.project, PID: 668
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at com.example.ashish.project.MainActivity.show(MainActivity.java:103)
at com.example.ashish.project.DatabaseHelper.search(DatabaseHelper.java:108)
at com.example.ashish.project.MainActivity$2$1.onClick(MainActivity.java:60)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21163)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
any help would be appreciated
You call show() by creating a new Instance of MainActivity. Hence all the variables of MainActivity will be null. Better you should make those static so that initialization of those views will be same for all instances of MainActivity. Try
static EditText firstName,lastName,number,email,editText_id_search;
Don't use static for your View widget.
Replace your search function in DatabaseHelper.java with below one:
public void search(String srch, MainActivity activity) {
SQLiteDatabase db = this.getReadableDatabase();
String sqlqry = "SELECT * FROM "+TABLE_NAME +" WHERE "+ COLUMN_ID + " = ?";
Cursor c= db.rawQuery(sqlqry,new String[]{srch});
if (c.moveToFirst())
{
do {
activity.show(c.getString(1),c.getString(2),c.getString(3),c.getString(4));
}
while (c.moveToNext());
}
}
In MainActivity.java, replace below:
db.search(qry);
With:
db.search(qry, MainActivity.this);
just wrap with try and catch it solves the problem.

onOptionsItemClick or onMenuItemClick not being called

(Very first thing i want to make clear is that i am COMPLETELY NEWBIE, very beginner in android, in fact in programming/coding!)
The menu is referred in onCreateOptionMenu and the calling method is also onOptionsItemSelected to open up menu but the method for each option/item is set as onMenuItemClick and onMenuItemLongClick which is ideal for context menu options/items!
The problem is onMenuItemClick have input parameters as (View v, int position) and I cannot change it to only (View v) or to (MenuItem item).
What I want is clicking on each item of menu should bring out new activity!
I also tried putting all my switch-case-break statements to onOptionsItemSelected method but it is still not working!
I also tried in fragment class, setHasOptionsMenu (true); but it did not work!
onMenuItemClick doesn't get called
(Deprecated) Fragment onOptionsItemSelected not being called
Below is the activity_main_menu.xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/menu_item_background">
<include layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Below is the fragment_main.xml layout
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.coffeeshop.MainFragment">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#color/menu_item_background">
<EditText
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/EditTextHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="#+id/usercontact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/usercontactHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="#+id/useremail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/useremailHint"
android:inputType="textEmailAddress" />
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/Toppings" />
<CheckBox
android:id="#+id/whippedCreamcheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingEnd="24dp"
android:paddingLeft="24dp"
android:paddingStart="24dp"
android:text="#string/WhippedCream"
android:textSize="16sp" />
<CheckBox
android:id="#+id/Chocolatebox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingEnd="24dp"
android:paddingLeft="24dp"
android:paddingStart="24dp"
android:text="#string/Chocolate"
android:textSize="16sp" />
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/quantity" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginTop="16dp"
android:onClick="decrement"
android:text="#string/minus" />
<TextView
android:id="#+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="16dp"
android:text="#string/Zero"
android:textColor="#android:color/black"
android:textSize="20sp" />
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginTop="16dp"
android:onClick="increment"
android:text="#string/plus" />
</LinearLayout>
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/OrderSummary" />
<TextView
android:id="#+id/order_summary_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/Price"
android:textColor="#android:color/black"
android:textSize="20sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/orderButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="submitOrder"
android:text="#string/Order" />
<Button
android:id="#+id/placeOrder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:onClick="placeOrder"
android:text="#string/PlaceOrder" />
</LinearLayout>
</LinearLayout>
</ScrollView>
Below is the MainMenu.java class file from where i am trying to handle fragment menu!
package com.example.android.coffeeshop5profile;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.yalantis.contextmenu.lib.ContextMenuDialogFragment;
import com.yalantis.contextmenu.lib.MenuObject;
import com.yalantis.contextmenu.lib.MenuParams;
import com.yalantis.contextmenu.lib.interfaces.OnMenuItemLongClickListener;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* This app displays an order form to order coffee.
*/
public class MainMenu extends AppCompatActivity implements ActionMenuView.OnMenuItemClickListener, OnMenuItemLongClickListener {
private FragmentManager fragmentManager;
private ContextMenuDialogFragment mMenuDialogFragment;
int quantity = 1;
int price = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
fragmentManager = getSupportFragmentManager();
initToolbar();
initMenuFragment();
addFragment(new MainFragment(), true, R.id.container);
}
private void initMenuFragment() {
MenuParams menuParams = new MenuParams();
menuParams.setActionBarSize((int) getResources().getDimension(R.dimen.tool_bar_height));
menuParams.setMenuObjects(getMenuObjects());
menuParams.setClosableOutside(false);
mMenuDialogFragment = ContextMenuDialogFragment.newInstance(menuParams);
mMenuDialogFragment.setItemLongClickListener(this);
}
private List<MenuObject> getMenuObjects() {
List<MenuObject> menuObjects = new ArrayList<>();
MenuObject close = new MenuObject();
close.setResource(R.drawable.icn_close);
MenuObject send = new MenuObject("Send message");
send.setResource(R.drawable.icn_1);
MenuObject like = new MenuObject("Like profile");
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.icn_2);
like.setBitmap(b);
MenuObject addFr = new MenuObject("Add to friends");
BitmapDrawable bd = new BitmapDrawable(getResources(),
BitmapFactory.decodeResource(getResources(), R.drawable.icn_3));
addFr.setDrawable(bd);
MenuObject addFav = new MenuObject("Add to favorites");
addFav.setResource(R.drawable.icn_4);
MenuObject block = new MenuObject("Block user");
block.setResource(R.drawable.icn_5);
menuObjects.add(close);
menuObjects.add(send);
menuObjects.add(like);
menuObjects.add(addFr);
menuObjects.add(addFav);
menuObjects.add(block);
return menuObjects;
}
private void initToolbar() {
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
TextView mToolBarTextView = (TextView) findViewById(R.id.text_view_toolbar_title);
setSupportActionBar(mToolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mToolbar.setNavigationIcon(R.drawable.btn_back);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
mToolBarTextView.setText(R.string.title_text);
}
protected void addFragment(Fragment fragment, boolean addToBackStack, int containerId) {
invalidateOptionsMenu();
String backStackName = fragment.getClass().getName();
boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStackName, 0);
if (!fragmentPopped) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(containerId, fragment, backStackName)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
if (addToBackStack)
transaction.addToBackStack(backStackName);
transaction.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.context_menu:
if (fragmentManager.findFragmentByTag(ContextMenuDialogFragment.TAG) == null) {
mMenuDialogFragment.show(fragmentManager, ContextMenuDialogFragment.TAG);
}
break;
case R.drawable.icn_3:
Intent userProfileIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(userProfileIntent);
break;
case R.drawable.icn_4:
Intent wishListIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(wishListIntent);
break;
}
return false; //Turning this true or to super.OnOptionsItemSelected did nothing!
}
#Override
public void onBackPressed() {
if (mMenuDialogFragment != null && mMenuDialogFragment.isAdded()) {
mMenuDialogFragment.dismiss();
} else {
finish();
}
}
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.drawable.icn_3:
Intent userProfileIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(userProfileIntent);
break;
case R.drawable.icn_4:
Intent wishListIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(wishListIntent);
break;
} return true;
}
#Override
public void onMenuItemLongClick(View clickedView, int position) {
Toast.makeText(this, "Long clicked on position: " + position, Toast.LENGTH_SHORT).show();
}
public void submitOrder(View view) {
String orderSummaryString = createOrderSummary(quantity);
displayMessage(orderSummaryString);
}
public void placeOrder(View view) {
TextView useremail = (TextView) findViewById(R.id.useremail);
String useremailString = useremail.getText().toString();
String orderSummaryString = createOrderSummary(quantity);
sendMail(useremailString, "Coffee Order By: " + useremailString, orderSummaryString);
}
private void sendMail(String email, String subject, String messageBody) {
Session session = createSessionObject();
try {
Message message = createMessage(email, subject, messageBody, session);
new SendMailTask().execute(message);
} catch (MessagingException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private Message createMessage(String email, String subject, String messageBody, Session session)
throws MessagingException, UnsupportedEncodingException {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("clientaddress#gmail.com", "Coffee Order By"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
message.setSubject(subject);
message.setText(messageBody);
return message;
}
private Session createSessionObject() {
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
return Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("clientaddress#gmail.com", "************");
}
});
}
public class SendMailTask extends AsyncTask<Message, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(MainMenu.this, "Please wait", "Sending mail", true, false);
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
#Override
public Void doInBackground(Message... messages) {
try {
Transport.send(messages[0]);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
/**
* This method is called when the plus button is clicked.
*/
public void increment(View view) {
if (quantity < 100) {
quantity = quantity + 1;
displayQuantity(quantity);
} else {
Toast.makeText(this, "You have reached maximum numbers of coffees to be allowed!", Toast.LENGTH_SHORT).show();
}
}
/**
* This method is called when the minus button is clicked.
*/
public void decrement(View view) {
if (quantity >= 2) {
quantity = quantity - 1;
displayQuantity(quantity);
} else {
Toast.makeText(this, "You can not place order in negative number!", Toast.LENGTH_SHORT).show();
}
}
public String createOrderSummary(int quantity) {
CheckBox whippedCreamCheckbox = (CheckBox) findViewById(R.id.whippedCreamcheckbox);
boolean hasWhippedCream = whippedCreamCheckbox.isChecked();
CheckBox chocolatebox = (CheckBox) findViewById(R.id.Chocolatebox);
boolean hasChocolate = chocolatebox.isChecked();
price = 5;
if (hasWhippedCream) {
price = price + 1;
}
if (hasChocolate) {
price = price + 2;
}
int finalPrice = quantity * price;
EditText usernameTextView = (EditText) findViewById(R.id.username);
String usernameString = usernameTextView.getText().toString();
EditText usercontact = (EditText) findViewById(R.id.usercontact);
String userContactString = usercontact.getText().toString();
EditText useremail = (EditText) findViewById(R.id.useremail);
String userEmailString = useremail.getText().toString();
String OrderSummary = getString(R.string.username) + ": " + usernameString;
OrderSummary += "\n" + getString(R.string.ContactNumber) + " " + userContactString;
OrderSummary += "\n" + getString(R.string.eAddress) + " " + userEmailString;
OrderSummary += "\n" + getString(R.string.AddedWhippedCream) + " " + hasWhippedCream;
OrderSummary += "\n" + getString(R.string.AddedChocolate) + " " + hasChocolate;
OrderSummary += "\n" + getString(R.string.quantity) + ": " + quantity;
OrderSummary += "\n" + getString(R.string.totalprice) + finalPrice;
OrderSummary += "\n" + getString(R.string.thankyou);
return OrderSummary;
}
/**
* This method displays the given quantity value on the screen.
*/
public void displayQuantity(int number) {
TextView quantityTextView = (TextView) findViewById(
R.id.quantity_text_view);
quantityTextView.setText(String.format("%d", number));
}
/**
* This method displays the given text on the screen.
*/
public void displayMessage(String message) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.order_summary_text_view);
orderSummaryTextView.setText(message);
}
}
Below is the MainFragment.java class file
package com.example.android.coffeeshop5profile;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
setHasOptionsMenu(true);
setMenuVisibility(false);
return rootView;
}
}
Following is the Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue_grey_700"
android:orientation="vertical"
android:weightSum="4"
tools:context=".legacy.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3"
android:gravity="center_vertical"
android:orientation="vertical">
<ImageView
android:id="#+id/google_icon"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:contentDescription="#string/desc_google_icon"
android:src="#drawable/googleg_color" />
<TextView
android:id="#+id/title_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_gravity="center"
android:text="#string/title_text"
android:textColor="#android:color/white"
android:textSize="36sp" />
<TextView
android:id="#+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/signed_out"
android:textColor="#android:color/white"
android:textSize="14sp" />
<TextView
android:id="#+id/detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fadeScrollbars="true"
android:gravity="center"
android:maxLines="5"
android:padding="10dp"
android:scrollbars="vertical"
android:textColor="#android:color/white"
android:textSize="14sp" />
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/blue_grey_900">
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible"
tools:visibility="gone" />
<LinearLayout
android:id="#+id/sign_out_and_disconnect"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="horizontal"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:visibility="gone"
tools:visibility="visible">
<Button
android:id="#+id/sign_out_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/sign_out"
android:theme="#style/ThemeOverlay.MyDarkButton" />
<Button
android:id="#+id/disconnect_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/disconnect"
android:theme="#style/ThemeOverlay.MyDarkButton" />
<Button
android:id="#+id/secondpage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/secondpage"
android:theme="#style/ThemeOverlay.MyDarkButton" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
below is the res/menu/context_main_menu.xml file
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/context_menu"
android:title="#string/context_menu"
android:icon="#drawable/btn_add"
android:orderInCategory="100"
app:showAsAction="always" />
</menu>
...unfortunately, 30000 characters limit has been reached so i cant upload mainActivity.java file!
Kindly help!
Best regards,
sagar
try this code on
Change the following code
onMenuItemClick(MenuItem item)
to
onMenuItemClick(View clickedView, int position)
like this
`#override
public void onMenuItemClick(View clickedView, int position) {
switch (position) {
case 1:
startActivity(new Intent(MainActivity.this, UserProfile.class));
break;
case 2:
startActivity(new Intent(MainActivity.this, UserProfile.class));
break;
}
}`
i hope this help you
If onOptionsItemSelected() method is not called in fragment then just make sure you return false from the onOptionsItemSelected() method of Activity.

Android: Open a new layout file on button click and apply SQLite data to it

I have a gridview here:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/topContent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="7">
<TextView
android:id="#+id/textView0"
android:background="#color/white"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="ID: "
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView1"
android:background="#color/purple"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridCode"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView2"
android:background="#color/green"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridDay"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView3"
android:background="#color/orange"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridStart"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView4"
android:background="#color/blue"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridDuration"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView5"
android:background="#color/yellow"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridType"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView6"
android:background="#color/red"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridRoom"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
</LinearLayout>
<GridView
android:id="#+id/gridTable"
android:layout_below="#+id/topContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:horizontalSpacing="10dip"
android:verticalSpacing="15dip"
android:stretchMode="columnWidth"
android:gravity="center"
android:numColumns="7"
android:background="#color/colorPrimary"
android:textSize="14sp"
>
</GridView>
</RelativeLayout>
And a database helper:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper
{
//database information
public static final String DATABASE_NAME = "timetable.db";
public static final String TABLE_NAME = "timetable_data";
//the data each column will store
public static final String COL_1 = "ID";
public static final String COL_2 = "CODE";
public static final String COL_3 = "DAY";
public static final String COL_4 = "START";
public static final String COL_5 = "DURATION";
public static final String COL_6 = "TYPE";
public static final String COL_7 = "ROOM";
//construct the database
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,CODE TEXT,DAY TEXT,START TEXT,DURATION TEXT,TYPE TEXT,ROOM 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 code, String day, String start, String duration, String type, String room)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,code);
contentValues.put(COL_3,day);
contentValues.put(COL_4,start);
contentValues.put(COL_5,duration);
contentValues.put(COL_6,type);
contentValues.put(COL_7, room);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("select * from "+TABLE_NAME,null);
return data;
}
public Integer deleteEntry(String id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME,"ID = ?", new String [] {id});
}
}
What I'm trying to do, is create an adapter that can be applied to that gridview when a button is pressed. The adapter should pull all of the information from the database and insert each bit of data into each cell of the grid. I'd like all of this to happen when a button is pressed, pressing the button will show the grid in a new layout, and when the back button is pressed go back to the main_acitivty layout.
but I'm not sure if I need the other layout file there, or where the button goes, or even if this is possible to do, so any help would be appreciated! thanks!
Main_activity source:
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
DatabaseHelper timetableDB;
EditText roomInput, codeInput, idInput;
Spinner dayInput, durationInput, timeInput, sessionInput;
Button button_add, button_display, button_delete, button_display_grid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timetableDB = new DatabaseHelper(this);
codeInput = (EditText) findViewById(R.id.codeInput);
dayInput = (Spinner) findViewById(R.id.dayInput);
timeInput = (Spinner) findViewById(R.id.timeInput);
durationInput = (Spinner) findViewById(R.id.durationInput);
sessionInput = (Spinner) findViewById(R.id.sessionInput);
roomInput = (EditText) findViewById(R.id.roomInput);
idInput = (EditText) findViewById(R.id.idInput);
button_add = (Button) findViewById(R.id.button_add);
button_display = (Button) findViewById(R.id.button_display);
button_display_grid = (Button) findViewById(R.id.button_display_grid);
button_delete = (Button) findViewById(R.id.button_delete);
AddData();
displayData();
deleteData();
}
button_display_grid.setOnClickListener(new View.OnClickListener()
{
//This method starts the GridView activity when the button is pressed
#Override
public void onClick (View v)
{
Intent i = new Intent(MainActivity.this, GridViewActivity.class);
startActivity(i);
}
}
public void deleteData()
{
button_delete.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Integer deletedData = timetableDB.deleteEntry(idInput.getText().toString());
if(deletedData > 0)
Toast.makeText(MainActivity.this, "Entry Removed", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Error Removing Entry", Toast.LENGTH_SHORT).show();
}
}
);
}
public void AddData()
{
button_add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
boolean isInserted = timetableDB.insertData(
codeInput.getText().toString(),
dayInput.getSelectedItem().toString(),
timeInput.getSelectedItem().toString(),
durationInput.getSelectedItem().toString(),
sessionInput.getSelectedItem().toString(),
roomInput.getText().toString());
if (isInserted = true)
Toast.makeText(MainActivity.this, "Module Added", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Error Adding Data", Toast.LENGTH_SHORT).show();
}
}
);
}
public void displayData()
{
button_display.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Cursor data = timetableDB.getAllData();
if(data.getCount() == 0)
{
//show message
return;
}
StringBuilder buffer = new StringBuilder();
while (data.moveToNext())
{
buffer.append("ID :"+ data.getString(0)+"\n");
buffer.append("Code :"+ data.getString(1)+"\n");
buffer.append("Day :"+ data.getString(2)+"\n");
buffer.append("Start :"+ data.getString(3)+"\n");
buffer.append("Duration: "+ data.getString(4)+"\n");
buffer.append("Type :"+ data.getString(5)+"\n");
buffer.append("Room :"+ data.getString(6)+"\n\n");
}
showMessage("My Timetable:", buffer.toString());
}
}
);
}
public void showMessage(String title, String Message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
GridViewActivity.java:
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by natha on 17/02/2016.
*
* This class gets all of the information in the getAllData() method, adds it to an array list,
* then an array adapter reads the data from this array list and applies that data to the GridView.
*
*/
public class GridViewActivity extends MainActivity
{
private GridView gridTable;
private ArrayList<String> moduleList;
private ArrayAdapter<String> adapter;
private Cursor data;
DatabaseHelper timetableDB;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState); setContentView(R.layout.gridview);
//GridView
gridTable=(GridView) findViewById(R.id.gridTable);
//ArrayList
moduleList = new ArrayList<>();
adapter = new ArrayAdapter<>(getApplicationContext(),
android.R.layout.simple_spinner_item,moduleList);
String id, code, day, time, duration, type, room;
id = "";
code = "";
day = "";
time = "";
duration = "";
type = "";
room = "";
timetableDB = new DatabaseHelper(getBaseContext());//getting the context object
timetableDB.getAllData();
try
{
//for holding retrieve data from query and store in the form of rows
Cursor data=timetableDB.getAllData();
//Move the cursor to the first row.
if(data.moveToFirst())
{
do
{
id = data.getString(data.getColumnIndex ("id"));
code = data.getString(data.getColumnIndex ("code"));
day = data.getString(data.getColumnIndex ("day"));
time = data.getString(data.getColumnIndex ("time"));
duration = data.getString(data.getColumnIndex ("duration"));
type = data.getString(data.getColumnIndex ("type"));
room = data.getString(data.getColumnIndex ("room"));
//add in to array list
moduleList . add(id);
moduleList . add(code);
moduleList . add(day);
moduleList . add(time);
moduleList . add(duration);
moduleList . add(type);
moduleList . add(room);
gridTable.setAdapter(adapter);
}
while(data.moveToNext());//Move the cursor to the next row.
}
else
{
Toast.makeText(getApplicationContext(),
"No data found", Toast.LENGTH_LONG).show();
}
}catch(Exception e)
{
Toast.makeText(getApplicationContext(),
"No data found "+e.getMessage(), Toast.LENGTH_LONG).show();
}
timetableDB.close();
}
}
You should move the button_display_grid.setOnClickListener, inside the onCreate of your activity, after its initialization.

sqlite database practice in android

I have made an application simple in android for database practice,as i have no idea about Sqlite database I've gone through so many links for it,But most of them are complex,I have created 4 activities 1st (mainActivity) contains 3 Buttons "add","Edit", and "View" in 2nd activity (AddActivity) I have made 3 EditTexts its entered values should be stored in database.So can you please tell me easy steps for doing same?
MainActivity.java
package com.example.db;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button add=(Button)findViewById(R.id.button1);
Button edit=(Button)findViewById(R.id.button2);
Button view=(Button)findViewById(R.id.button3);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub]
Intent i=new Intent(MainActivity.this,AddActivity.class);
startActivity(i);
}
});
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,EditActivity.class);
startActivity(i);
}
});
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,ViewActivity.class);
startActivity(i);
}
});
}
}
AddActivity.java
package com.example.db;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class AddActivity extends Activity {
EditText name,addres,phon;
Button ad,cn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
name = (EditText)findViewById(R.id.name);
addres=(EditText)findViewById(R.id.address);
phon = (EditText)findViewById(R.id.phone);
ad =(Button)findViewById(R.id.add);
cn=(Button)findViewById(R.id.cancel);
final SQLiteDatabase db = openOrCreateDatabase("Mydb",MODE_PRIVATE, null);
db.execSQL("create table if not exists simple(name varchar,address varchar,phone varchar");
ad.setOnClickListener(new OnClickListener() {
String n=name.getText().toString();
String a=addres.getText().toString();
String p= phon.getText().toString();
#Override
public void onClick(View v) {
db.execSQL("insert into simple values('n','a','p')");
Cursor c =db.rawQuery("select * from simple",null);
c.moveToFirst();
}
});
cn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i =new Intent(AddActivity.this,MainActivity.class);
startActivity(i);
}
});
}
}
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="100dp"
android:layout_marginTop="92dp"
android:text="Add" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button1"
android:layout_below="#+id/button1"
android:layout_marginTop="28dp"
android:text="Edit" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button2"
android:layout_below="#+id/button2"
android:layout_marginTop="37dp"
android:text="View" />
</RelativeLayout>
Add.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AddActivity" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView2"
android:layout_marginTop="60dp"
android:text="phone"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView3"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="17dp"
android:layout_marginTop="14dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_alignParentRight="true"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="80dp"
android:layout_toLeftOf="#+id/editText2"
android:text="Address"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView2"
android:ems="10"
android:inputType="textPostalAddress" />
<EditText
android:id="#+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView3"
android:layout_alignParentRight="true"
android:ems="10"
android:inputType="phone" />
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/phone"
android:layout_marginTop="62dp"
android:layout_toRightOf="#+id/textView1"
android:text="Add" />
<Button
android:id="#+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/add"
android:layout_marginLeft="36dp"
android:layout_toRightOf="#+id/add"
android:text="Cancel" />
</RelativeLayout>
ok I think you want to add the value of edit text into your db
package com.example.databasesample;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener {
static EditText edtAdd;
Button btnAdd, btnShow;
ListView listName;
static DataBaseSqlLiteHelper mBaseSqlLiteHelper;
DBModel mDbModel;
ArrayList<DBModel> mArrayList;
ListAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
mArrayList = new ArrayList<DBModel>();
mBaseSqlLiteHelper = new DataBaseSqlLiteHelper(MainActivity.this);
mBaseSqlLiteHelper.getReadableDatabase();
mBaseSqlLiteHelper.getWritableDatabase();
}
public void initialize() {
edtAdd = (EditText) findViewById(R.id.edtEnterName);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
btnShow = (Button) findViewById(R.id.btnShow);
btnShow.setOnClickListener(this);
listName = (ListView) findViewById(R.id.listName);
listName.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
deleteItem(mArrayList.get(arg2).getId());
}
});
}
#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;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnAdd:
addName(edtAdd.getText().toString());
break;
case R.id.btnShow:
showNames();
break;
default:
break;
}
}
// for adding values
public void addName(String name) {
SQLiteDatabase mOpenHelper = mBaseSqlLiteHelper.getWritableDatabase();
ContentValues mContentValues = new ContentValues();
mContentValues.put("name", name);
mOpenHelper.insert("NAMES", null, mContentValues);
mOpenHelper.close();
}
//showing values in list
public void showNames() {
String selectQuery = "SELECT * FROM NAMES";
SQLiteDatabase mDatabase = mBaseSqlLiteHelper.getWritableDatabase();
Cursor mCursor = mDatabase.rawQuery(selectQuery, null);
if (mCursor.moveToFirst()) {
do {
mDbModel = new DBModel();
mDbModel.setId(mCursor.getString(0));
mDbModel.setName(mCursor.getString(1));
mArrayList.add(mDbModel);
} while (mCursor.moveToNext());
}
mAdapter = new ListAdapter(MainActivity.this, mArrayList);
listName.setAdapter(mAdapter);
}
deleteing values
public void deleteItem(String id) {
SQLiteDatabase mDatabase = mBaseSqlLiteHelper.getWritableDatabase();
String delete = "Delete from NAMES Where _id =" + id;
mDatabase.execSQL(delete);
mDatabase.close();
mAdapter.notifyDataSetChanged();
mArrayList.remove(id);
}
//updating item
public static void updateItem(String id) {
SQLiteDatabase mDatabase = mBaseSqlLiteHelper.getWritableDatabase();
String update = "Update NAMES set name=\""
+ edtAdd.getText().toString() + "\" where _id=" + id;
mDatabase.execSQL(update);
mDatabase.close();
}
}
package com.example.databasesample;
public class DatabaseConstants {
public static final String CREATE_TABLE_PROFILE_QUERY = "CREATE TABLE NAMES("
+ " _id integer primary key autoincrement," + " name VARCHAR"
+ ")";
}
package com.example.databasesample;
import android.content.Context;
android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseSqlLiteHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "My Sample DataBase";
private static final int DATABASE_VERSION = 1;
public DataBaseSqlLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DatabaseConstants.CREATE_TABLE_PROFILE_QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
package com.example.databasesample;
public class DBModel {
String id;
String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.example.databasesample;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
public class ListAdapter extends BaseAdapter {
Context mContext;
ArrayList<DBModel> mArrayList;
public ListAdapter(Context mContext, ArrayList<DBModel> models) {
// TODO Auto-generated constructor stub
this.mArrayList = models;
this.mContext = mContext;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mArrayList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater mLayoutInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mLayoutInflater.inflate(R.layout.list_layout, parent,
false);
TextView txtId = (TextView) convertView.findViewById(R.id.txtId);
txtId.setText(mArrayList.get(position).getId());
TextView txtName = (TextView) convertView
.findViewById(R.id.txtName);
txtName.setText(mArrayList.get(position).getName());
Button btnUpdate=(Button)convertView.findViewById(R.id.btnUpdate);
btnUpdate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MainActivity.updateItem(mArrayList.get(position).getId());
}
});
}
return convertView;
}
}
//activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="#+id/edtEnterName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter Name" />
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edtEnterName"
android:text="Add to Database" />
<Button
android:id="#+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnAdd"
android:text="Show" />
<ListView
android:id="#+id/listName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnShow" >
</ListView>
//listlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtId"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/txtId" />
<Button
android:id="#+id/btnUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtName"
android:text="Update" />
Here I make an app in which you can add ,edit and update your database.i use Two main classes First DataBaseSqlLiteHelper.java to create databse and DatabaseConstants.java to create table. To delete item from db click on list and for update first enter value in edit text.comment on this if you need further help.
Ok if you want only a single value to show on database then you can do like this
take a textView
TextView txtName;
initialize it in my above method of initialize();
then make a method to get single value
// Getting single Name to textView
public void getContact(String id) {
SQLiteDatabase db = mBaseSqlLiteHelper.getReadableDatabase();
String select="Select name from NAMES Where _id ="+id;
Cursor mCursor=db.rawQuery(select,null);
if (mCursor!=null) {
mCursor.moveToFirst();
String name=mCursor.getString(0);
txtName.setText(name);
}
db.close();
}
then call this method on the click of some button and pass the id of the row you want to select.

Categories

Resources