Referencing an input :( - android

i was wondering if anyone could tell me how to use my input/EditText as the value for the max value (line 15, where the .nextInt(1000) is) for this random number generator. I've tried looking up how to do it and asked. Any help is greatly appreciated!
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textOne = (TextView) findViewById(R.id.textView1);
Button pushMe = (Button) findViewById(R.id.button1);
pushMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String randText = "";
// TODO Auto-generated method stub
Random randGen = new Random();
int rando = randGen.nextInt(1000) + 1;
randText = Integer.toString(rando);
textOne.setText(randText);
}
});
}

If you have an EditText in your layout with android:id="#+id/editText1", then this would be one way:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textOne = (TextView) findViewById(R.id.textView1);
final EditText editText = (EditText) findViewById(R.id.editText1);
Button pushMe = (Button) findViewById(R.id.button1);
pushMe.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Random randGen = new Random();
String randText = "";
int max = 0;
String input = editText.getText().toString();
try
{
max = Integer.parseInt(input);
int rando = randGen.nextInt(max) + 1;
randText = Integer.toString(rando);
}
catch (IllegalArgumentException e)
{
randText = "Invalid input";
}
textOne.setText(randText);
}
}
);
}
Please note that catch (IllegalArgumentException e) will catch both the IllegalArgumentException that Random.nextInt() can throw, as well as the NumberFormatException that Integer.parseInt() can throw.

Related

Android Error on passing data from one activity to another acitvity

