Sending integers via Intent method - android

I have seen a decent amount of methods to add a numerical value to an int integer value using intent(). Mine however is not working so well. Does anyone have any advice? I am sending an integer value, via a button, from a separate activity using theintent() method. This value should add 1 to the activity when the button is pressed. Here is what I have so far:
public class GameEmulator extends Activity{
//Creating two static values to pass strings from SelectPlayer classes
public final static String value = "EMPTY_VALUE";
public final static String value2 = "EMPTY_VALUE2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
//Button created to go back to AddPlayer activity
Button addplayer1 = findViewById(R.id.button9);
addplayer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(GameEmulator.this, AddPlayer.class);
startActivity(i);
}
});
Button viewScores = findViewById(R.id.viewScore);
viewScores.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(GameEmulator.this, MainActivity.class);
startActivity(intent);
}
});
//Button for player one winning
Button winButtonOne = findViewById(R.id.button7);
winButtonOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int scored = 1;
Intent intent = new Intent(GameEmulator.this, Scoreboard.class);
intent.putExtra("MY_KEY", scored);
startActivity(intent);
}
});
TextView textView = findViewById(R.id.name1);
TextView textview2 = findViewById(R.id.name2);
//setting value retrieved from SleectPlayer and Displaying it in textView
Intent intent = getIntent();
String extra = intent.getStringExtra(value);
textView.setText(extra);
//setting value retrieved from SleectPlayer2 and Displaying it in textView2
Intent in = getIntent();
String extra1 = in.getStringExtra(value2);
textview2.setText(extra1);
}
}
public class Scoreboard extends Activity{
public static ArrayAdapter<String> adapter2;
public static ArrayAdapter<String> adapter3;
public static ArrayList<String> list2 = new ArrayList<>();
public static ArrayList<String> list3 = new ArrayList<>();
ListView selectView3;
ListView selectView4;
public static int losses1 = 0;
public static int ties1 = 0;
public static int losses2 = 0;
public static int ties2 = 0;
public final static String value2 = "EMPTY_VALUE2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scoreboard);
selectView3 = findViewById(R.id.selectview3);
selectView3.setVisibility(View.VISIBLE);
selectView4 = findViewById(R.id.selectview4);
selectView4.setVisibility(View.VISIBLE);
//Using adapter for ListView menu
adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list2);
selectView3.setAdapter(adapter2);
//Using intent to retrieve string from AddPlayer Activity
Intent i = getIntent();
int score = getIntent().getIntExtra("MY_KEY", 1);
String data = i.getStringExtra("text_key");
if(data != null){
list2.add("Player 1"+"\n"+"Name: "+data+"\n"+"Wins: "+ score +"\n"+"Losses: "+ losses1+"\n"+"Ties: "+ ties1);
}
if(data != ""){
changeList();
}
adapter3 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list3);
selectView4.setAdapter(adapter3);
Intent intent = getIntent();
String extra= intent.getStringExtra(value2);
if(extra != null) {
list3.add("Player 2" + "\n" + "Name: " + extra + "\n" + "Wins: " + score + "\n" + "Losses: " + losses2 + "\n" + "Ties: " + ties2);
}
if(data != ""){
changeList();
}
}
public void changeList()
{
adapter2.notifyDataSetChanged();
}
}

This line:
String data = i.getStringExtra("text_key");
makes data = null because you did not put in the original intent an extra value with key "text_key"
So this code:
list2.add("Player 1"+"\n"+"Name: "+data+"\n"+"Wins: "+ score +"\n"+"Losses: "+ losses1+"\n"+"Ties: "+ ties1);
is never executed

Related

SQLite database columns stay Null on update method in different activities

