I'm trying to create a Sign Up page for my Android system. I need to check validations for it like email_id already exists ,password should contain more than eight characters ,mobile number field should contain maximum 10 digits .How can I do it?? This is my code..I use java rest webservices and Mysql database
Sign Up.java
package com.example.locationapp;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.entity.StringEntity;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
#SuppressWarnings("deprecation")
public class SignUp extends Activity {
EditText et_name, et_email, et_password, et_conf_password, et_number;
Button signup;
private Context context;
private ProgressDialog pDialog;
private CheckInternet checkNet;
private Pattern pattern;
private Matcher matcher;
private String EMAIL_PATTERN, name, email, password, conf_password, number,
toastMessage;
private boolean emailValidity, internet_status;
private final String TAG_RESPONSE_CODE = "resp_code";
ServiceHandle jsonParser = new ServiceHandle();
private String url = "http://172.30.54.89:8080/LocationBasedFramework/SignUp/RegisterUser";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
context = SignUp.this;
et_name = (EditText) findViewById(R.id.nameEditText);
et_email = (EditText) findViewById(R.id.emailEditText);
et_password = (EditText) findViewById(R.id.passwordEditText);
et_conf_password = (EditText) findViewById(R.id.conf_passwordEditText);
et_number = (EditText) findViewById(R.id.numberEditText);
signup = (Button) findViewById(R.id.signUpbutton);
checkNet = new CheckInternet();
EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
pDialog = new ProgressDialog(SignUp.this);
pDialog.setMessage("New User...");
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// CheckInternet
name = et_name.getText().toString();
email = et_email.getText().toString();
password = et_password.getText().toString();
conf_password = et_conf_password.getText().toString();
number = et_number.getText().toString();
if (email.equals("")) {
toastMessage = "Email field cannot be empty";
et_email.requestFocus(1);
} else {
emailValidity = validate(email);
if (!emailValidity) {
toastMessage = "Invalid E_mail id";
et_email.setText("");
checkNet.ToastMessage(toastMessage,
getApplicationContext());
System.out.println("onclick 3.5");
et_email.requestFocus(1);
} else {
System.out.println("-------onClick4-------");
if (password.equals("")) {
toastMessage = "Password field cannot be empty";
checkNet.ToastMessage(toastMessage, context);
et_conf_password.setText("");
et_password.requestFocus(1);
} else {
if (conf_password.equals("")) {
toastMessage = "Please confirm your password";
checkNet.ToastMessage(toastMessage, context);
et_conf_password.requestFocus(1);
} else {
if (name.equals("")) {
toastMessage = "Plaese enter your name";
checkNet.ToastMessage(toastMessage, context);
et_name.requestFocus(1);
} else {
if (number.equals("")) {
toastMessage = "Mobile No field cannot be empty";
checkNet.ToastMessage(toastMessage,
context);
et_number.requestFocus(1);
} else {
System.out
.println("-------onClick8-------");
internet_status = checkNet
.isInternetOn(context);
if (internet_status == true) {
System.out
.println("-------onClick9-------");
new CreateUser().execute();
} else {
System.out
.println("-------onClick10-------");
checkNet.ifNoInternet(context);
}
}
}
}
}
}
}
}
});
}
public boolean validate(String email) {
CharSequence hex = null;
matcher = pattern.matcher(email);
return matcher.matches();
}
class CreateUser extends AsyncTask<String, String, String> {
StringEntity se = null;
JSONObject json;
String jsonStr = "";
Boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.show();
}
protected String doInBackground(String... params) {
try {
json = new JSONObject();
json.put("name", name);
json.put("email_id", email);
json.put("password", password);
json.put("mob_num", number);
se = new StringEntity(json.toString());
System.out.println("--after se--");
String method = "post";
// int response_flag = 1;
ServiceHandle sh = new ServiceHandle();
internet_status = checkNet
.isInternetOn(getApplicationContext());
System.out.println("--internet--" + internet_status);
if (internet_status == true) {
jsonStr = sh.makeServiceCall(url, method, se);
} else {
checkNet.ifNoInternet(context);
}
if (jsonStr != null) {
json = new JSONObject(jsonStr);
int resp_code = json.getInt(TAG_RESPONSE_CODE);
if (resp_code == 0) {
name = json.getString("TAG_Name");
email = json.getString("TAG_Email");
password = json.getString("TAG_Password");
conf_password = json.getString("TAG_confPassword");
number = json.getString("TAG_Number");
}
} else {
;
}
}
catch (Exception e) {
}
return null;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
pDialog.cancel();
int response_flag = 0;
if (response_flag == 0) {
int resp_code = 0;
if (resp_code == 0) {
SharedPreferences pref = getApplicationContext()
.getSharedPreferences("userData", MODE_PRIVATE);
Editor editor = pref.edit();
editor.clear();
editor.commit();
editor.putString("name", name);
editor.putString("e_mail", email);
editor.putString("password", password);
editor.putString("conf_password", conf_password);
editor.putString("number", number);
editor.commit();
Intent intent = new Intent(SignUp.this, ViewMap.class);
startActivity(intent);
finish();
}
}
} catch (Exception e) {
}
}
}
}
This is the xml for SignUp.java .
activity_sign_up.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="com.example.locationapp.SignUp" >
<TextView
android:id="#+id/NametextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:gravity="center"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/emailtextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:gravity="center"
android:text="Email-id"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/passwordtextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:gravity="center"
android:text="Password"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/conf_passwordtextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:gravity="center"
android:text="Confirm Password"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/numbertextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="250dp"
android:gravity="center"
android:text="Mobile"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" />
<EditText
android:id="#+id/nameEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/NametextView"
android:layout_alignBottom="#+id/NametextView"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/passwordtextView"
android:background="#FFFFFF"
android:ems="10" />
<EditText
android:id="#+id/emailEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/emailtextView"
android:layout_alignBottom="#+id/emailtextView"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/passwordtextView"
android:background="#FFFFFF"
android:ems="10" />
<EditText
android:id="#+id/passwordEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/passwordtextView"
android:layout_alignBottom="#+id/passwordtextView"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/passwordtextView"
android:background="#FFFFFF"
android:ems="10"
android:inputType="textPassword" />
<EditText
android:id="#+id/conf_passwordEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/conf_passwordtextView"
android:layout_alignBottom="#+id/passwordtextView"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/conf_passwordtextView"
android:background="#FFFFFF"
android:ems="10"
android:inputType="textPassword"/>
<EditText
android:id="#+id/numberEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/numbertextView"
android:layout_alignBottom="#+id/numbertextView"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/passwordtextView"
android:background="#FFFFFF"
android:ems="10"
android:inputType="number" />
<Button
android:id="#+id/signUpbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/numbertextView"
android:layout_marginTop="34dp"
android:layout_toRightOf="#+id/emailtextView"
android:gravity="center"
android:text="SIGNUP" />
</RelativeLayout>
To check validations for it like email_id already exists
...Manage it form server
password should contain more than eight characters ,mobile number field should contain maximum 10 digits
Just pass password to following given mathod
private boolean isValidEmail(String email) {
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
Related
I want to save the old state of checkbox With checkbox I want to update my data in database. When user changes the activity I lose his checked checkbox and when he again comes to that activity then every checkbox is unchecked and when he click to save with new values it will not saved because I set date as primary key in database. If I update the data with new values I lost my old data....
CheckBoxActivity.java
package com.example.shakeelmughal.assanislam;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
public class NamazCounterActivity extends AppCompatActivity {
DatabaseHelper mydb;
CheckBox cb1,cb2,cb3,cb4,cb5;
Button B1,B2,B3;
int vcb1=0,vcb2=0,vcb3=0,vcb4=0,vcb5=0,vet=0;
Date date = new Date();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_namaz_counter);
mydb = new DatabaseHelper(this);
SharedPreferences settings = getSharedPreferences("mysettings", 0);
SharedPreferences.Editor editor = settings.edit();
cb1 = findViewById(R.id.namaz1);
cb2 = findViewById(R.id.namaz2);
cb3 = findViewById(R.id.namaz3);
cb4 = findViewById(R.id.namaz4);
cb5 = findViewById(R.id.namaz5);
B1 = findViewById(R.id.result);
B2 = (Button) findViewById(R.id.dateee);
B3 = findViewById(R.id.sumr);
c_date();
B1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InsertingData();
}
});
B3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor cr = mydb.getAllData();
if(cr.getCount() == 0)
{
showData("Error","No Data Found");
return;
}
StringBuffer buffer = new StringBuffer();
while (cr.moveToNext())
{
buffer.append("ID: "+cr.getString(0)+ "\n");
buffer.append("Fajar: "+cr.getString(1)+ "\n");
buffer.append("Zohr: "+cr.getString(2)+ "\n");
buffer.append("Asr: "+cr.getString(3)+ "\n");
buffer.append("Magrib: "+cr.getString(2)+ "\n");
buffer.append("Isha: "+cr.getString(3)+ "\n");
}
showData("Data",buffer.toString());
}
});
//home button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}}
//function for going back to previous activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
public void InsertingData()
{
if(cb1.isChecked())
{
vcb1 = 1;
}
else
{
vcb1 = 0;
}
if(cb2.isChecked())
{
vcb2 = 1;
cb2.setChecked(true);
}
else
{
vcb2 = 0;
}
if(cb3.isChecked())
{
vcb3 = 1;
cb3.setChecked(true);
}
else
{
vcb3 = 0;
}
if(cb4.isChecked())
{
vcb4 = 1;
cb4.setChecked(true);
}
else
{
vcb4 = 0;
}
if(cb5.isChecked())
{
vcb5 = 1;
cb5.setChecked(true);
}
else
{
vcb5 = 0;
}
boolean result = mydb.InsertData(B2.getText().toString(),Integer.toString(vcb1),Integer.toString(vcb2),Integer.toString(vcb3),Integer.toString(vcb4),Integer.toString(vcb5));
if(result == true)
{
Toast.makeText(NamazCounterActivity.this, "Prayer Saved",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(NamazCounterActivity.this, "Some Error", Toast.LENGTH_LONG).show();
}
}
public void Updateingdata()
{
if(cb1.isChecked())
{
vcb1 = 1;
}
else
{
vcb1 = 0;
}
if(cb2.isChecked())
{
vcb2 = 1;
}
else
{
vcb2 = 0;
}
if(cb3.isChecked())
{
vcb3 = 1;
}
else
{
vcb3 = 0;
}
if(cb4.isChecked())
{
vcb4 = 1;
}
else
{
vcb4 = 0;
}
if(cb5.isChecked())
{
vcb5 = 1;
}
else
{
vcb5 = 0;
}
boolean res = mydb.UpdateData(B2.getText().toString(),Integer.toString(vcb1),Integer.toString(vcb2),Integer.toString(vcb3),Integer.toString(vcb4),Integer.toString(vcb5));
if(res == true)
{
Toast.makeText(NamazCounterActivity.this,"Data Updated",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(NamazCounterActivity.this,"Data Not Updated",Toast.LENGTH_SHORT).show();
}
}
//for date ()
public void c_date()
{
date.setTime(System.currentTimeMillis()); //set to current time
B2.setText(date.toString());
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEEEEEEE, MMM dd, yyyy");
B2.setText(dateFormat.format(date));
}
public void showData(String title, String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
Its XML file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.shakeelmughal.assanislam.NamazCounterActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrollView2">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="#+id/namaz1"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="47dp"
android:layout_marginStart="47dp"
android:layout_marginTop="50dp"
android:background="?android:attr/listChoiceIndicatorMultiple"
android:button="#null"
android:theme="#style/forCheckBox" />
<CheckBox
android:id="#+id/namaz2"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignLeft="#+id/namaz1"
android:layout_alignStart="#+id/namaz1"
android:layout_below="#+id/namaz1"
android:layout_marginTop="12dp"
android:button="#null"
android:background="?android:attr/listChoiceIndicatorMultiple"
android:theme="#style/forCheckBox" />
<CheckBox
android:id="#+id/namaz3"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignLeft="#+id/namaz2"
android:layout_alignStart="#+id/namaz2"
android:layout_below="#+id/namaz2"
android:layout_marginTop="19dp"
android:button="#null"
android:background="?android:attr/listChoiceIndicatorMultiple"
android:theme="#style/forCheckBox" />
<CheckBox
android:id="#+id/namaz4"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignLeft="#+id/namaz3"
android:layout_alignStart="#+id/namaz3"
android:layout_below="#+id/namaz3"
android:layout_marginTop="19dp"
android:button="#null"
android:background="?android:attr/listChoiceIndicatorMultiple"
android:theme="#style/forCheckBox" />
<CheckBox
android:id="#+id/namaz5"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignLeft="#+id/namaz4"
android:layout_alignStart="#+id/namaz4"
android:layout_below="#+id/namaz4"
android:layout_marginTop="11dp"
android:button="#null"
android:background="?android:attr/listChoiceIndicatorMultiple"
android:theme="#style/forCheckBox" />
<TextView
android:id="#+id/textView20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/namaz1"
android:layout_alignBottom="#+id/namaz1"
android:layout_marginLeft="41dp"
android:layout_marginStart="41dp"
android:layout_toEndOf="#+id/result"
android:layout_toRightOf="#+id/result"
android:text="نمازِ فجر"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="#+id/textView21"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/textView20"
android:layout_alignRight="#+id/textView20"
android:layout_alignTop="#+id/namaz2"
android:layout_marginTop="14dp"
android:text=" نمازِ ظہر / جمعہ"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="#+id/textView22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/textView21"
android:layout_alignRight="#+id/textView21"
android:layout_alignTop="#+id/namaz3"
android:layout_marginTop="11dp"
android:text="نمازِ عصر"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="#+id/textView23"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/namaz4"
android:layout_alignBottom="#+id/namaz4"
android:layout_alignEnd="#+id/textView21"
android:layout_alignRight="#+id/textView21"
android:text="نمازِ مغرب"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="#+id/textView24"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/textView23"
android:layout_alignRight="#+id/textView23"
android:layout_alignTop="#+id/namaz5"
android:layout_marginTop="12dp"
android:text="نمازِ عشاء"
android:textColor="#000"
android:textSize="20sp"/>
<Button
android:id="#+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView24"
android:layout_centerHorizontal="true"
android:text="Save" />
<Button
android:id="#+id/dateee"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView20"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/sumr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/result"
android:layout_centerHorizontal="true"
android:layout_marginTop="13dp"
android:text="View Summery" />
</RelativeLayout>
</ScrollView>
</RelativeLayout>
There could be many ways to do that, some of them are :
1. By using a File
2. By using shared preferences
I will recommend that latter one, a great implementation could be found by
Save CheckBox State to SharedPreferences File in Android
I'm new to Android Studio and have some problems with running example code :
activity_main.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.abdul.moqueet.currency.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="5"
android:id="#+id/et"
android:layout_marginTop="33dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spin"
android:layout_alignTop="#+id/et"
android:layout_toRightOf="#+id/et"
android:layout_toEndOf="#+id/et"
android:layout_marginLeft="47dp"
android:layout_marginStart="47dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/convert"
android:id="#+id/btn"
android:layout_marginTop="33dp"
android:layout_below="#+id/spin"
android:layout_toRightOf="#+id/et"
android:layout_toEndOf="#+id/et" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/usdtxt"
android:id="#+id/TextView1"
android:layout_marginTop="20dp"
android:layout_below="#+id/btn"
android:layout_alignLeft="#+id/spin"
android:layout_alignStart="#+id/spin"
android:layout_marginLeft="80dp"
android:layout_marginStart="80dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/eurtxt"
android:id="#+id/TextView2"
android:layout_marginTop="20dp"
android:layout_below="#+id/TextView1"
android:layout_alignLeft="#+id/spin"
android:layout_alignStart="#+id/spin"
android:layout_marginLeft="80dp"
android:layout_marginStart="80dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/inrtxt"
android:id="#+id/TextView3"
android:layout_marginTop="20dp"
android:layout_below="#+id/TextView2"
android:layout_alignLeft="#+id/spin"
android:layout_alignStart="#+id/spin"
android:layout_marginLeft="80dp"
android:layout_marginStart="80dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/zero"
android:id="#+id/usd"
android:layout_alignTop="#+id/TextView1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="17dp"
android:layout_marginStart="17dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/zero"
android:id="#+id/euro"
android:layout_above="#+id/TextView3"
android:layout_alignLeft="#+id/usd"
android:layout_alignStart="#+id/usd" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/zero"
android:id="#+id/inr"
android:layout_alignTop="#+id/TextView3"
android:layout_alignLeft="#+id/euro"
android:layout_alignStart="#+id/euro" />
</RelativeLayout>
MainActivity.java
package com.example.adriangranosik.coinconverter;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private EditText et;
private TextView usd, euro, inr;
private Button btn;
private Spinner spin;
private int index = 0;
private double inputvalue;
private String result[] = new String[10];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.et);
usd = (TextView) findViewById(R.id.usd);
euro = (TextView) findViewById(R.id.euro);
inr = (TextView) findViewById(R.id.inr);
btn = (Button) findViewById(R.id.btn);
spin = (Spinner) findViewById(R.id.spin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.currency, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
index = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
usd.setText("wait...");
euro.setText("wait...");
inr.setText("wait...");
if (et.getText().toString().trim().length() > 0 && !et.getText().toString().trim().equals(".")) {
String textValue = et.getText().toString();
inputvalue = Double.parseDouble(textValue);
new calculate().execute();
}
}
});
}
public class calculate extends AsyncTask<String, String, String[]> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String[] doInBackground(String... params) {
if (index == 0) {
String uRl;
try {
uRl = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDEUR,USDINR%22)&format=json&env=store://datatables.org/alltableswithkeys");
JSONObject USDtojObj;
USDtojObj = new JSONObject(uRl);
JSONArray rateArray = USDtojObj.getJSONObject("query").getJSONObject("results").getJSONArray("rate");
result[0] = rateArray.getJSONObject(0).getString("Rate");
result[1] = rateArray.getJSONObject(1).getString("Rate");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} else if (index == 1) {
String uRl;
try {
uRl = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22EURUSD,EURINR%22)&format=json&env=store://datatables.org/alltableswithkeys");
JSONObject EurotojObj;
EurotojObj = new JSONObject(uRl);
JSONArray rateArray = EurotojObj.getJSONObject("query").getJSONObject("results").getJSONArray("rate");
result[0] = rateArray.getJSONObject(0).getString("Rate");
result[1] = rateArray.getJSONObject(1).getString("Rate");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} else if (index == 2) {
String uRl;
try {
uRl = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22INRUSD,INREUR%22)&format=json&env=store://datatables.org/alltableswithkeys");
JSONObject INRtojObj;
INRtojObj = new JSONObject(uRl);
JSONArray rateArray = INRtojObj.getJSONObject("query").getJSONObject("results").getJSONArray("rate");
result[0] = rateArray.getJSONObject(0).getString("Rate");
result[1] = rateArray.getJSONObject(1).getString("Rate");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
return result;
}
#Override
protected void onPostExecute(String[] strings) {
if(index == 0){
double usdtoeuroval, usdtoinrval, usdtoeuroinp, usdtoinrinp, usdtousdinp;
usdtousdinp = inputvalue * 1;
usd.setText(""+usdtousdinp);
usdtoeuroval = Double.parseDouble(result[0]);
usdtoeuroinp = inputvalue * usdtoeuroval;
euro.setText(""+usdtoeuroinp);
usdtoinrval = Double.parseDouble(result[1]);
usdtoinrinp = inputvalue * usdtoinrval;
inr.setText(""+usdtoinrinp);
}else if(index == 1){
double eurotousdval, eurotoinrval, eurotousdinp, eurotoinrinp, eurotoeuroinp;
eurotoeuroinp = inputvalue * 1;
euro.setText(""+eurotoeuroinp);
eurotousdval = Double.parseDouble(result[0]);
eurotousdinp = inputvalue * eurotousdval;
usd.setText(""+eurotousdinp);
eurotoinrval = Double.parseDouble(result[1]);
eurotoinrinp = inputvalue * eurotoinrval;
inr.setText(""+eurotoinrinp);
}else if(index == 2){
double inrtousdval, inrtoeuroval, inrtousdinp, inrtoeuroinp, inrtoinrinp;
inrtoinrinp = inputvalue * 1;
inr.setText(""+inrtoinrinp);
inrtousdval = Double.parseDouble(result[0]);
inrtousdinp = inputvalue * inrtousdval;
usd.setText(""+inrtousdinp);
inrtoeuroval = Double.parseDouble(result[1]);
inrtoeuroinp = inputvalue * inrtoeuroval;
euro.setText(""+inrtoeuroinp);
}
}
public String getJson(String url) throws ClientProtocolException, IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
}
}
I am getting Following Errors :
layout/activity_main.xml
error: resource dimen/activity_vertical_margin (aka com.example.adriangranosik.coinconverter:dimen/activity_vertical_margin) not found.
error: resource dimen/activity_horizontal_margin (aka com.example.adriangranosik.coinconverter:dimen/activity_horizontal_margin) not found.
error: resource string/convert (aka com.example.adriangranosik.coinconverter:string/convert) not found.
error: resource string/usdtxt (aka com.example.adriangranosik.coinconverter:string/usdtxt) not found.
error: resource string/eurtxt (aka com.example.adriangranosik.coinconverter:string/eurtxt) not found.
error: resource string/inrtxt (aka com.example.adriangranosik.coinconverter:string/inrtxt) not found.
error: resource string/zero (aka com.example.adriangranosik.coinconverter:string/zero) not found.
error: resource string/zero (aka com.example.adriangranosik.coinconverter:string/zero) not found.
error: resource string/zero (aka com.example.adriangranosik.coinconverter:string/zero) not found.
null
failed linking file resources.
I just wanna run a program to analyze source code. I know there is dimens.xml file which is missing but i have no clue what to put there.
I'm new in Android dev so i found example code just to learn how to create apps like that. But it's hard when i cannot run it :D
Thanks for your help.
you may just replace this
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
with smth like
android:paddingBottom="8dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingTop="8dp"
(or if all 4 paddings are equal, you may set just android:padding="8dp")
In res -> Values put this code in dimens.xml
<dimen name="activity_vertical_margin">3dp</dimen>
Adjust dp according to your UI.
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
replace above code with below lines in RelativeLayout :
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
Android Studio is showing open app again app-crash when I click sign up button
The app is running fine but when I click the sign up button it crashes, also want to start new activity after sign up but the error is com
I think there is some problem with button click listener or validation code but don't know where this error is coming from.
following is my java file code:
public class SignUp extends AppCompatActivity {
private static final String TAG = "SignUp";
private Vibrator vib;
Animation animShake;
private EditText signupInputName, signupInputEmail, signupInputPassword, signupInputDOB;
private TextInputLayout signupInputLayoutName, signupInputLayoutEmail, signupInputLayoutPasword, signupInputLayoutDOB;
private Button btnSignUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up_form);
signupInputLayoutName = (TextInputLayout) findViewById(R.id.sign_up_name);
signupInputLayoutName = (TextInputLayout) findViewById(R.id.sign_up_email);
signupInputLayoutName = (TextInputLayout) findViewById(R.id.sign_up_Password);
signupInputLayoutName = (TextInputLayout) findViewById(R.id.sign_up_DOB);
signupInputName = (EditText) findViewById(R.id.signup_input_name);
signupInputName = (EditText) findViewById(R.id.signup_input_email);
signupInputName = (EditText) findViewById(R.id.signup_input_Password);
signupInputName = (EditText) findViewById(R.id.signup_input_DOB);
btnSignUp = (Button) findViewById(R.id.btn_signUp);
animShake = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shake);
vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
register();
}
});
}
public void register() {
submitForm();
{
if (!checkName() || !checkEmail() || !checkDOB() || !checkPassword()) {
Toast.makeText(this, "signup failed", Toast.LENGTH_SHORT).show();
} else {
onSignupSuccess();
}
}
}
public void onSignupSuccess() {
Intent intent = new Intent(SignUp.this, tab1Petrol.class);
startActivity(intent);
finish();
}
private void submitForm() {
if (!checkName()) {
signupInputName.setAnimation(animShake);
signupInputName.startAnimation(animShake);
vib.vibrate(125);
return;
}
if (!checkEmail()) {
signupInputEmail.setAnimation(animShake);
signupInputEmail.startAnimation(animShake);
vib.vibrate(125);
return;
}
if (!checkPassword()) {
signupInputPassword.setAnimation(animShake);
signupInputPassword.startAnimation(animShake);
vib.vibrate(125);
return;
}
if (!checkDOB()) {
signupInputDOB.setAnimation(animShake);
signupInputDOB.startAnimation(animShake);
vib.vibrate(125);
return;
}
signupInputLayoutName.setErrorEnabled(false);
signupInputLayoutEmail.setErrorEnabled(false);
signupInputLayoutPasword.setErrorEnabled(false);
signupInputLayoutDOB.setErrorEnabled(false);
Toast.makeText(this, "you are successfully Registered", Toast.LENGTH_SHORT).show();
}
private boolean checkName() {
if (signupInputName.getText().toString().trim().isEmpty()) {
signupInputLayoutName.setErrorEnabled(true);
signupInputLayoutName.setError("Please enter a Name");
signupInputName.setError("valid Input Required");
return false;
}
signupInputLayoutName.setErrorEnabled(false);
return true;
}
private boolean checkEmail() {
String email = signupInputEmail.getText().toString().trim();
if (email.isEmpty() || !isValidEmail(email)) {
signupInputLayoutEmail.setErrorEnabled(true);
signupInputLayoutEmail.setError("Please enter a Valid Email");
signupInputEmail.setError("valid Input Required");
requestFocus(signupInputEmail);
return false;
}
signupInputLayoutEmail.setErrorEnabled(false);
return true;
}
private boolean checkPassword() {
if (signupInputPassword.getText().toString().trim().isEmpty()) {
signupInputLayoutPasword.setError("Please enter password");
requestFocus(signupInputPassword);
return false;
}
signupInputLayoutPasword.setErrorEnabled(false);
return true;
}
private boolean checkDOB() {
try {
boolean isDateValid = false;
String[] s = signupInputDOB.getText().toString().split("/");
int date = Integer.parseInt(s[0]);
int month = Integer.parseInt(s[1]);
if (date < 32 && month < 13)
isDateValid = true;
if (signupInputDOB.getText().toString().trim().isEmpty() && isDateValid) {
signupInputLayoutDOB.setError("Enter a valid D.O.B");
requestFocus(signupInputDOB);
signupInputDOB.setError("valid input required");
return false;
}
} catch (Exception ex) {
signupInputLayoutDOB.setError("Enter a valid D.O.B");
requestFocus(signupInputDOB);
return false;
}
signupInputDOB.setError(null);
return true;
}
private static boolean isValidEmail(String email) {
return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
}
XML file code:
<?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:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center">
<android.support.design.widget.TextInputLayout
android:id="#+id/sign_up_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<EditText
android:id="#+id/signup_input_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/name" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/sign_up_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<EditText
android:id="#+id/signup_input_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textEmailAddress"
android:hint="Email" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/sign_up_Password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<EditText
android:id="#+id/signup_input_Password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword"
android:hint="Password" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/sign_up_DOB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<EditText
android:id="#+id/signup_input_DOB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:maxLines="1"
android:hint="Date of Birth" />
</android.support.design.widget.TextInputLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/gender_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am"
android:fontFeatureSettings="Password"
android:textSize="20dp"
android:fontFamily="Password"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/gender_textView"
android:orientation="horizontal">
<RadioButton
android:id="#+id/male_radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:checked="true"/>
<RadioButton
android:id="#+id/Female_radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"/>
</RadioGroup>
</RelativeLayout>
<Button
android:id="#+id/btn_signUp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:text="Sign Up"
android:textColor="#android:color/white" />
</LinearLayout>
</LinearLayout>
Well for starters you are re-assigning the Input fields here, overwriting the previous one... I'm pretty sure the issue is because of this.
signupInputName = (EditText) findViewById(R.id.signup_input_name);
signupInputName = (EditText) findViewById(R.id.signup_input_email);
signupInputName = (EditText) findViewById(R.id.signup_input_Password);
signupInputName = (EditText) findViewById(R.id.signup_input_DOB);
signupInputLayoutName = (TextInputLayout) findViewById(R.id.sign_up_name);
signupInputLayoutName = (TextInputLayout) findViewById(R.id.sign_up_email);
signupInputLayoutName = (TextInputLayout) findViewById(R.id.sign_up_DOB);
The very first thing your code does after onCreate() is checkEmail(), and as I stated above, there is no R.id.signup_input_email assigned to signupInputEmail.
Your code will throw an exception here since checkEmail() refers to a NULL variable.
if (!checkEmail()) { ... }
When I run my android app and activate a click event that tries to transfer data from a table row to post it to a PHP file, the main thread forces the app to shut-down regardless of using another thread in the background to establish the network connection (using AsyncTask). Below I have provided my files:
MainActivity.java
package com.example.stevenkennedy.categorizer;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
public class MainActivity extends AppCompatActivity {
// Local Variables
private Boolean snapBool = false;
private Boolean snapBool2 = false;
private Boolean snapBool3 = false;
private Boolean snapBool4 = false;
private Boolean snapBool5 = false;
// Add ImageView objects for camera
private ImageView snap;
private ImageView snap2;
private ImageView snap3;
private ImageView snap4;
private ImageView snap5;
private static final int CAMERA_REQUEST = 1888;
// Add Button for click event for server communication
private Button sendBtn;
// Row 1
private EditText idRow1;
private EditText nameRow1;
private Spinner categoryRow1;
private EditText commentRow1;
private EditText priceRow1;
private ImageView galleryRow1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Row 1
idRow1 = (EditText) findViewById(R.id.idBox);
nameRow1 = (EditText) findViewById(R.id.nameBox);
categoryRow1 = (Spinner) findViewById(R.id.cateBox);
commentRow1 = (EditText) findViewById(R.id.commBox);
priceRow1 = (EditText) findViewById(R.id.priceBox);
galleryRow1 = (ImageView) findViewById(R.id.gallBox);
// listeners for camera event
snap = (ImageView) findViewById(R.id.gallBox);
snap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
// flag local boolean
snapBool = true;
}
});
snap2 = (ImageView) findViewById(R.id.gallBox2);
snap2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
// flag local boolean
snapBool2 = true;
}
});
snap3 = (ImageView) findViewById(R.id.gallBox3);
snap3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
// flag local boolean
snapBool3 = true;
}
});
snap4 = (ImageView) findViewById(R.id.gallBox4);
snap4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
// flag local boolean
snapBool4 = true;
}
});
snap5 = (ImageView) findViewById(R.id.gallBox5);
snap5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
// flag local boolean
snapBool5 = true;
}
});
// confirm button to send data to server
sendBtn = (Button) findViewById(R.id.send);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// create AsyncTask to get user entered cell data
new MyTask().execute();
}
});
} // ******** ON CREATE END ************
/*
* Method that activates the camera and gets a thumbnail of the photo for the
* table cell
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
if (snapBool == true) {
snap.setImageBitmap(photo);
} else if (snapBool2 == true) {
snap2.setImageBitmap(photo);
} else if (snapBool3 == true) {
snap3.setImageBitmap(photo);
} else if (snapBool4 == true) {
snap4.setImageBitmap(photo);
} else if(snapBool5 == true) {
snap5.setImageBitmap(photo);
}
// set boolean flags back to false
snapBool = false;
snapBool2 = false;
snapBool3 = false;
snapBool4 = false;
snapBool5 = false;
}
}
/*
* Method to get cell data of Row 1 and send it to a sql server using
* post data with php
*/
public void getCells() {
// get the data in boxes
String str1 = idRow1.getText().toString();
String str2 = nameRow1.getText().toString();
String str3 = categoryRow1.getSelectedItem().toString();
String str4 = commentRow1.getText().toString();
String str5 = priceRow1.getText().toString();
//galleryRow1.get
// create sql object
MySQLConnect sql = new MySQLConnect(str1, str2, str3, str4, str5, "png23.png");
sql.sendTo();
}
/**
* AsyncTask Class
*/
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
getCells();
return null;
}
protected void onPostExecute(String result) {}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
} // ************** CLASS END **************
MySQLConnect.java
package com.example.stevenkennedy.categorizer;
import android.media.Image;
import android.os.AsyncTask;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
/**
* Created by Steven Kennedy on 27/10/2015.
*/
public class MySQLConnect {
// Class Variables
private String id;
private String name;
private String cate;
private String comm;
private String price;
private String gall;
// constructor
public MySQLConnect(String id, String name, String cate, String comm, String price, String gall){
this.id = id;
this.name = name;
this.cate = cate;
this.comm = comm;
this.price = price;
this.gall = gall;
}
// getters and setters
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;
}
public String getCate() {
return cate;
}
public void setCate(String cate) {
this.cate = cate;
}
public String getComm() {
return comm;
}
public void setComm(String comm) {
this.comm = comm;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getGall() {
return gall;
}
public void setGall(String gall) {
this.gall = gall;
}
public void sendTo() {
// HTTP client
HttpClient client = new DefaultHttpClient();
// use php to post data to
HttpPost post = new HttpPost("http://myPHPfile.com/myFile.php");
try {
// add to arraylist
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
// add values
nameValuePairs.add(new BasicNameValuePair("id", this.getId() ));
nameValuePairs.add(new BasicNameValuePair("name", this.getName()));
nameValuePairs.add(new BasicNameValuePair("category", this.getCate()));
nameValuePairs.add(new BasicNameValuePair("comment", this.getComm()));
nameValuePairs.add(new BasicNameValuePair("price", this.getPrice()));
//nameValuePairs.add(new BasicNameValuePair("gallery", this.getGall()));
// send to server - POST
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//HttpResponse response = client.execute(post);
client.execute(post);
} catch (ClientProtocolException ed) {
// TODO Auto-generated catch block
ed.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} // ********* END ***********
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Header Table -->
<TableLayout
android:id="#+id/topTable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left|top"
android:background="#B3EAFF">
<TableRow android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:padding="10dip">
<TextView
android:id="#+id/idTitle"
android:text="id"
android:gravity="right"
android:paddingRight="70dp"/>
<TextView
android:text="Name"
android:paddingRight="75dp"/>
<TextView
android:text="Category"
android:paddingRight="55dp" />
<TextView
android:text="Comment"
android:paddingRight="45dp" />
<TextView
android:text="Price"
android:paddingRight="30dp" />
<TextView
android:text="Gallery" />
</TableRow>
<!-- drawn line -->
<View
android:layout_height="2dip"
android:background="#FF909090" />
</TableLayout>
<!-- Scroll Layout -->
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView"
android:layout_below="#+id/topTable"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:scrollbars="vertical">
<RelativeLayout
android:layout_width="fill_parent"
android:orientation="vertical"
android:id="#+id/linearLayout1"
android:layout_height="fill_parent"
android:layout_alignTop="#+id/scrollView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<!-- Row 1 -->
<EditText
android:layout_width="70dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:id="#+id/idBox" />
<EditText
android:layout_width="110dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:id="#+id/nameBox"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/idBox"
android:layout_toEndOf="#+id/idBox" />
<Spinner
android:layout_width="110dip"
android:layout_height="45dip"
android:entries="#array/cate_array"
android:prompt="#string/cate_spin"
android:background="#drawable/border_style"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/nameBox"
android:layout_toEndOf="#+id/nameBox"
android:id="#+id/cateBox" />
<EditText
android:layout_width="120dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/cateBox"
android:layout_toEndOf="#+id/cateBox"
android:id="#+id/commBox" />
<EditText
android:layout_width="60dip"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:digits="0123456789."
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/commBox"
android:layout_toEndOf="#+id/commBox"
android:id="#+id/priceBox" />
<!--<EditText
android:layout_width="90dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:onClick="true"
android:text=" [ O ]"
android:editable="false"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/priceBox"
android:layout_toEndOf="#+id/priceBox"
android:id="#+id/gallBox" />-->
<ImageView
android:layout_width="90dip"
android:layout_height="45dip"
android:background="#drawable/border_style"
android:onClick="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/priceBox"
android:layout_toEndOf="#+id/priceBox"
android:id="#+id/gallBox"/>
<!-- Row 2 -->
<EditText
android:layout_width="70dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_below="#+id/idBox"
android:id="#+id/idBox2" />
<EditText
android:layout_width="110dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:id="#+id/nameBox2"
android:layout_below="#+id/nameBox"
android:layout_toRightOf="#+id/idBox2" />
<Spinner
android:layout_width="110dip"
android:layout_height="45dip"
android:entries="#array/cate_array"
android:prompt="#string/cate_spin"
android:background="#drawable/border_style"
android:layout_toRightOf="#+id/nameBox2"
android:layout_below="#+id/cateBox"
android:id="#+id/cateBox2" />
<EditText
android:layout_width="120dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_toRightOf="#+id/cateBox2"
android:layout_below="#+id/commBox"
android:id="#+id/commBox2" />
<EditText
android:layout_width="60dip"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:digits="0123456789."
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_toRightOf="#+id/commBox2"
android:layout_below="#+id/priceBox"
android:id="#+id/priceBox2" />
<ImageView
android:layout_width="90dip"
android:layout_height="45dip"
android:background="#drawable/border_style"
android:onClick="true"
android:layout_toRightOf="#+id/priceBox2"
android:layout_below="#+id/gallBox"
android:id="#+id/gallBox2"/>
<!-- Row 3 -->
<EditText
android:layout_width="70dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_below="#+id/idBox2"
android:id="#+id/idBox3" />
<EditText
android:layout_width="110dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:id="#+id/nameBox3"
android:layout_below="#+id/nameBox2"
android:layout_toRightOf="#+id/idBox3" />
<Spinner
android:layout_width="110dip"
android:layout_height="45dip"
android:entries="#array/cate_array"
android:prompt="#string/cate_spin"
android:background="#drawable/border_style"
android:layout_toRightOf="#+id/nameBox3"
android:layout_below="#+id/cateBox2"
android:id="#+id/cateBox3" />
<EditText
android:layout_width="120dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_toRightOf="#+id/cateBox3"
android:layout_below="#+id/commBox2"
android:id="#+id/commBox3" />
<EditText
android:layout_width="60dip"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:digits="0123456789."
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_toRightOf="#+id/commBox3"
android:layout_below="#+id/priceBox2"
android:id="#+id/priceBox3" />
<ImageView
android:layout_width="90dip"
android:layout_height="45dip"
android:background="#drawable/border_style"
android:onClick="true"
android:layout_toRightOf="#+id/priceBox3"
android:layout_below="#+id/gallBox2"
android:id="#+id/gallBox3"/>
<!-- Row 4 -->
<EditText
android:layout_width="70dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_below="#+id/idBox3"
android:id="#+id/idBox4" />
<EditText
android:layout_width="110dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:id="#+id/nameBox4"
android:layout_below="#+id/nameBox3"
android:layout_toRightOf="#+id/idBox4" />
<Spinner
android:layout_width="110dip"
android:layout_height="45dip"
android:entries="#array/cate_array"
android:prompt="#string/cate_spin"
android:background="#drawable/border_style"
android:layout_toRightOf="#+id/nameBox4"
android:layout_below="#+id/cateBox3"
android:id="#+id/cateBox4" />
<EditText
android:layout_width="120dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_toRightOf="#+id/cateBox4"
android:layout_below="#+id/commBox3"
android:id="#+id/commBox4" />
<EditText
android:layout_width="60dip"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:digits="0123456789."
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_toRightOf="#+id/commBox4"
android:layout_below="#+id/priceBox3"
android:id="#+id/priceBox4" />
<ImageView
android:layout_width="90dip"
android:layout_height="45dip"
android:background="#drawable/border_style"
android:onClick="true"
android:layout_toRightOf="#+id/priceBox4"
android:layout_below="#+id/gallBox3"
android:id="#+id/gallBox4"/>
<!-- Row 5 -->
<EditText
android:layout_width="70dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_below="#+id/idBox4"
android:id="#+id/idBox5" />
<EditText
android:layout_width="110dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:id="#+id/nameBox5"
android:layout_below="#+id/nameBox4"
android:layout_toRightOf="#+id/idBox5" />
<Spinner
android:layout_width="110dip"
android:layout_height="45dip"
android:entries="#array/cate_array"
android:prompt="#string/cate_spin"
android:background="#drawable/border_style"
android:layout_toRightOf="#+id/nameBox5"
android:layout_below="#+id/cateBox4"
android:id="#+id/cateBox5" />
<EditText
android:layout_width="120dip"
android:layout_height="wrap_content"
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_toRightOf="#+id/cateBox5"
android:layout_below="#+id/commBox4"
android:id="#+id/commBox5" />
<EditText
android:layout_width="60dip"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:digits="0123456789."
android:background="#drawable/border_style"
android:singleLine="true"
android:scrollHorizontally="true"
android:layout_toRightOf="#+id/commBox5"
android:layout_below="#+id/priceBox4"
android:id="#+id/priceBox5" />
<ImageView
android:layout_width="90dip"
android:layout_height="45dip"
android:background="#drawable/border_style"
android:onClick="true"
android:layout_toRightOf="#+id/priceBox5"
android:layout_below="#+id/gallBox4"
android:id="#+id/gallBox5"/>
<!-- Send to server -->
<Button
android:id="#+id/send"
android:layout_width="80dp"
android:layout_height="40dp"
android:text="Send"
android:layout_below="#+id/idBox5"
android:layout_marginTop="15dp" />
</RelativeLayout>
</ScrollView>
myFile.php
<?php
$servername = "******";
$username = "*****";
$password = "*****";
$dbname = "*****";
// POST data
$idPass = $_POST['id'];
$namePass = $_POST['name'];
$catePass = $_POST['category'];
$commPass = $_POST['comment];
$pricePass = $_POST['price'];
//$gallPass = $_POST['gallery'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO viewer VALUES ('$idPass', '$namePass', '$catePass', '$commPass', '$pricePass', 'imge.png')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
If anyone knows a better way to connect to a database that doesn't require a lot of memory usage, I would gladly take that as an answer. I also know about Apache libraries being depreciated as of the latest updates, and have tried the java HttpURLConnection class to post data, but got the same issue of the main thread exception.
Probably you are getting an exception like: "Method getText() must be called from the UI thread, currently inferred thread is worker."
You cannot use the View#getText() from the background Thread in your AsyncTask.
What you need to do is to pass your Strings on your execute method changing the signature in:
private class MyTask extends AsyncTask<String, Void, Void> {
No. you just need to add :
new THread(new Runable(){on Run()}).start() to wrap up your code for request!
public void sendTo() {
new Thread(new Runnable() {
#Override
public void run() {
// HTTP client
HttpClient client = new DefaultHttpClient();
// use php to post data to
HttpPost post = new HttpPost("http://myPHPfile.com/myFile.php");
try {
// add to arraylist
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
// add values
nameValuePairs.add(new BasicNameValuePair("id", this.getId() ));
nameValuePairs.add(new BasicNameValuePair("name", this.getName()));
nameValuePairs.add(new BasicNameValuePair("category", this.getCate()));
nameValuePairs.add(new BasicNameValuePair("comment", this.getComm()));
nameValuePairs.add(new BasicNameValuePair("price", this.getPrice()));
//nameValuePairs.add(new BasicNameValuePair("gallery", this.getGall()));
// send to server - POST
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//HttpResponse response = client.execute(post);
client.execute(post);
} catch (ClientProtocolException ed) {
// TODO Auto-generated catch block
ed.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
I tried everything but unable to disable that save button. i wrote it at the end of my onCreate.
Actually i wanted if user edits some notes and selects category from spinner it will automatically get enabled and i achieved it.
But i want that first when user is on this page button should be disabled. When user dose his work it will enable.
But how should i disable this save button.
Here is my OfflinePBDetails.java class
package passbookManager;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
import logs.TraceLog;
import mainApplication.*;
import forbes.mPassbook.R;
import databaseClasses.DBAccountStatement;
import databaseClasses.DBCategoryMaster;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
public class OfflinePBDetails extends Activity implements OnItemSelectedListener
{
TextView tvDate;
TextView tvAmount;
TextView tvBalance;
TextView tvParticular;
TextView tvTitleAmount;
EditText etNotes;
Spinner spinnerCategory;
Button btnBack;
Button btnSave;
String file_Path;
Properties properties_config;
long sessionTimeout;
String passTransId;
String passDate;
String passParticular;
String passDebitCreditIndicator;
String passAmount;
String passTransString;
String passBalance;
String passFlag;
String transId;
String notes;
int countDBRows;
int countDBColumns;
String dbSubCategory;
String dbNotes;
String selectedCategory;
String[][] tableCategory ;
ArrayList<String> categoryIncome;
ArrayList<String> categoryExpense;
ArrayAdapter<String> adapterSelect;
DBCategoryMaster dbCMaster;
DBAccountStatement dbStatement;
TraceLog tc = new TraceLog();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ActionBar bar=getActionBar();
bar.hide();
setContentView(R.layout.activity_offline_pbdetails);
dbCMaster = new DBCategoryMaster(this);
dbStatement = new DBAccountStatement(this);
file_Path=Environment.getExternalStorageDirectory()+ "/Android/data/forbes.mPassbook/";
readConfigFileDetails();
if( Build.VERSION.SDK_INT >= 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
try
{
tvDate = (TextView)findViewById(R.id.tv_getDate);
tvParticular = (TextView)findViewById(R.id.tv_getParticular);
tvAmount = (TextView)findViewById(R.id.tv_getAmount);
tvTitleAmount = (TextView)findViewById(R.id.tv_titleAmount);
tvBalance = (TextView)findViewById(R.id.tv_getBalance);
spinnerCategory = (Spinner)findViewById(R.id.spn_selectCategory);
etNotes = (EditText)findViewById(R.id.et_getNotes);
btnBack = (Button)findViewById(R.id.btnBack);
btnSave = (Button)findViewById(R.id.btnSave);
Intent intent = getIntent();
passTransId = intent.getExtras().getString("TransactionId");
passDate = intent.getExtras().getString("Date");
passParticular = intent.getExtras().getString("Particular");
passAmount = intent.getExtras().getString("Amount");
passTransString = intent.getExtras().getString("TransString");
passDebitCreditIndicator = intent.getExtras().getString("Indicator");
passBalance = intent.getExtras().getString("Balance");
passFlag = intent.getExtras().getString("FilterFlag");
tvDate.setText(passDate);
tvParticular.setText(passParticular);
tvTitleAmount.setText(passTransString);
if(tvTitleAmount.getText().equals("Withdrawal Amount"))
{
tvAmount.setTextColor(Color.RED);
}
else
{
tvAmount.setTextColor(Color.rgb(48,128,20));
}
String trimAmount = passAmount.trim();
String trimBalance = passBalance.trim();
tvAmount.setText(trimAmount);
tvBalance.setText(trimBalance);
etNotes.addTextChangedListener(new TextWatcher()
{
#Override
public void afterTextChanged(Editable arg0)
{
btnSave.setEnabled(true);
resetDisconnectTimer();
// Toast.makeText(getApplicationContext(), "After Typing", Toast.LENGTH_LONG).show();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
// Toast.makeText(getApplicationContext(), "Before Typing", Toast.LENGTH_LONG).show();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
// Toast.makeText(getApplicationContext(), "Typing", Toast.LENGTH_LONG).show();
}
});
btnBack.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(passFlag.equalsIgnoreCase("OfflinePB"))
{
Intent i = new Intent(OfflinePBDetails.this,OfflinePB.class);
i.putExtra("filterFlag","notes");/**********Code to go back to DisplayFilter Page***************************/
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
else if(passFlag.equalsIgnoreCase("notes"))
{
Intent i = new Intent(OfflinePBDetails.this,DisplayFilters.class);
i.putExtra("filterFlag","notes");
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
else if(passFlag.equalsIgnoreCase("transfer"))
{
Intent i = new Intent(OfflinePBDetails.this,DisplayFilters.class);
i.putExtra("filterFlag","transfer");
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
else if(passFlag.equalsIgnoreCase("cheque"))
{
Intent i = new Intent(OfflinePBDetails.this,DisplayFilters.class);
i.putExtra("filterFlag","cheque");
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
}
});
btnSave.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
try
{
btnSave.setEnabled(false);
transId = passTransId;
notes = etNotes.getText().toString();
// if(spinnerCategory.length()==0)
// {
// spinnerCategory.setError("Please Enter mPIN ");
// mPin.requestFocus();
// }
// else
// if(notes.trim().length()==0)
// {
// etNotes.setError("Please Add Your Notes ");
// etNotes.setText(null);
// etNotes.requestFocus();
// }
if(dbStatement.updatePassbook(transId, selectedCategory, notes))
{
Toast.makeText(getApplicationContext(), "Data Updated Successfully", Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "selectedCategory : " + selectedCategory, Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "notes : " + notes, Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
tc.WriteToTransactionLog("Exception: OfflinePBDetails.java Save.setOnClickListener():- "+e.toString());
}
}
});
dbGetCategoryList();
btnSave.setEnabled(false);
}
catch(Exception e)
{
tc.WriteToTransactionLog("Exception: OfflinePBDetails.java onCreate():- "+e.toString());
}
}
public void dbGetCategoryList()
{
int element;
try
{
Cursor rs = dbCMaster.getData();
countDBRows = rs.getCount();
countDBColumns = rs.getColumnCount();
tableCategory = new String[countDBRows][countDBColumns];
rs.moveToFirst();
for(element = 0; element < countDBRows; element++)
{
tableCategory[element][0] = rs.getString(0); // subCategory
tableCategory[element][1] = rs.getString(1); // Category
tableCategory[element][2] = rs.getString(2); // transType
rs.moveToNext();
// String finalData = tableCategory[element][0]+ " " + tableCategory[element][1]
// + " " + tableCategory[element][2];
// Toast.makeText(getApplicationContext(), "finalData : " + finalData, Toast.LENGTH_SHORT).show();
}
rs.close();
showCategoryList();
}
catch(Exception e)
{
tc.WriteToTransactionLog("Exception: OfflinePBDetails.java dbGetCategoryList():- "+e.toString());
}
}
public void showCategoryList()
{
int i = 0;
int j = 0;
int element;
String transType;
categoryIncome = new ArrayList<String>();
categoryExpense = new ArrayList<String>();
// categoryIncome = new String[2];
// categoryExpense = new String[3];
try
{
for(element = 0; element < countDBRows; element++)
{
transType = tableCategory[element][2];
// Toast.makeText(getApplicationContext(), "transType : " + transType, Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(), "passDebitCreditIndicator : " + passDebitCreditIndicator, Toast.LENGTH_SHORT).show();
if(passDebitCreditIndicator.equalsIgnoreCase("D"))
{
if(passDebitCreditIndicator.equalsIgnoreCase(transType))
{
if(tableCategory[element][0].equalsIgnoreCase("Others-E"))
{
categoryExpense.add("Others");
}
else
{
categoryExpense.add(tableCategory[element][0]);
}
// Toast.makeText(getApplicationContext(), "categoryExpense : " + categoryExpense, Toast.LENGTH_SHORT).show();
i++;
}
}
else
{
if(passDebitCreditIndicator.equalsIgnoreCase(transType))
{
if(tableCategory[element][0].equalsIgnoreCase("Others-I"))
{
categoryIncome.add("Others");
}
else
{
categoryIncome.add(tableCategory[element][0]);
}
// Toast.makeText(getApplicationContext(), "categoryIncome : " + categoryIncome, Toast.LENGTH_SHORT).show();
j++;
}
}
}
if(passDebitCreditIndicator.equalsIgnoreCase("D"))
{
adapterSelect = new ArrayAdapter<String>(this, R.layout.spinner_pb_details,categoryExpense);
// adapterSelect = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categoryExpense);
}
else
{
adapterSelect = new ArrayAdapter<String>(this, R.layout.spinner_pb_details,categoryIncome);
// adapterSelect = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categoryIncome);
}
adapterSelect.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCategory.setAdapter(adapterSelect);
spinnerCategory.setOnItemSelectedListener(this);
checkDBData();
if(dbSubCategory.equalsIgnoreCase("Others-E") || dbSubCategory.equalsIgnoreCase("Others-I"))
{
dbSubCategory = "Others";
}
ArrayAdapter myAdap = (ArrayAdapter) spinnerCategory.getAdapter(); //cast to an ArrayAdapter
int spinnerPosition = myAdap.getPosition(dbSubCategory);
//set the default according to value
spinnerCategory.setSelection(spinnerPosition);
etNotes.setText(dbNotes);
// to disable save button after notes is filled with note from db and item is selected from item listner
}
catch(Exception e)
{
tc.WriteToTransactionLog("Exception: OfflinePBDetails.java showCategoryList():- "+e.toString());
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
// try
// {
spinnerCategory.setSelection(position);
selectedCategory = (String) spinnerCategory.getSelectedItem();
if(passDebitCreditIndicator.equalsIgnoreCase("D"))
{
if(selectedCategory.equalsIgnoreCase("Others"))
{
selectedCategory = "Others-E";
}
// else
// {
// selectedCategory = selectedCategory;
// }
// Toast.makeText(getApplicationContext(), "selectedCategory : " + selectedCategory, Toast.LENGTH_SHORT).show();
}
else
{
if(selectedCategory.equalsIgnoreCase("Others"))
{
selectedCategory = "Others-I";
}
// else
// {
// selectedCategory = (String) spinnerCategory.getSelectedItem();
// }
// Toast.makeText(getApplicationContext(), "selectedCategory : " + selectedCategory, Toast.LENGTH_SHORT).show();
}
btnSave.setEnabled(true);
// switch (position) {
// case 0:
// // Whatever you want to happen when the first item gets selected
// break;
// case 1:
// // Whatever you want to happen when the second item gets selected
// break;
// case 2:
// // Whatever you want to happen when the thrid item gets selected
// break;}
// }
// catch(Exception e)
// {
// Toast.makeText(getApplicationContext(), "Exception onItemSelected : " + e, Toast.LENGTH_SHORT).show();
// }
}
public void checkDBData()
{
try
{
int element;
Cursor rs = dbStatement.getCategory(passTransId);
// int countCategoryRow = rs.getCount();
// int countCategoryColumn = rs.getColumnCount();
rs.moveToFirst();
dbSubCategory = rs.getString(13);
dbNotes = rs.getString(14);
rs.moveToNext();
// String reducedNotes = dbNotes.replace("\n", "").replace("\r", "");
//// String str =dbNotes.substring(0, 3);
// Toast.makeText(getApplicationContext(), "reducedNotes : " + reducedNotes, Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
tc.WriteToTransactionLog("Exception: OfflinePBDetails.java checkDBData():- "+e.toString());
}
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
// TODO Auto-generated method stub
}
public void readConfigFileDetails()
{
try
{
properties_config= new Properties();
FileInputStream fis2 = new FileInputStream(file_Path + "config.properties");
properties_config.load(fis2);
sessionTimeout = Long.parseLong(properties_config.getProperty("session_timeout"));
fis2.close();
}
catch(Exception e)
{
e.printStackTrace();
tc.WriteToTransactionLog("Exception: OfflinePBDetails.java readConfigFileDetails():- "+e.toString());
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ( keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onBackPressed()
{
return;
}
public void onRestart()
{
finish();
super.onRestart();
startActivity(new Intent(this, Welcome.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
finish();
}
private Handler disconnectHandler = new Handler(){
public void handleMessage(Message msg)
{
}
};
private Runnable disconnectCallback = new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), "Session Expired", Toast.LENGTH_LONG).show();
System.out.println("Session Expired");
Intent intent = new Intent(getApplicationContext(),Welcome.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
};
public void resetDisconnectTimer()
{
disconnectHandler.removeCallbacks(disconnectCallback);
disconnectHandler.postDelayed(disconnectCallback, sessionTimeout);
}
public void stopDisconnectTimer()
{
disconnectHandler.removeCallbacks(disconnectCallback);
}
#Override
public void onUserInteraction()
{
resetDisconnectTimer();
}
#Override
public void onResume()
{
super.onResume();
resetDisconnectTimer();
}
#Override
public void onStop()
{
super.onStop();
stopDisconnectTimer();
}
}
Here is my .xml file :
<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="#drawable/bbk_base_all"
android:focusable="true"
android:focusableInTouchMode="true"
android:paddingRight="3dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/txtwelcome" />
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="130dp"
android:gravity="center" >
<TableRow
android:layout_width="wrap_content"
android:layout_height="30dp"
android:background="#drawable/buttonborder"
android:paddingTop="10dp" >
<TextView
android:id="#+id/tv_titleDate"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="25dp"
android:text="Transaction Date"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold|italic" />
<TextView
android:id="#+id/tv_getDate"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingBottom="5dp"
android:paddingLeft="30dp"
android:text="Date"
android:textColor="#FFFFFF"
android:textSize="15sp" />
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/buttonborder"
android:paddingTop="10dp" >
<TextView
android:id="#+id/tv_titleParticulars"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="25dp"
android:text="Particulars"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold|italic" />
<TextView
android:id="#+id/tv_getParticular"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:ems="50"
android:gravity="left"
android:maxLines="4"
android:paddingLeft="30dp"
android:text="Particulars"
android:textColor="#FFFFFF"
android:textSize="15sp" />
</TableRow>
<TableRow
android:layout_width="250dp"
android:layout_height="30dp"
android:background="#drawable/buttonborder"
android:paddingTop="10dp" >
<TextView
android:id="#+id/tv_titleAmount"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="25dp"
android:text="Amount"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold|italic" />
<TextView
android:id="#+id/tv_getAmount"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="30dp"
android:text="Amount"
android:textColor="#FFFFFF"
android:textSize="15sp" />
</TableRow>
<TableRow
android:layout_width="250dp"
android:layout_height="30dp"
android:background="#drawable/buttonborder"
android:paddingTop="10dp" >
<TextView
android:id="#+id/tv_titleBalance"
android:layout_width="150dp"
android:layout_height="25dp"
android:gravity="left"
android:paddingLeft="25dp"
android:text="Balance Amount"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold|italic" />
<TextView
android:id="#+id/tv_getBalance"
android:layout_width="125dp"
android:layout_height="25dp"
android:gravity="left"
android:paddingLeft="30dp"
android:text="Balance"
android:textColor="#FFFFFF"
android:textSize="15sp" />
</TableRow>
<TableRow
android:layout_width="250dp"
android:layout_height="wrap_content"
android:background="#drawable/buttonborder"
android:paddingTop="10dp" >
<TextView
android:id="#+id/tv_titleCategory"
android:layout_width="150dp"
android:layout_height="25dp"
android:gravity="center_vertical"
android:paddingLeft="25dp"
android:text="Select Category"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold|italic" />
<Spinner
android:id="#+id/spn_selectCategory"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:gravity="left"
android:paddingLeft="30dp"
android:textColor="#FFFFFF" />
</TableRow>
<TableRow
android:layout_width="250dp"
android:layout_height="wrap_content"
android:background="#drawable/buttonborder"
android:paddingTop="10dp" >
<TextView
android:id="#+id/tv_titleNotes"
android:layout_width="150dp"
android:layout_height="25dp"
android:gravity="center_vertical"
android:paddingLeft="25dp"
android:text="Notes"
android:textColor="#FFFFFF"
android:textSize="15sp"
android:textStyle="bold|italic" />
<EditText
android:id="#+id/et_getNotes"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:layout_below="#+id/tableLayout1"
android:layout_toLeftOf="#+id/imageView1"
android:hint="Add Your Own Notes"
android:maxLines="3"
android:paddingLeft="30dp"
android:textColor="#FFFFFF" >
</EditText>
</TableRow>
</TableLayout>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:gravity="center"
android:text="Transaction Details"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="24dp"
android:textStyle="bold|italic" />
<Button
android:id="#+id/btnSave"
android:layout_width="110dp"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/tableLayout1"
android:layout_marginLeft="20dp"
android:layout_marginTop="30dp"
android:background="#drawable/normalbuttonborder"
android:text="Save"
android:textSize="16sp"
android:textStyle="bold"
android:enabled="false" />
<Button
android:id="#+id/btnBack"
android:layout_width="110dp"
android:layout_height="30dp"
android:layout_alignBaseline="#+id/btnSave"
android:layout_alignBottom="#+id/btnSave"
android:layout_marginRight="20dp"
android:layout_toLeftOf="#+id/imageView1"
android:background="#drawable/normalbuttonborder"
android:text="Back"
android:textSize="16sp"
android:textStyle="bold" />
</RelativeLayout>
Please help me.
Initially disable that Button after findViewById like this
btnSave = (Button)findViewById(R.id.btnSave);
btnSave.setEnabled(false);
The problem is you have Spinner where u enabling that Button. By default 1st item of Spinner is selected automatically and it is call in onCreate(...) and your Button gets enabled what you can do
Change logic of enabling that Button in Spinner's OnItemSelected(...) check if previously selected value and currently selected value is equal and EditText's value has not been changed then disable that Button otherwise enable that Button. Use boolean flag for this work.
You didnt disable your button before enabling it.
disble your button after declaring it.
btnSave.setEnabled(false);
Then enable it in your textChanged method
Since you want to disable your button use:
btnSave.setEnabled(false);
or try setting:
btnSave.setClickable(false);
along with setEnabled(false)
Alternatively, use below line in your xml:
android:clickable = "false"
android:enabled = "false"
and whenever user is done with note editing (i.e after selecting spinner item ) enable both(enabled & clickable) on btnSave according to your logic i.e use:
btnSave.setClickable(true);
btnSave.setEnabled(true);