I am creating an app which calculates the total marks & percentage and shows the result in the next activity called ResultActvity. I am using same ResultActivity for showing result for 1st yr student & 2nd yr student marks, everything works fine when it come to show the result for 1st yr students but when it comes to show the result for second yr students it is only showing total marks but no % is shown. I am a newbie to android development please help me in fixing this. Thank You :).
FIRSTACTIVITY
package com.jntuhcalculator.anu.jntuhcalculator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by anu on 18/9/15.
*/
public class FirstMarks extends Activity {
TextView tv_Subjects1, tv_Internal1, tv_External1;
EditText et_Int_Eng, et_Int_M1, et_Int_MM, et_Int_Phy, et_Int_Chem, et_Int_Cp, et_Int_ElcsLab, et_Int_EpLab, et_Int_ItLab, et_Int_Draw;
EditText et_Ext_Eng, et_Ext_M1, et_Ext_MM, et_Ext_Phy, et_Ext_Chem, et_Ext_Cp, et_Ext_ElcsLab, et_Ext_EpLab, et_Ext_ItLab, et_Ext_Draw;
Button btn_Cal1, btn_Ok1;
int IEng,IM1,IMM,IEPhy,IEChem,ICp,IEDraw,IELCS_Lab,IEP_LAB,IIT_LAB;
int EEng,EM1,EMM,EEPhy,EEChem,ECp,EEDraw,EELCS_Lab,EEP_LAB,EIT_LAB;
int ITotal1,ETotal1,Total1;
float Percentage1;
String f1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.marks_1);
//INITIALISING VIEWS.
//INITIALISING TEXT VIEWS.
tv_Subjects1 = (TextView) findViewById(R.id.tv_Subject1);
tv_Internal1 = (TextView) findViewById(R.id.tv_Internal1);
tv_External1 = (TextView) findViewById(R.id.tv_External1);
//INITIALISING EDIT TEXT.
//INTERNAL
et_Int_Eng = (EditText) findViewById(R.id.et_Int_Eng);
et_Int_M1 = (EditText) findViewById(R.id.et_Int_M1);
et_Int_MM = (EditText) findViewById(R.id.et_Int_MM);
et_Int_Phy = (EditText) findViewById(R.id.et_Int_Phy);
et_Int_Chem = (EditText) findViewById(R.id.et_Int_Chem);
et_Int_Cp = (EditText) findViewById(R.id.et_Int_Cp);
et_Int_ElcsLab = (EditText) findViewById(R.id.et_Int_ElcsLab);
et_Int_EpLab = (EditText) findViewById(R.id.et_Int_EpLab);
et_Int_ItLab = (EditText) findViewById(R.id.et_Int_ItLab);
et_Int_Draw = (EditText) findViewById(R.id.et_Int_Draw);
//EXTERNAL
et_Ext_Eng = (EditText) findViewById(R.id.et_Ext_Eng);
et_Ext_M1 = (EditText) findViewById(R.id.et_Ext_M1);
et_Ext_MM = (EditText) findViewById(R.id.et_Ext_MM);
et_Ext_Phy = (EditText) findViewById(R.id.et_Ext_Phy);
et_Ext_Chem = (EditText) findViewById(R.id.et_Ext_Chem);
et_Ext_Cp = (EditText) findViewById(R.id.et_Ext_Cp);
et_Ext_ElcsLab = (EditText) findViewById(R.id.et_Ext_ElcsLab);
et_Ext_EpLab = (EditText) findViewById(R.id.et_Ext_EpLab);
et_Ext_ItLab = (EditText) findViewById(R.id.et_Ext_ItLab);
et_Ext_Draw = (EditText) findViewById(R.id.et_Ext_Draw);
//INITIALISING BUTTON
btn_Cal1 = (Button) findViewById(R.id.btn_Cal1);
btn_Ok1 = (Button) findViewById(R.id.btn_Ok1);
//WHEN SAVE BUTTON IS CLICKED.
btn_Ok1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//GETTING VALUES FROM EDIT TEXT.
//INTERNALS.
IEng = getIntValue(et_Int_Eng);
IM1 = getIntValue(et_Int_M1);
IMM = getIntValue(et_Int_MM);
IEPhy = getIntValue(et_Int_Phy);
IEChem = getIntValue(et_Int_Chem);
ICp = getIntValue(et_Int_Cp);
IEDraw = getIntValue(et_Int_Draw);
IELCS_Lab = getIntValue(et_Int_ElcsLab);
IEP_LAB = getIntValue(et_Int_EpLab);
//EXTERNALS.
EEng = getIntValue(et_Ext_Eng);
EM1 = getIntValue(et_Ext_M1);
EMM = getIntValue(et_Ext_MM);
EEPhy = getIntValue(et_Ext_Phy);
EEChem = getIntValue(et_Ext_Chem);
ECp = getIntValue(et_Ext_Cp);
EEDraw = getIntValue(et_Ext_Draw);
EELCS_Lab = getIntValue(et_Ext_ElcsLab);
EEP_LAB = getIntValue(et_Ext_EpLab);
EIT_LAB = getIntValue(et_Ext_ItLab);
//CALCUATIONS.
//INTERNAL TOTAL.
ITotal1 = (IEng+IM1+IMM+IEPhy+IEChem+ICp+IEDraw+IELCS_Lab+IEP_LAB+IIT_LAB);
//EXTERNAL TOTAL.
ETotal1 = (EEng+EM1+EMM+EEPhy+EEChem+ECp+EEDraw+EELCS_Lab+EEP_LAB+EIT_LAB);
//TOTAL.
Total1 = (ITotal1+ETotal1);
//PERCENTAGE.
Percentage1 = (float)(Total1/10);
f1 = Float.toString(Percentage1);
//CREATING TOAST.
Toast.makeText(getBaseContext(),"Press Result",Toast.LENGTH_SHORT).show();
}
});
btn_Cal1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(FirstMarks.this,FirstResult.class);
Bundle b = new Bundle();
b.putInt("res1",Total1);
b.putString("per1",f1);
i.putExtras(b);
startActivity(i);
finish();
}
});
}
//SUB-FUNCTION FOR GETTING INTEGER FROM EDITTEXT.
private int getIntValue(EditText et) throws NumberFormatException {
int i =0;
String s;
try {
s = et.getText().toString();
if(s.equals("")){
Toast.makeText(getApplicationContext(),"Invalid Marks",Toast.LENGTH_SHORT).show();
}
i = Integer.parseInt(s);
return i;
} catch (NumberFormatException e) {
Log.e("ERROR:", "NOT A NUMBER");
}
return 0;
}
}
**SECONDACTIVITY**
package com.jntuhcalculator.anu.jntuhcalculator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by anu on 19/9/15.
*/
public class SecondMarks_1 extends Activity {
TextView tv_PS,tv_MFCS,tv_DS,tv_DLD,tv_EDC,tv_BEE,tv_EELab,tv_DSLab;
TextView tv_Subjects21, tv_Internal21, tv_External21;
EditText et_Int_PS, et_Int_MFCS, et_Int_DS, et_Int_DLD, et_Int_EDC, et_Int_BEE, et_Int_EELab, et_Int_DSLab;
EditText et_Ext_PS, et_Ext_MFCS, et_Ext_DS, et_Ext_DLD, et_Ext_EDC, et_Ext_BEE, et_Ext_EELab, et_Ext_DSLab;
Button btn_Cal21, btn_Ok21;
int IPS,IMFCS,IDS,IDLD,IEDC,IBEE,IEE_Lab,IDS_Lab;
int EPS,EMFCS,EDS,EDLD,EEDC,EBEE,EEE_Lab,EDS_Lab;
int ITotal21,ETotal21,Total21;
float Percentage21;
String f21;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondmarks_1);
//INITIALISING VIEWS.
//INITIALISING TEXT VIEWS.
tv_Subjects21 = (TextView) findViewById(R.id.tv_Subject21);
tv_Internal21 = (TextView) findViewById(R.id.tv_Internal21);
tv_External21 = (TextView) findViewById(R.id.tv_External21);
//SUBJECT TEXT VIEWS.
tv_PS = (TextView) findViewById((R.id.tv_PS));
tv_MFCS = (TextView) findViewById((R.id.tv_MFCS));
tv_DS = (TextView) findViewById((R.id.tv_DS));
tv_DLD = (TextView) findViewById((R.id.tv_DLD));
tv_EDC = (TextView) findViewById((R.id.tv_EDC));
tv_BEE = (TextView) findViewById((R.id.tv_BEE));
tv_EELab = (TextView) findViewById((R.id.tv_EE_Lab));
tv_DSLab = (TextView) findViewById((R.id.tv_DS_Lab));
//INITIALISING EDIT TEXT.
//INTERNAL
et_Int_PS = (EditText) findViewById(R.id.et_Int_PS);
et_Int_MFCS = (EditText) findViewById(R.id.et_Int_MFCS);
et_Int_DS = (EditText) findViewById(R.id.et_Int_DS);
et_Int_DLD = (EditText) findViewById(R.id.et_Int_DLD);
et_Int_EDC = (EditText) findViewById(R.id.et_Int_EDC);
et_Int_BEE = (EditText) findViewById(R.id.et_Int_BEE);
et_Int_EELab = (EditText) findViewById(R.id.et_Int_EELab);
et_Int_DSLab = (EditText) findViewById(R.id.et_Int_DSLab);
//EXTERNAL
et_Ext_PS = (EditText) findViewById(R.id.et_Ext_PS);
et_Ext_MFCS = (EditText) findViewById(R.id.et_Ext_MFCS);
et_Ext_DS = (EditText) findViewById(R.id.et_Ext_DS);
et_Ext_DLD = (EditText) findViewById(R.id.et_Ext_DLD);
et_Ext_EDC = (EditText) findViewById(R.id.et_Ext_EDC);
et_Ext_BEE = (EditText) findViewById(R.id.et_Ext_BEE);
et_Ext_EELab = (EditText) findViewById(R.id.et_Ext_EELab);
et_Ext_DSLab = (EditText) findViewById(R.id.et_Ext_DSLab);
//INITIALISING BUTTON
btn_Cal21 = (Button) findViewById(R.id.btn_Cal21);
btn_Ok21 = (Button) findViewById(R.id.btn_Ok21);
//DISPLAYING SUBJECT NAMES WHEN TEXT VIEW IS CLICKED.
tv_PS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
disp(tv_PS, "PS:Probabilty & Statistics");
}
});
tv_MFCS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
disp(tv_MFCS, "MFCS:Mathematical Foundation Of Computer Science");
}
});
tv_DS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {disp(tv_DS, "DS:Data Structures");
}
});
tv_DLD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
disp(tv_DLD, "DLD:Digital Logic Design");
}
});
tv_EDC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
disp(tv_EDC, "EDC:Electronic Devices & Circuits");
}
});
tv_BEE.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { disp(tv_BEE, "BEE:Basic Electrical Engineering");
}
});
tv_EELab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { disp(tv_EELab, "Electrical & Electronics Lab");
}
});
tv_DSLab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {disp(tv_DSLab, "Data Structures Lab");
}
});
//WHEN SAVE BUTTON IS CLICKED.
btn_Ok21.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//GETTING VALUES FROM EDIT TEXT.
//INTERNALS.
IPS = getIntValue(et_Int_PS);
IMFCS = getIntValue(et_Int_MFCS);
IDS = getIntValue(et_Int_DS);
IDLD = getIntValue(et_Int_DLD);
IEDC = getIntValue(et_Int_EDC);
IBEE = getIntValue(et_Int_BEE);
IEE_Lab = getIntValue(et_Int_EELab);
IDS_Lab = getIntValue(et_Int_DSLab);
//EXTERNALS.
EPS = getIntValue(et_Ext_PS);
EMFCS = getIntValue(et_Ext_MFCS);
EDS = getIntValue(et_Ext_DS);
EDLD = getIntValue(et_Ext_DLD);
EEDC = getIntValue(et_Ext_EDC);
EBEE = getIntValue(et_Ext_BEE);
EEE_Lab = getIntValue(et_Ext_EELab);
EDS_Lab = getIntValue(et_Ext_DSLab);
//CALCULATIONS.
//INTERNAL TOTAL.
ITotal21 = (IPS+IMFCS+IDS+IDLD+IEDC+IBEE+IEE_Lab+IDS_Lab);
//EXTERNAL TOTAL.
ETotal21 = (EPS+EMFCS+EDS+EDLD+EEDC+EBEE+EEE_Lab+EDS_Lab);
//TOTAL.
Total21 = (ITotal21+ETotal21);
//PERCENTAGE.
Percentage21 = ((Total21/750)*100);
f21 = Float.toString(Percentage21);
//CREATING TOAST.
Toast.makeText(getBaseContext(),"Press Result",Toast.LENGTH_SHORT).show();
}
});
btn_Cal21.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(SecondMarks_1.this,FirstResult.class);
Bundle b = new Bundle();
b.putInt("res1",Total21);
b.putString("per1",f21);
i.putExtras(b);
startActivity(i);
finish();
}
});
}
//SUB-FUNCTION FOR GETTING INTEGER FROM EDITTEXT.
private int getIntValue(EditText et) throws NumberFormatException {
int i =0;
String s;
try {
s = et.getText().toString();
if(s.equals("")){
Toast.makeText(getApplicationContext(),"Invalid Marks",Toast.LENGTH_SHORT).show();
}
i = Integer.parseInt(s);
return i;
} catch (NumberFormatException e) {
Log.e("ERROR:", "NOT A NUMBER");
}
return 0;
}
private void disp(TextView tv,String s){
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
}
**RESULTACTIVITY**
<pre><code>
package com.jntuhcalculator.anu.jntuhcalculator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by anu on 18/9/15.
*/
public class FirstResult extends Activity {
EditText et_Total1,et_Percentage1;
Button btn_Exit1;
int sres1;
String sper1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_first);
//INITIALISING VIEWS.
et_Total1 = (EditText) findViewById(R.id.et_Total1);
et_Percentage1 = (EditText) findViewById(R.id.et_Percentage1);
btn_Exit1 = (Button) findViewById(R.id.btn_Exit1);
//GETTING DATA FROM PREVIOUS ACTIVITY.
Bundle b = getIntent().getExtras();
sres1 = b.getInt("res1", 0);
sper1 = b.getString("per1");
//Converting Float Into String.
//f = Float.toString(sper1);
//SETTING RESULTS.
et_Total1.setText(sres1+"");
et_Percentage1.setText(sper1+"%");
//WHEN EXIT IS CLICKED.
btn_Exit1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getBaseContext(), YearDetails.class);
i.putExtra("Total",sres1);
startActivity(i);
finish();
System.exit(0);
}
});
}
}
You are properly not able to send values between different activities, i will give you an example, try it.
The syntax is like this
For sending data
String data = getIntent().getExtras().getString("keyName");
Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
intent.putExtra("keyName","value");
For receiving at ActivityTwo
String value= getIntent().getStringExtra("keyName");
Intent intent = getIntent();
Bundle extras = intent.getExtras();
Additional hint:-
So you need to edit in FirstActivity
btn_Cal21.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(SecondMarks_1.this,FirstResult.class);
Bundle b = new Bundle();
b.putInt("res1",Total21);
b.putString("per1",f21);
i.putExtras(b);
startActivity(i);
finish();
}
});
Same for the following activities.
Still Did not get ? Actually in you FirstActivity you have put
Intent i = new Intent(FirstMarks.this,FirstResult.class);
Bundle b = new Bundle();
b.putInt("res1",Total1);
b.putString("per1",f1);
And in your second activity.
Intent i = new Intent(SecondMarks_1.this,FirstResult.class);
Bundle b = new Bundle();
b.putInt("res1",Total21);
b.putString("per1",f21);
i.putExtras(b);
startActivity(i);
You see you have used per1 string in both places, change that, that is probably causing the app not to get values(possibly give some other string).
And in this part, you need to add code for 2nd activity result to be received.
Bundle b = getIntent().getExtras();
sres1 = b.getInt("res1", 0);
sper1 = b.getString("per1");
Hope that helps.