I use SQLite database to save data from different activities in my app. in the first activity I use the add method to create a row in the table and the next activities use update method to update the created columns. my previous question which is somehow similar can be found here :
Previous Question
Previously my problem was with not using setId. Now my problem is with the third activity. after calling the update method, the columns stay Null. I tried passing the id from NewProjectActivity to the MainActivity and then to the IntensityActivity but I don't know why the columns don't get updated. Here are the codes :
SQLite Helper:
public class SQLiteHelper extends SQLiteOpenHelper implements ProjectDAO {
public SQLiteHelper(Context context) {
super(context, "my_db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("CREATE TABLE tbl_project_info (id INTEGER PRIMARY KEY," +
"name TEXT," +
"company_name TEXT," +
"address TEXT," +
"length1 TEXT," +
"length2 TEXT," +
"length3 TEXT," +
"length4 TEXT," +
"length5 TEXT," +
"diameter1 Text," +
"diameter2 Text," +
"diameter3 Text," +
"diameter4 Text," +
"diameter5 Text," +
"surface Text," +
"soilResistance Text," +
"intensity Text," +
"allowedIntensity Text," +
"intensityResult Text)");
} catch (SQLiteException e) {
Log.e("SQLITE", "onCreate: " + e.toString());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
#Override
public long addProject(Project project) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", project.getName());
contentValues.put("company_name", project.getCompany_name());
contentValues.put("address", project.getAddress());
contentValues.put("length1", project.getLength1());
contentValues.put("length2", project.getLength2());
contentValues.put("length3", project.getLength3());
contentValues.put("length4", project.getLength4());
contentValues.put("length5", project.getLength5());
contentValues.put("diameter1", project.getDiameter1());
contentValues.put("diameter2", project.getDiameter2());
contentValues.put("diameter3", project.getDiameter3());
contentValues.put("diameter4", project.getDiameter4());
contentValues.put("diameter5", project.getDiameter5());
contentValues.put("surface", project.getSurface());
contentValues.put("soilResistance", project.getSoilResistance());
contentValues.put("intensity", project.getIntensity());
contentValues.put("allowedIntensity", project.getAllowedIntensity());
contentValues.put("intensityResult", project.getIonS());
long result = db.insert("tbl_project_info", null, contentValues);
db.close();
return result;
}
#Override
public int getProjectsCount() {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM tbl_project_info", null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
}
#Override
public boolean updateProject(Project project) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("length1", project.getLength1());
contentValues.put("length2", project.getLength2());
contentValues.put("length3", project.getLength3());
contentValues.put("length4", project.getLength4());
contentValues.put("length5", project.getLength5());
contentValues.put("diameter1", project.getDiameter1());
contentValues.put("diameter2", project.getDiameter2());
contentValues.put("diameter3", project.getDiameter3());
contentValues.put("diameter4", project.getDiameter4());
contentValues.put("diameter5", project.getDiameter5());
contentValues.put("surface", project.getSurface());
contentValues.put("soilResistance", project.getSoilResistance());
contentValues.put("intensity", project.getIntensity());
contentValues.put("allowedIntensity", project.getAllowedIntensity());
contentValues.put("intensityResult", project.getIonS());
db.update("tbl_project_info", contentValues, "id = ?", new String[]{String.valueOf(project.getId())});
db.close();
return true;
}
#Override
public List<Project> getAllProjects() {
List<Project> projects = new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM tbl_project_info", null);
if (cursor.moveToFirst()) {
do {
Project project = new Project();
project.setName(cursor.getString(0));
project.setCompany_name(cursor.getString(1));
project.setAddress(cursor.getString(2));
projects.add(project);
} while (cursor.moveToNext());
}
return projects;
}
}
NewProjectActivity :
public class NewProjectActivity extends AppCompatActivity {
private ProjectDAO projectDAO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_project);
projectDAO = DBInjector.provideProjectDao(this);
setupViews();
}
private void setupViews() {
final EditText projectNameET = findViewById(R.id.et_newProject_projectName);
final EditText companyNameET = findViewById(R.id.et_newProject_companyName);
final EditText addressET = findViewById(R.id.et_newProject_address);
Button saveInfoBTN = findViewById(R.id.btn_newProject_saveInfo);
saveInfoBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long projectID = -1;
if (projectNameET.length() > 0) {
if (companyNameET.length() > 0) {
if (addressET.length() > 0) {
Project project = new Project();
project.setName(projectNameET.getText().toString());
project.setCompany_name(companyNameET.getText().toString());
project.setAddress(addressET.getText().toString());
projectID = projectDAO.addProject(project);
if (projectID > 0){
Toast.makeText(NewProjectActivity.this, "Success", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(NewProjectActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
}else {
companyNameET.setError("company name not entered");
}
}else{
projectNameET.setError("project name not entered");
}
PersonalInfoSharedPrefManager manager = new PersonalInfoSharedPrefManager(NewProjectActivity.this);
manager.setID(projectID);
Intent intent = new Intent(NewProjectActivity.this,MainActivity.class);
intent.putExtra("IE_PROJECTID",projectID);
startActivity(intent);
}
});
}
}
MainActivity :
public class MainActivity extends AppCompatActivity {
private ProjectDAO projectDAO;
private long mProjectID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
projectDAO = DBInjector.provideProjectDao(this);
mProjectID = getIntent().getLongExtra("IE_PROJECTID",0);
final EditText lengthET1 = findViewById(R.id.et_main_length1);
final EditText lengthET2 = findViewById(R.id.et_main_length2);
final EditText lengthET3 = findViewById(R.id.et_main_length3);
final EditText lengthET4 = findViewById(R.id.et_main_length4);
final EditText lengthET5 = findViewById(R.id.et_main_length5);
final EditText diameterET1 = findViewById(R.id.et_main_diameter1);
final EditText diameterET2 = findViewById(R.id.et_main_diameter2);
final EditText diameterET3 = findViewById(R.id.et_main_diameter3);
final EditText diameterET4 = findViewById(R.id.et_main_diameter4);
final EditText diameterET5 = findViewById(R.id.et_main_diameter5);
Button calculateButton = findViewById(R.id.btn_main_calculate);
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
float Le1 = 0;
if (lengthET1.length() > 0) {
String L1 = lengthET1.getText().toString();
Le1 = Float.parseFloat(L1);
}
float Di1 = 0;
if (diameterET1.length() > 0) {
String D1 = diameterET1.getText().toString();
Di1 = Float.parseFloat(D1);
}
float Le2 = 0;
if (lengthET2.length() > 0) {
String L2 = lengthET2.getText().toString();
Le2 = Float.parseFloat(L2);
}
float Di2 = 0;
if (diameterET2.length() > 0) {
String D2 = diameterET2.getText().toString();
Di2 = Float.parseFloat(D2);
}
float Le3 = 0;
if (lengthET3.length() > 0) {
String L3 = lengthET3.getText().toString();
Le3 = Float.parseFloat(L3);
}
float Di3 = 0;
if (diameterET3.length() > 0) {
String D3 = diameterET3.getText().toString();
Di3 = Float.parseFloat(D3);
}
float Le4 = 0;
if (lengthET4.length() > 0) {
String L4 = lengthET4.getText().toString();
Le4 = Float.parseFloat(L4);
}
float Di4 = 0;
if (diameterET4.length() > 0) {
String D4 = diameterET4.getText().toString();
Di4 = Float.parseFloat(D4);
}
float Le5 = 0;
if (lengthET5.length() > 0) {
String L5 = lengthET5.getText().toString();
Le5 = Float.parseFloat(L5);
}
float Di5 = 0;
if (diameterET5.length() > 0) {
String D5 = diameterET5.getText().toString();
Di5 = Float.parseFloat(D5);
}
final float Surface1 = (float) (Le1 * Di1 * Math.PI);
final float Surface2 = (float) (Le2 * Di2 * Math.PI);
final float Surface3 = (float) (Le3 * Di3 * Math.PI);
final float Surface4 = (float) (Le4 * Di4 * Math.PI);
final float Surface5 = (float) (Le5 * Di5 * Math.PI);
final float Surface = Surface1 + Surface2 + Surface3 + Surface4 + Surface5;
long projectID = -1;
Intent intent = new Intent(MainActivity.this, IntensityActivity.class);
if (Surface == 0) {
Toast.makeText(MainActivity.this, "No numbers are entered", Toast.LENGTH_SHORT).show();
} else {
intent.putExtra("Result", Surface);
intent.putExtra("IE_PROJECTID",projectID);
startActivity(intent);
}
PersonalInfoSharedPrefManager manager = new PersonalInfoSharedPrefManager(MainActivity.this);
manager.setSuface(Surface);
Project project = new Project();
project.setId(mProjectID);
project.setLength1(lengthET1.getText().toString());
project.setDiameter1(diameterET1.getText().toString());
project.setLength2(lengthET2.getText().toString());
project.setDiameter2(diameterET2.getText().toString());
project.setLength3(lengthET3.getText().toString());
project.setDiameter3(diameterET3.getText().toString());
project.setLength4(lengthET4.getText().toString());
project.setDiameter4(diameterET4.getText().toString());
project.setLength5(lengthET5.getText().toString());
project.setDiameter5(diameterET5.getText().toString());
project.setSurface(String.valueOf(Surface));
projectDAO.updateProject(project);
}
});
}
}
IntensityActivity :
public class IntensityActivity extends AppCompatActivity {
private ProjectDAO projectDAO;
private long mProjectID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intensity);
projectDAO = DBInjector.provideProjectDao(this);
mProjectID = getIntent().getLongExtra("IE_PROJECTID",0);
final float Result = getIntent().getFloatExtra("Result",0);
final Button resistanceBTN1 = findViewById(R.id.btn_intensity_R1);
final Button resistanceBTN2 = findViewById(R.id.btn_intensity_R2);
final Button resistanceBTN3 = findViewById(R.id.btn_intensity_R3);
final Button resistanceBTN4 = findViewById(R.id.btn_intensity_R4);
final Button resistanceBTN5 = findViewById(R.id.btn_intensity_R5);
final View RL = findViewById(R.id.rl_intensity_allowedIntensity);
final TextView allowedResistance = findViewById(R.id.tv_intensity_allowedIntensityNumber);
final TextView surfaceNumber = findViewById(R.id.tv_intensity_surfaceNumber);
final EditText intensityNumber = findViewById(R.id.et_intensity_intensityNumber);
Button calculateButton = findViewById(R.id.btn_intensity_calculate);
final Button goToVoltageButton = findViewById(R.id.btn_intensity_goToVoltage);
final TextView formulaResultNumber = findViewById(R.id.tv_intensity_resultNumber);
String Sur = Float.toString(Result);
surfaceNumber.setText(Sur);
final double R1 = Result*0.250;
final double R2 = Result*0.125;
final double R3 = Result*0.050;
final double R4 = Result*0.025;
final double R5 = Result*0.010;
final String Re1 = Double.toString(R1);
final String Re2 = Double.toString(R2);
final String Re3 = Double.toString(R3);
final String Re4 = Double.toString(R4);
final String Re5 = Double.toString(R5);
resistanceBTN1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re1);
}
});
resistanceBTN2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re2);
}
});
resistanceBTN3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re3);
}
});
resistanceBTN4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re4);
}
});
resistanceBTN5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re5);
}
});
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String I = intensityNumber.getText().toString();
float In = Float.parseFloat(I);
float R = In/Result;
String Res = String.valueOf(R);
formulaResultNumber.setText(Res);
goToVoltageButton.setVisibility(View.VISIBLE);
PersonalInfoSharedPrefManager manager = new PersonalInfoSharedPrefManager(IntensityActivity.this);
manager.setIntensity(In);
}
});
goToVoltageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(IntensityActivity.this,SimpleVoltage.class);
startActivity(intent);
Project project = new Project();
project.setId(mProjectID);
project.setAllowedIntensity(String.valueOf(allowedResistance));
project.setIntensity(intensityNumber.getText().toString());
projectDAO.updateProject(project);
}
});
}
}
From MainActivity to IntensityActivity, What I found is that you are always passing -1 in Project ID
final float Surface = Surface1 + Surface2 + Surface3 + Surface4 + Surface5;
long projectID = -1;
Intent intent = new Intent(MainActivity.this, IntensityActivity.class);
if (Surface == 0) {
Toast.makeText(MainActivity.this, "No numbers are entered", Toast.LENGTH_SHORT).show();
} else {
intent.putExtra("Result", Surface);
intent.putExtra("IE_PROJECTID",projectID);
startActivity(intent);
}
Instead you can pass the same ID you have got on this activity from Intent
Just update your code in MainActivity as below and pass mProjectID.
final float Surface = Surface1 + Surface2 + Surface3 + Surface4 + Surface5;
long projectID = -1;
Intent intent = new Intent(MainActivity.this, IntensityActivity.class);
if (Surface == 0) {
Toast.makeText(MainActivity.this, "No numbers are entered", Toast.LENGTH_SHORT).show();
} else {
intent.putExtra("Result", Surface);
intent.putExtra("IE_PROJECTID",mProjectID);
startActivity(intent);
}
Hope this will help.
try this way in your update method,
db.update("tbl_project_info", contentValues, "id="+String.valueOf(project.getId()), null);
Also you need to change following line into MainActivity.java
long projectID = -1;
to
long projectID = mProjectID;