get value from edit text within a loop

I have a question, as I can get all the data that has been inserted into the edit text? the edit text is on a loop, I need a way to get those values ​​and work with them, try using an array but I get errors. could help me? any idea? Help!
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText count = (EditText) findViewById(R.id.count);
final Button generate = (Button) findViewById(R.id.generate);
final LinearLayout container = (LinearLayout) findViewById(R.id.container);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int numberOfControlsToGenerate = 0;
try {
numberOfControlsToGenerate = Integer.parseInt(count.getText().toString().trim());
} catch (NumberFormatException e) {
Log.e(TAG, e.getMessage(), e);
}
if (numberOfControlsToGenerate > 0) {
if (container.getChildCount() > 0) {
container.removeAllViews();
}
for (int counter = 0; counter < numberOfControlsToGenerate; counter++) {
addEditText(container);
}
}
}
});
}
private void addEditText(LinearLayout container) {
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
EditText editTextToAdd = new EditText(this);
editTextToAdd.setLayoutParams(params);
container.addView(editTextToAdd);
}
}
You can create multiple edittext by using array.
public class MainActivity extends Activity{
EditText[] sample_et;
int numberOfControlsToGenerate = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
LinearLayout root_layout = (LinearLayout)findViewById(R.id.root);
sample_et = new EditText[numberOfControlsToGenerate];
//numberOfControlsToGenerate is decleres statically you can get the count from edit text
for(int i = 0; i < count; i++ ){
sample_et[i] = new EditText(this);
root_layout.addView(sample_et[i]);
}
}
}
Add setTag when you create dynamic EditText
add line in addEditText(LinearLayout container) method
private void addEditText(LinearLayout container) {
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
EditText editTextToAdd = new EditText(this);
editTextToAdd.setLayoutParams(params);
editTextToAdd.setTag(editTextToAdd); //Add this Line
container.addView(editTextToAdd);
}
Write code onClick listener on any Button
getvalue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < container.getChildCount(); i++) {
if(container.getChildAt(i) instanceof EditText) {
EditText et = (EditText) container.getChildAt(i).getTag();
if(et != null) {
Log.i("<Tag Name>", et.getText().toString());
}
}
}
}
});