Android studio. Parceling data to a specific object in an array list

package com.example.hussain.assignment4task1;
import android.os.Parcel;
import android.os.Parcelable;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class Image implements Parcelable
{
private String imageName;
private String date;
public ArrayList<Image> images;
public Image(String imageName, String date, ArrayList<Image> images)
{
update(imageName, date, images);
}
public void update(String imageName, String date, ArrayList<Image> images)
{
this.imageName = imageName;
this.date = date;
this.images = images;
}
public String toString()
{
String str = "Image Name: "+ imageName;
str += "\nDate: " + date;
return str;
}
/** The following block of code parcels / unparcels data for distribution between activities */
/** Describe the contents in the parcel --
* interface forces implementation */
public int describeContents()
{
return 0;
}
public void writeToParcel(Parcel out, int flags)
{
out.writeString(imageName);
out.writeString(date);
out.writeList(images);
}
public static final Parcelable.Creator<Image> CREATOR =
new Parcelable.Creator<Image>()
{
public Image createFromParcel(Parcel in)
{
return new Image(in);
}
public Image[] newArray(int size)
{
return new Image[size];
}
};
/** Private constructor called internally only */
private Image(Parcel in)
{
imageName = in.readString();
date = in.readString();
}
}
This is my activity where i insert the image details to be passed to the image in the other activity.
public void onBackPressed()
{
Log.i("IMAGE DETAILS", "Back Button Pressed");
storeImageDetails(); // to cover half filled forms
Intent resultIntent = new Intent(this, MainActivity.class);
// need an array list even if we put a single object only
ArrayList<Image> dataList = new ArrayList<Image>(4);
dataList.add(image);
resultIntent.putParcelableArrayListExtra("IMAGE_DATA", dataList);
setResult(RESULT_OK, resultIntent);
ImageDetailsActivity.super.onBackPressed(); // do not forget
}
/** This method will store all information entered */
private void storeImageDetails()
{
EditText imageNameText = (EditText) findViewById(R.id.imageNameText);
EditText dateText = (EditText) findViewById(R.id.dateText);
String imageName = imageNameText.getText().toString();
String date = dateText.getText().toString();
ArrayList<Image> dataList = new ArrayList<Image>();
if (image == null)
image = new Image(imageName, date, dataList);
else
image.update(imageName, date, dataList);
Log.i("IMAGE DETAILS CHANGED", image.toString());
}
I have 4 images on my main activity. clicking on one of them opens up a form where you can enter their details and on back button pressed they sow up below the image themselves only the image name and date. but this shows up the same for all the images. i wanna know how to make it so that only the image that i clicked on gets the details passed to it and not the other images. so separateness passing the data to the individual images is what i wanna figure out.
I think the public ArrayList<Image> images field shouldn't be a part of the Image class, instead it should be a field in your Main activity.
Try something like this:
public class MainActivity extends Activity {
public ArrayList<Image> images;
// show images list via adapter or something, and put an OnClickListener on each
private void onImageClicked(int index) {
Image image = images.get(index);
Intent intent = new Intent(this, ImageDetailsActivity.class);
intent.putExtra("IMAGE", image);
intent.putExtra("INDEX", index);
startActivityForResult(intent, 12345);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 12345 && resultCode == RESULT_OK) {
int index = data.getIntExtra("INDEX", -1);
String name = data.getStringExtra("NAME");
String date = data.getStringExtra("DATE");
Image image = images.get(index);
image.update(name, date);
}
}
}
public class ImageDetailsActivity extends Activity {
public void onBackPressed() {
EditText imageNameText = (EditText) findViewById(R.id.imageNameText);
EditText dateText = (EditText) findViewById(R.id.dateText);
String imageName = imageNameText.getText().toString();
String date = dateText.getText().toString();
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.putExtra("INDEX", getIntent().getIntExtra("INDEX", -1)); // return the same index we got from Main
resultIntent.putExtra("NAME", imageName);
resultIntent.putExtra("DATE", date);
setResult(RESULT_OK, resultIntent);
super.onBackPressed();
}
}