How to multiply two editText's value and accoringly get value in a textView when user enters value in android

I have two EditText and one TextView in my activity,I want to multiple both edittext value thing is that when user entering values to any of edittext ,Accordingly the textView value should be change..My code is as below:
EDITTEXTS:qty,price
TextView:tv_subtotal
main.java
package com.epe.yehki.ui;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.epe.yehki.util.Utils;
import com.example.yehki.R;
public class PlaceOrderActivity extends ListActivity {
Button confirm, shipping;
RelativeLayout rl_adress;
TextView product_name;
TextView tv_adress;
TextView tv_select_adres;
EditText qty;
EditText price;
TextView tv_subtotal;
TextView tv_total;
ArrayAdapter<String> adapter;
String method;
ImageView back;
Double total, subtotal, min_qty, min_agree_prc, max_agree_prc, min_agree_qty, Max_agree_qty, min_qty_unit_name, max_price, min_price;
Intent i = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_place_order);
final ListView lv = getListView();
System.out.println("::::::::::::my custome Id inside ::::::::::place order" + Pref.getValue(PlaceOrderActivity.this, Const.PREF_CUSTOMER_ID, ""));
// FINDINLG IDS...!!
qty = (EditText) findViewById(R.id.et_qty);
price = (EditText) findViewById(R.id.et_price);
rl_adress = (RelativeLayout) findViewById(R.id.btn_adress);
product_name = (TextView) findViewById(R.id.tv_product_name);
tv_adress = (TextView) findViewById(R.id.tv_adress);
tv_select_adres = (TextView) findViewById(R.id.tv_select_adress);
tv_total = (TextView) findViewById(R.id.tv_total);
tv_subtotal = (TextView) findViewById(R.id.tv_subtotal);
back = (ImageView) findViewById(R.id.iv_back);
qty.setCursorVisible(false);
price.setCursorVisible(false);
lv.setVisibility(View.GONE);
String[] shipMethods = new String[] { "Sea Freight", "Air Cargo", "Express" };
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, shipMethods);
shipping = (Button) findViewById(R.id.btn_shiping_method);
shipping.setText("Select shipping Method");
if (Pref.getValue(PlaceOrderActivity.this, Const.FLAG_ADDRESS, "").equals("")) {
max_agree_prc = Double.parseDouble(i.getStringExtra(Const.TAG_PRODUCT_AGREE_MAX_PRICE));
min_agree_prc = Double.parseDouble(i.getStringExtra(Const.TAG_PRODUCT_AGREE_MIN_PRICE));
Max_agree_qty = Double.parseDouble(i.getStringExtra(Const.TAG_PRODUCT_AGREE_MAX_QTY));
min_agree_qty = Double.parseDouble(i.getStringExtra(Const.TAG_PRODUCT_AGREE_MIN_QTY));
min_qty = Double.parseDouble(i.getStringExtra(Const.TAG_PRODUCT_MIN_ORDER_QTY));
min_qty_unit_name = Double.parseDouble(i.getStringExtra(Const.TAG_PRODUCT_MIN_ORDER_QTY_UNIT_NAME));
max_price = Double.parseDouble(i.getStringExtra(Const.TAG_PRODUCT_MAX_PRICE));
min_price = Double.parseDouble(i.getStringExtra(Const.TAG_PRODUCT_MIN_PRICE));
product_name.setText(getIntent().getStringExtra(Const.TAG_PRODUCT_NAME));
}
qty.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
qty.setCursorVisible(true);
}
});
price.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
price.setCursorVisible(true);
}
});
// SELECT ADDRESS CLICK EVENT..!
rl_adress.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
i = new Intent(PlaceOrderActivity.this, AddressListActivity.class);
startActivity(i);
}
});
shipping.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
setListAdapter(adapter);
lv.setVisibility(View.VISIBLE);
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
method = (String) getListAdapter().getItem(position);
shipping.setText(method);
i.putExtra("shipping", method);
lv.setVisibility(View.GONE);
}
});
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
confirm.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Checking for quantity and price...!!!
if (Integer.parseInt(qty.getText().toString()) >= min_qty) {
// check for quantity range
if (Integer.parseInt(price.getText().toString()) >= min_price && Integer.parseInt(price.getText().toString()) <= max_price) {
// check for price range
} else {
Utils.showCustomeAlertValidation(PlaceOrderActivity.this, "Enter Price in Range", "ALERT", "OK");
}
} else {
Utils.showCustomeAlertValidation(PlaceOrderActivity.this, "Enter Quantity in Range", "ALERT", "OK");
}
}
});
}
private void calculate() {
// TODO Auto-generated method stub
double QuantyInt = 1;
double PriceInt = 0;
if (qty != null)
QuantyInt = Double.parseDouble(qty.getText().toString());
if (price != null)
PriceInt = Double.parseDouble(price.getText().toString());
subtotal = (QuantyInt * PriceInt);
String textResult = "Your BMI is " + subtotal;
tv_subtotal.setText(textResult);
tv_total.setText(textResult);
}
}