Getting Same Values For Two Different Keys in Shared Preferences

i am creating an app in which different payments modes are there so for card payments and cheque payments i have created two different activities in which i am getting details from user and save the data into shared Preferences and then app returns back to the activities where other details are also there and then user can save the data on a button click.This data gets saved into Sqlite Database.
My problem is when i am selecting card payment its getting stored properly but the same value also getting stored at cheque No aswell into the sqlite database.Inshort the value of card payment is getting copied into cheque no column by default.
below is my code for Card payment Activity :
public class CardNo extends Activity {
String bankname;
String cardno;
int chq;
TextView textView1, textView2;
EditText editText1, editText2;
Button btn;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.creditdebit);
textView1 = (TextView) findViewById(R.id.tv1);
textView2 = (TextView) findViewById(R.id.tv2);
editText1 = (EditText) findViewById(R.id.bankname);
editText2 = (EditText) findViewById(R.id.cardno);
btn = (Button) findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData();
Intent card = new Intent(CardNo.this, EnterAmount.class);
startActivity(card);
finish();
}
});
}
private void saveData() {
bankname = editText1.getText().toString();
cardno = editText2.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Bank Name", bankname);
editor.putString("Card No", cardno);
editor.apply();
}
}
Now code for cheque payment Activity :
public class Cheque extends Activity {
String bankname1;
String chequeno;
int chq;
TextView textView1,textView2;
EditText editText1,editText2;
Button btn;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cheque);
textView1=(TextView)findViewById(R.id.tv11);
textView2=(TextView)findViewById(R.id.tv12);
editText1=(EditText)findViewById(R.id.bankname1);
editText2=(EditText)findViewById(R.id.chequeno);
btn=(Button)findViewById(R.id.btn11);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData();
Intent cheque = new Intent(Cheque.this, EnterAmount.class);
startActivity(cheque);
finish();
}
});
}
private void saveData() {
bankname1 = editText1.getText().toString();
chequeno = editText2.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Bank Name", bankname1);
editor.putString("Cheque No", chequeno);
editor.apply();
}
}
Now the code of the activity where i am retrieving the data from shared preferences and storing the data into sqlite.
public class EnterAmount extends Activity implements OnClickListener {
Intent intent;
Button save;
Spinner spinnerPayment, spinnerCategory;
EditText etamt, etbdgt, et_get_other;
String date, sBdgt, budget, bankname, cardno, chequeno;
String sAmt;
String spinnerItemSelectedPayment;
String spinnerItemSelectedCategory;
// String category;
int amt;
int date2;
TextView caategories, tv_cat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.enteramount);
save = (Button) findViewById(R.id.bsaveDb);
caategories = (TextView) findViewById(R.id.tvCaategories);
etamt = (EditText) findViewById(R.id.etAmount);
etbdgt = (EditText) findViewById(R.id.etbudget);
spinnerCategory = (Spinner) findViewById(R.id.spinnerCategory);
spinnerPayment = (Spinner) findViewById(R.id.payment_spinner);
List<String> sCategory = new ArrayList<String>();
String[] categories = {"Food", "Bills",
"Travel", "Entertainment", "Office Stationary",
"Medical Expenses", "Fuel"
};
sCategory.add("Food");
sCategory.add("Office Stationary");
sCategory.add("Bills");
sCategory.add("Travel");
sCategory.add("Entertainment");
sCategory.add("Medical Expenses");
sCategory.add("Fuel");
ArrayAdapter<String> sc = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, sCategory);
spinnerCategory.setAdapter(sc);
List<String> l = new ArrayList<String>();
String[] paymentMode = {"Cash", "Credit/Debit Card", "Cheque", "NetBanking"};
l.add("Cash");
l.add("Credit/Debit Card");
l.add("Cheque");
l.add("NetBanking");
ArrayAdapter<String> sp = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, l);
spinnerPayment.setAdapter(sp);
save.setOnClickListener(this);
spinnerCategory.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View selectedItemView, int pos, long id) {
spinnerItemSelectedCategory = parent.getItemAtPosition(pos)
.toString();
}
public void onNothingSelected(AdapterView<?> parentView) {
spinnerItemSelectedCategory = "Food";
}
});
spinnerPayment.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View selectedItemView, int pos, long id) {
spinnerItemSelectedPayment = parent.getItemAtPosition(pos).toString();
if (spinnerItemSelectedPayment.equals("Cheque")) {
Intent cheque = new Intent(EnterAmount.this, Cheque.class);
cheque.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(cheque);
} else if (spinnerItemSelectedPayment.equals("Credit/Debit Card")) {
Intent card = new Intent(EnterAmount.this, CardNo.class);
card.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(card);
}
}
public void onNothingSelected(AdapterView<?> parentView) {
spinnerItemSelectedPayment = "Cash";
}
});
final Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy-HH:mm:ss ");
date = sdf.format(c.getTime());
int yy = c.get(Calendar.YEAR);
int mm = c.get(Calendar.MONTH) + 1;
int dd = c.get(Calendar.DAY_OF_MONTH);
String s = yy + "" + (mm < 10 ? ("0" + mm) : (mm)) + ""
+ (dd < 10 ? ("0" + dd) : (dd));
Log.e("datechange", s);
date2 = Integer.parseInt(s);
Log.e("integer2", "hello" + date2);
}
#Override
public void onBackPressed () {
super.onBackPressed();
finish();
}
private void vibrate(int ms) {
((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).vibrate(ms);
}
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
budget = sharedPreferences.getString("Budget", " ");
getSharedPreferences(mypreference,Context.MODE_PRIVATE);
bankname = sharedPreferences.getString("Bank Name", "Not Applicable");
cardno = sharedPreferences.getString("Card No", "Not Applicable");
chequeno = sharedPreferences.getString("Cheque No", "Not Applicable");
}
private void removeSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("Bank Name");
editor.remove("Cheque No");
editor.remove("Card No");
editor.apply();
}
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bsaveDb: {
savePreferences("Budget", etbdgt.getText().toString());
loadSavedPreferences();
sAmt = etamt.getText().toString();
Log.e("category", "Hello" + sAmt);
try {
amt = Integer.parseInt(sAmt);
Log.e("amt is", "" + amt);
} catch (Exception e) {
}
DbClass dc = new DbClass(this);
dc.open();
if (amt == 0) {
Toast.makeText(getApplicationContext(),
"Please insert the amount", Toast.LENGTH_SHORT).show();
} else {
dc.categoryDetailsInsert(amt, spinnerItemSelectedCategory, date, spinnerItemSelectedPayment, date2, bankname, cardno, chequeno);
dc.close();
Toast.makeText(getApplicationContext(), "Saved successfully",
Toast.LENGTH_LONG).show();
amt = 0;
etamt.setText("");
etbdgt.setText(budget);
removeSavedPreferences();
}
break;
}
}
}
}
i am attching a screenshot of sqlite database and you can see bank name is getting stored properly but cardno and cheque no is always same with respect to payment.Screenshot Of Database
Attach your keys to the context tag to prevent override of values.
like:
String TAG = "ContextName or ActivityName";
then on saving do:
pref.put(TAG+key, "value");
Actually above code is Fine the Problem was in the code where i was retrieving code from the database i inserted the same index number for the two different columns. so i was getting same values for cheque no and debit card number.