Getting zero as result (android)

I am getting zero as the output. I couldnt find any errors in it
any help would be great.
full code:
package com.equbez.resistor_decoder;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Second extends Activity {
int i,b1,b2,b3,result,four;
String one,two,three;
String arr[]={"black","brown","red","orange","yellow","green","blue","violet","grey","white"};
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
EditText etone=(EditText) findViewById(R.id.editText1);
one=etone.getText().toString();
for(i=0;i<9;i++) {
if(one.equalsIgnoreCase(arr[i])) {
b1=i;
}
}
EditText ettwo=(EditText) findViewById(R.id.editText2);
two=ettwo.getText().toString();
for(i=0;i<9;i++) {
if(two.equalsIgnoreCase(arr[i])) {
b2=i;
}
}
EditText etthree=(EditText) findViewById(R.id.editText3);
three=etthree.getText().toString();
for(i=0;i<9;i++) {
if(three.equalsIgnoreCase(arr[i])) {
b3=i;
}
}
result=b2+b2+b3;
Button bfour=(Button) findViewById(R.id.button4);
bfour.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View V) {
TextView tv=(TextView) findViewById(R.id.textView4);
tv.setText(""+result);
}
});
}
}
any help would be great.
initially the EditTextView will be empty when the activity is called. so you always get an empty string which you are comparing to the Strings in arr[].
b1, b2, b3 are initialized to default values ie.,, '0' hence result is always '0'
write all the getText code in the bfour.setOnClickListener()
or else implement TextWatcher and use onTextChanged method
use
for(i = 0 ; i< arr.length ;i++)
do something
In your code if you are inputting white its not getting compared
Are you giving any spaces while inputing the string at the end? once check the length of the string that you give as input whether its exact or not
Here i have re-coded with the changes, try out this code,
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Second extends Activity
{
private static int b1,b2,b3,result,four;
private String one,two,three;
private String arr[]={"black","brown","red","orange","yellow","green","blue","violet","grey","white"};
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
EditText etone=(EditText) findViewById(R.id.editText1);
one=etone.getText().toString();
for( int i = 0 ; i < 10; i++ )
{
if(one.trim().equalsIgnoreCase(arr[i].trim()))
{
b1=i;
break;
}
}
EditText ettwo=(EditText) findViewById(R.id.editText2);
two=ettwo.getText().toString();
for( int i = 0 ; i < 10; i++ )
{
if(two.trim().equalsIgnoreCase(arr[i].trim()))
{
b2=i;
break;
}
}
EditText etthree=(EditText) findViewById(R.id.editText3);
three=etthree.getText().toString();
for( int i = 0 ; i < 10; i++ )
{
if(three.trim().equalsIgnoreCase(arr[i].trim()))
{
b3=i;
break;
}
}
result=b2+b2+b3;
Button bfour=(Button) findViewById(R.id.button4);
bfour.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View V)
{
TextView tv=(TextView) findViewById(R.id.textView4);
tv.setText( String.valueOf(result));
}
});
}
}
I got the problem. You have to run your all 3 loops after clicking the button. you have done that on Oncreate(). So you always get 0.
see below:
int i, b1, b2, b3, result, four;
String one, two, three;
String arr[] = { "black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "grey", "white" };
EditText etone, ettwo, etthree;
Button bfour;
TextView tv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
etone = (EditText) findViewById(R.id.editText1);
ettwo = (EditText) findViewById(R.id.editText2);
etthree = (EditText) findViewById(R.id.editText3);
bfour = (Button) findViewById(R.id.button4);
bfour.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View V) {
one = etone.getText().toString();
for (i = 0; i < arr.length; i++) {
if (one.equals(arr[i])) {
b1 = i;
System.out.println("dhrupal one="+b1);
}
}
two = ettwo.getText().toString();
for (i = 0; i < arr.length; i++) {
if (two.equals(arr[i])) {
System.out.println("dhrupal one="+two);
b2 = i;
}
}
three = etthree.getText().toString();
for (i = 0; i < arr.length; i++) {
if (three.equals(arr[i])) {
System.out.println("dhrupal one="+three);
b3 = i;
}
}
result = b1 + b2 + b3;
tv = (TextView) findViewById(R.id.textView4);
tv.setText("result=" + result);
}
});
}