App isn't responding. Using ListActivity

When I try to launch application it closes before even shows something. I use ListActivity and I was using this site to write the code : Android ListActivity Example. I think everything is good in code. What can it be then?
public class MainActivity extends ListActivity {
static int kiekis, n = 10000, s = 20000, f = 30000, p1 = 40000, p2 = 50000, pozicija, i = 1;
ArrayList<String> list;
static String vardas;
static String numeris;
static String skype;
static String facebook;
static String papildoma1;
static String papildoma2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sprefs = getSharedPreferences("Prefs", MODE_PRIVATE);
list = new ArrayList<String>();
for (i = 1; i <= kiekis; i++) {
vardas = sprefs.getString(String.valueOf(i), "");
list.add(vardas);
}
setListAdapter(new ArrayAdapter<String>(this,
R.layout.list_view, R.id.vardas, list));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//String item = (String) getListAdapter().getItem(position);
Intent intent = new Intent(MainActivity.this, Detail.class);
pozicija = position;
SharedPreferences sprefs = getPreferences(MODE_PRIVATE);
numeris = sprefs.getString(String.valueOf(n + position), "");
skype = sprefs.getString(String.valueOf(s + position), "");
facebook = sprefs.getString(String.valueOf(f + position), "");
papildoma1 = sprefs.getString(String.valueOf(p1 + position), "");
papildoma2 = sprefs.getString(String.valueOf(p2 + position), "");
startActivity(intent);
finish();
}
}
Try putting break point on the First line and run in debug mode. Then you can see where it breaks

onCreate() method with if-else condition

I am calling an activity namely LoginActivity.java in which i am getting values using Intent, storing data to SQLite, fetching data from SQLite and given a small condition, condition looks like this:
if(txtEvent.getText().toString().equals("") && txtOperative.getText().toString().equals(""))
{
Intent intentCall = new Intent(LoginActivity.this, LicenseListActivity.class);
startActivity(intentCall);
}
Now, how App works:-
Splash Screen > LoginActivity (if txtEvent and txtOperative equals to null) then calling > LicenseListActivity > GetEventsActivity > GetOperativesActivity (passing some values mainly EVENT & OPERATIVE name) to LoginActivity (also storing to database - checked using SQLite DB Viewer)
So issue is, instead of calling LoginActivity.java its calling LicenseListActivity.java again, after GetOperativesActivity.java ?
GetOperativesActivity.java:-
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
firstName = contactList.get(position).get(TAG_NAME);
Intent intent = new Intent(GetOperativesActivity.this, LoginActivity.class);
intent.putExtra("name", name);
intent.putExtra("deviceID", deviceID);
intent.putExtra("emailID", emailID);
intent.putExtra("firstName", firstName);
startActivity(intent);
}
});
LoginActivity.java:-
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_login);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnCamera = (Button) findViewById(R.id.btnCamera);
btnGallery = (Button) findViewById(R.id.btnGallery);
txtDeviceID = (TextView) findViewById(R.id.txtDeviceID);
txtEmailID = (TextView) findViewById(R.id.txtEmailID);
txtEvent = (TextView) findViewById(R.id.txtEvent);
txtOperative = (TextView) findViewById(R.id.txtOperative);
txtEventOperator = (TextView) findViewById(R.id.txtEventOperator);
Intent intent = getIntent();
deviceID = intent.getStringExtra("deviceID");
emailID = intent.getStringExtra("emailID");
event = intent.getStringExtra("name");
operative = intent.getStringExtra("firstName");
txtDeviceID.setText(deviceID);
txtEmailID.setText(emailID);
txtEvent.setText(event);
txtOperative.setText(operative);
txtEventOperator.setText(event + " " + operative);
strEvent = txtEvent.getText().toString();
strOperative = txtOperative.getText().toString();
// Dialog
final AlertDialog.Builder adb = new AlertDialog.Builder(this);
AlertDialog ad = adb.create();
// new Class DB
final myDBClass myDb = new myDBClass(this);
// Save Data
long saveStatus = myDb.InsertData(
txtDeviceID.getText().toString(),
txtEmailID.getText().toString(),
txtEvent.getText().toString(),
txtOperative.getText().toString(),
txtEventOperator.getText().toString()
);
if(saveStatus <= 0)
{
ad.setMessage("Error!! ");
ad.show();
return;
}
// Show Data
String arrData[] = myDb.SelectData();
if(arrData != null)
{
txtDeviceID.setText(arrData[1]);
txtEmailID.setText(arrData[2]);
txtEvent.setText(arrData[3]);
txtOperative.setText(arrData[4]);
txtEventOperator.setText(arrData[5]);
}
if(txtEvent.getText().toString().equals("") && txtOperative.getText().toString().equals(""))
{
Intent intentCall = new Intent(LoginActivity.this, LicenseListActivity.class);
startActivity(intentCall);
}
}
If you have any question in your mind, please let me know ...
public class LoginActivity extends Activity{
static int counter = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_login);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnCamera = (Button) findViewById(R.id.btnCamera);
btnGallery = (Button) findViewById(R.id.btnGallery);
txtDeviceID = (TextView) findViewById(R.id.txtDeviceID);
txtEmailID = (TextView) findViewById(R.id.txtEmailID);
txtEvent = (TextView) findViewById(R.id.txtEvent);
txtOperative = (TextView) findViewById(R.id.txtOperative);
txtEventOperator = (TextView) findViewById(R.id.txtEventOperator);
Intent intent = getIntent();
deviceID = intent.getStringExtra("deviceID");
emailID = intent.getStringExtra("emailID");
event = intent.getStringExtra("name");
operative = intent.getStringExtra("firstName");
txtDeviceID.setText(deviceID);
txtEmailID.setText(emailID);
txtEvent.setText(event);
txtOperative.setText(operative);
txtEventOperator.setText(event + " " + operative);
strEvent = txtEvent.getText().toString();
strOperative = txtOperative.getText().toString();
// Dialog
final AlertDialog.Builder adb = new AlertDialog.Builder(this);
AlertDialog ad = adb.create();
// new Class DB
final myDBClass myDb = new myDBClass(this);
// Save Data
long saveStatus = myDb.InsertData(
txtDeviceID.getText().toString(),
txtEmailID.getText().toString(),
txtEvent.getText().toString(),
txtOperative.getText().toString(),
txtEventOperator.getText().toString()
);
if(saveStatus <= 0)
{
ad.setMessage("Error!! ");
ad.show();
return;
}
// Show Data
String arrData[] = myDb.SelectData();
if(arrData != null)
{
txtDeviceID.setText(arrData[1]);
txtEmailID.setText(arrData[2]);
txtEvent.setText(arrData[3]);
txtOperative.setText(arrData[4]);
txtEventOperator.setText(arrData[5]);
}
if(counter==0&&txtEvent.getText().toString().equals("") && txtOperative.getText().toString().equals(""))
{
counter++;
Intent intentCall = new Intent(LoginActivity.this, LicenseListActivity.class);
startActivity(intentCall);
}
}//end onCreate
}//end class

Categories

Resources