Null pointer exception error : database in android

package com.andrd.gps;
import com.android.util.Utils;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class EditUserDetailActivity extends Activity{
String strTruckType, strTruckPermit, strEmploymentType;
EditText driverNameEdtxt,ageEdtxt,addressEdtxt,liecenceNoEdtxt,contactNoEdtxt,truckNoEdtxt,fromLocationEdtxt,toLocationEdtxt,longitudeEdtxt,latitudeEdtxt;
LinearLayout addUserLayout, updateUserLayout;
Button updateBtn,cancelBtn;
UserDetail user;
TransportData database;
String strTruckNo;
Spinner employmentTypeSpn, truckPermitSpn, truckTypeSpn;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_user);
user=new UserDetail();
database=new TransportData(this);
addUserLayout = (LinearLayout) findViewById(R.id.addUserlayout);
addUserLayout.setVisibility(View.GONE);
driverNameEdtxt = (EditText) findViewById(R.id.driverNameedtx);
ageEdtxt = (EditText) findViewById(R.id.ageEdtxt);
addressEdtxt = (EditText) findViewById(R.id.addressEdtxt);
liecenceNoEdtxt = (EditText) findViewById(R.id.licenceNoEdtxt);
contactNoEdtxt = (EditText) findViewById(R.id.contactNoEdtxt);
truckNoEdtxt = (EditText) findViewById(R.id.truckNoEdtxt);
fromLocationEdtxt = (EditText) findViewById(R.id.fromLocationEdtxt);
toLocationEdtxt = (EditText) findViewById(R.id.toLocationEdtxt);
longitudeEdtxt = (EditText) findViewById(R.id.longitudeEdtxt);
latitudeEdtxt = (EditText) findViewById(R.id.latitudeEdtxt);
Spinner employmentType = (Spinner) findViewById(R.id.DriverSpnr);
employmentType.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,Utils.driver_type));
Spinner truckType = (Spinner)findViewById(R.id.TruckTypespnr);
truckType.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,Utils.truck_type));
Spinner truckPermit = (Spinner) findViewById(R.id.TruckPermitSpnr);
truckPermit.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,Utils.truck_permit));
truckPermit.setSelection(0);
truckPermit.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long arg3) {
strTruckPermit = adapterView.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
getUserData();
updateBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
boolean ok = false;
try {
user.driverName = driverNameEdtxt.getText().toString();
user.age = ageEdtxt.getText().toString();
user.liecenceNo = liecenceNoEdtxt.getText().toString();
user.address = addressEdtxt.getText().toString();
user.contactNo = contactNoEdtxt.getText().toString();
user.driverType = strEmploymentType;
user.truckNo = truckNoEdtxt.getText().toString();
user.truckPermit = strTruckPermit;
user.truckType = strTruckType;
user.fromLocation= fromLocationEdtxt.getText().toString();
user.toLocation = toLocationEdtxt.getText().toString();
user.latitude = latitudeEdtxt.getText().toString();
user.longitude = longitudeEdtxt.getText().toString();
int n = database.updateUser(user);
if(n>0)
{
ok = true;
}
} catch (Exception e) {
ok= false;
}
finally{
if(ok)
{
Toast.makeText(getApplicationContext(), "Successful update data", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "database Error", Toast.LENGTH_LONG).show();
}
}
}
});
cancelBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
finish();
}
});
}
private void getUserData() {
user.truckNo = strTruckNo;
try {
database.getUserDetail(user);
driverNameEdtxt.setText(user.driverName);
ageEdtxt.setText(user.age);
addressEdtxt.setText(user.address);
liecenceNoEdtxt.setText(user.liecenceNo);
contactNoEdtxt.setText(user.contactNo);
employmentTypeSpn.setTag(user.driverType);
truckNoEdtxt.setText(user.truckNo);
truckTypeSpn.setTag(user.truckType);
truckPermitSpn.setTag(user.truckPermit);
fromLocationEdtxt.setText(user.fromLocation);
toLocationEdtxt.setText(user.toLocation);
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "database Error", Toast.LENGTH_LONG).show();
}
}
}
//error in line no 83(error name null pointer exception)
You aren't setting your Spinner instance variables. You are assigning your spinners to local variables instead.
Instead of:
Spinner employmentType = (Spinner) findViewById(R.id.DriverSpnr);
Spinner truckType = (Spinner)findViewById(R.id.TruckTypespnr);
Spinner truckPermit = (Spinner) findViewById(R.id.TruckPermitSpnr);
you need:
employmentTypeSpn = (Spinner) findViewById(R.id.DriverSpnr);
truckTypeSpn = ...
truckPermitSpn = ...
You need to also get your updateBtn somehow:
updateBtn = (Button) findViewById(R.id.update_button);

Categories

Resources