Activity crashes when closed via an AlertDialog and re-opened later - java

Everything works just as expected until I exit the activity using the button of the AlertDialog and re-enter the same dialog through the main menu.
Here's how I coded the AlertDialog:
AlertDialog.Builder builder = new AlertDialog.Builder(NewCustomerInfoActivity.this);
if (result.equals("{\"success\":true}")){
builder.setMessage("Yeni müşteri başarıyla kaydedildi.").setTitle("Kayıt Başarılı");
builder.setPositiveButton("Ana ekrana dön", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent backToMainActivityIntent = new Intent(NewCustomerInfoActivity.this, MainActivity.class);
dialog.dismiss();
startActivity(backToMainActivityIntent);
}
});
} else {
builder.setMessage("Yeni müşteri kaydedilemedi.").setTitle("Kayıt Başarısız");
builder.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
}
AlertDialog dialog = builder.create();
dialog.show();
Everything works fine if I remove the code above.
The whole activity if it helps:
public class NewCustomerInfoActivity extends AppCompatActivity {
String jCities;
ArrayList<City> cities;
ArrayList<String> cityStrings;
ArrayList<String> townStrings;
RadioButton personalRadioButton;
RadioButton corporateRadioButton;
Spinner citySpinner;
Spinner townSpinner;
String url;
int isPersComp = 1;
String cityString = "Adana";
int cityNo = 1;
String townString = "Aladağ";
int townNo = 1;
JSONObject json;
String deviceId;
User user;
String result;
Toast toast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_customer_info);
deviceId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
user = (User) getIntent().getSerializableExtra("user");
url = getResources().getString(R.string.service_call_url) + "newCustomer/" + deviceId + "/" + user.getSecureSessionId() + "/";
// Kayıtlı şehir ve ilçeler okunur.
SharedPreferences prefs = getSharedPreferences("cities", MODE_PRIVATE);
jCities = prefs.getString("jCities", null);
if (!(jCities.isEmpty() || jCities == null)){
WebRequest webRequest = new WebRequest();
cities = webRequest.parseCities(jCities);
cityStrings = new ArrayList<String>();
for (City city : cities){
if (!cityStrings.contains(city.getCityName())){
cityStrings.add(city.getCityName());
}
}
}
// Tüzel - Şahıs radio butonlarının kendilerine dokunulması durumunda tepkileri belirlenir.
personalRadioButton = (RadioButton) findViewById(R.id.personalRadioButton);
corporateRadioButton = (RadioButton) findViewById(R.id.corporateRadioButton);
isPersComp = 1;
View.OnClickListener optionOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView taxOrIdNoTitleTextView = (TextView) findViewById(R.id.taxOrIdNoTitleTextView);
if (personalRadioButton.isChecked()){
taxOrIdNoTitleTextView.setText("TC Kimlik No:");
isPersComp = 1;
}
if (corporateRadioButton.isChecked()){
taxOrIdNoTitleTextView.setText("Vergi No:");
isPersComp = 0;
}
}
};
personalRadioButton.setOnClickListener(optionOnClickListener);
corporateRadioButton.setOnClickListener(optionOnClickListener);
// İl seçimi için spinner doldurulur.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, cityStrings);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
final Spinner citySpinner = (Spinner) findViewById(R.id.citySpinner);
citySpinner.setAdapter(adapter);
citySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
cityString = citySpinner.getSelectedItem().toString();
cityNo = 1 + citySpinner.getSelectedItemPosition();
resetTownSpinner(cityNo);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
// Şehir seçimi yapılınca çağırılan ve ilçe spinner'ını seçilen şehre göre dolduran fonksiyon.
public void resetTownSpinner(int cityCode){
townStrings = new ArrayList<String>();
for (City city : cities){
if (city.getCityCode() == cityCode){
townStrings.add(city.getTownName());
}
}
townSpinner = (Spinner) findViewById(R.id.townSpinner);
ArrayAdapter<String> townAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, townStrings);
townSpinner.setAdapter(townAdapter);
townSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
townString = townSpinner.getSelectedItem().toString();
townNo = 1 + townSpinner.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
// Kayıt butonuna basıldığında çağırılan fonksiyon.
public void saveNewCustomer (View view){
// JSON objesi oluşturulur.
json = new JSONObject();
try {
// JSON objesi kullanıcının girdiği değerlere göre doldurulur.
JSONObject jCustomer = new JSONObject();
jCustomer.put("LOGICALREF", 0);
jCustomer.put("CODE", "");
EditText definitionText = (EditText) findViewById(R.id.definitionText);
jCustomer.put("DEFINITION_", definitionText.getText().toString());
jCustomer.put("ISPERSCOMP", isPersComp);
EditText taxOrIdNoText = (EditText) findViewById(R.id.taxOrIdNoText);
if (isPersComp == 1){
jCustomer.put("TAXNR", "");
jCustomer.put("TCKNO", taxOrIdNoText.getText().toString());
} else {
jCustomer.put("TAXNR", taxOrIdNoText.getText().toString());
jCustomer.put("TCKNO", "");
}
EditText taxOfficeText = (EditText) findViewById(R.id.taxOfficeText);
String taxOfficeString = taxOfficeText.getText().toString();
if (taxOfficeString.isEmpty() || taxOfficeString == null){
jCustomer.put("TAXOFFICE", "TCKIMLIK");
} else {
jCustomer.put("TAXOFFICE", taxOfficeString);
}
EditText emailText = (EditText) findViewById(R.id.emailText);
jCustomer.put("EMAILADDR", emailText.getText().toString());
EditText address1Text = (EditText) findViewById(R.id.address1Text);
jCustomer.put("ADDR1", address1Text.getText().toString());
EditText address2Text = (EditText) findViewById(R.id.address2Text);
jCustomer.put("ADDR2", address2Text.getText().toString());
jCustomer.put("CITY", cityString);
jCustomer.put("CITYCODE", cityNo);
jCustomer.put("TOWN", townString);
jCustomer.put("TOWNCODE", townNo);
EditText inChargeText = (EditText) findViewById(R.id.inChargeText);
jCustomer.put("INCHARGE", inChargeText.getText().toString());
EditText nameText = (EditText) findViewById(R.id.nameText);
jCustomer.put("NAME", nameText.getText().toString());
EditText surnameText = (EditText) findViewById(R.id.surnameText);
jCustomer.put("SURNAME", surnameText.getText().toString());
EditText phoneNo1Text = (EditText) findViewById(R.id.phoneNo1Text);
jCustomer.put("TELNRS1", phoneNo1Text.getText().toString());
EditText phoneNo2Text = (EditText) findViewById(R.id.phoneNo2Text);
jCustomer.put("TELNRS2", phoneNo2Text.getText().toString());
json.put("data", jCustomer);
// JSON objesini server'a gönderen Thread başlatılır.
new postJSON().execute();
} catch (Exception e){
e.printStackTrace();
}
}
// JSON objesini server'a gönderen Thread.
private class postJSON extends AsyncTask<Void, Void, Void>{
ProgressDialog progressDialog;
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(NewCustomerInfoActivity.this);
progressDialog.setMessage("Yeni müşteri kaydediliyor. Lütfen bekleyiniz.");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
WebRequest webRequest = new WebRequest();
// JSON objesi string'e dönüştürülür ve linkin sonuna eklenir.
url = url + json.toString();
result = webRequest.getJson(url, true);
return null;
}
protected void onPostExecute(Void requestResult) {
super.onPostExecute(requestResult);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
AlertDialog.Builder builder = new AlertDialog.Builder(NewCustomerInfoActivity.this);
// Server'dan dönen değer kontrol edilir.
if (result.equals("{\"success\":true}")){
builder.setMessage("Yeni müşteri başarıyla kaydedildi.").setTitle("Kayıt Başarılı");
builder.setPositiveButton("Ana ekrana dön", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent backToMainActivityIntent = new Intent(NewCustomerInfoActivity.this, MainActivity.class);
dialog.dismiss();
startActivity(backToMainActivityIntent);
}
});
} else {
builder.setMessage("Yeni müşteri kaydedilemedi.").setTitle("Kayıt Başarısız");
builder.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
}
AlertDialog dialog = builder.create();
dialog.show();
}
}
}
Again, no problems as long as the AlertDialog isn't used. No problem at all unless you use the AlertDialog and then try to get into the Activity once again, then the app stops working.
Logcat:
07-27 13:14:16.113 28618-28618/eof.concrete E/AndroidRuntime: FATAL EXCEPTION: main
Process: eof.concrete, PID: 28618
java.lang.RuntimeException: Unable to start activity ComponentInfo{eof.concrete/eof.concrete.newCustomer.NewCustomerInfoActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String eof.concrete.classes.User.getSecureSessionId()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String eof.concrete.classes.User.getSecureSessionId()' on a null object reference
at eof.concrete.newCustomer.NewCustomerInfoActivity.onCreate(NewCustomerInfoActivity.java:64)
at android.app.Activity.performCreate(Activity.java:6980)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6540) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

The problem is in this line and not in the AlertDialog
user = (User) getIntent().getSerializableExtra("user");
Prior to calling getIntent() you need to be sure that your Activity has been created by an intent.
When your activity is destroyed and re-created by the Android framework, the intent will be null.
If the user object in the intent is fundamental to the Activity functionalities, you could finish it.
Intent intent = getIntent();
if (intent != null){
user = (User) intent.getSerializableExtra("user");
if (user == null){
//handle null user
}
} else {
//here you can call finish() if the user is fundamental to your Activity
//or you must handle a possible nullable `User` object in the following code
finish();
return;
}
And in your AlertDialog, if you want to simply go back to the previous Activity you can replace this code
Intent backToMainActivityIntent = new Intent(NewCustomerInfoActivity.this,
MainActivity.class);
dialog.dismiss();
startActivity(backToMainActivityIntent);
with this
dialog.dismiss();
finish();

Related

Android application, Got error "java.lang.NullPointerException: println needs a message"

i have trouble with my app please i can't fix it. I know the problem at the price = getIntent().getIntExtra("price", -1); line but I don't know how to fix it. i have asked my friend but he sent me here. Please help me this is for my coursework.
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_detail);
init();
sqLiteHelper = new SQLiteHelper(this, "DrinDB.sqlite", null, 1);
sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS CART(ID INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, " +
"quantity INTEGER, price INTEGER)");
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (item < 1) {
Toast.makeText(DrinkDetailActivity.this, "Maaf Pesanan Minimal 1 cup", Toast.LENGTH_SHORT).show();
return;
}
try {
Log.i("TXT PRICE", txtName.getText().toString());
sqLiteHelper.insertData(txtName.getText().toString().trim(),
txtQuantity.getText().toString().trim(),
txtPrice.getText().toString().trim());
Toast.makeText(getApplicationContext(), "Masuk Keranjang!", Toast.LENGTH_SHORT).show();
txtQuantity.setText("0");
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(DrinkDetailActivity.this, CartListActivity.class);
startActivity(intent);
}
});
String name = getIntent().getStringExtra("name");
String type = getIntent().getStringExtra("type");
int image;
image = getIntent().getIntExtra("image", -1);
price = getIntent().getIntExtra("price", -1);
Log.e("SECOND ACTIVITY", name);
TextView nameTV = (TextView) findViewById(R.id.drink_name_text_view);
nameTV.setText(name);
TextView typeTV = (TextView) findViewById(R.id.type);
typeTV.setText(type);
ImageView imageV = (ImageView) findViewById(R.id.drink_image);
imageV.setImageResource(image);
imageV.setVisibility(View.VISIBLE);
TextView priceTV = (TextView) findViewById(R.id.harga_detail_text_view);
priceTV.setText(Integer.toString(price));
sumTextView = (TextView) findViewById(R.id.sum_text_view);
priceTotalTextView =(TextView) findViewById(R.id.harga_total_text_view);
Button incrementBtn = (Button) findViewById(R.id.increment_btn);
incrementBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
increment();
}
});
Button decrementBtn = (Button) findViewById(R.id.decrement_btn);
decrementBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
decrement();
}
});
}
private void init(){
txtName = findViewById(R.id.drink_name_text_view);
txtQuantity = findViewById(R.id.sum_text_view);
txtPrice = findViewById(R.id.harga_total_text_view);
btnAdd = findViewById(R.id.pesan_btn);
btnCart = findViewById(R.id.cart_btn);
}
private void increment(){
item++;
sumTextView.setText(Integer.toString(item));
priceTotalTextView.setText(Integer.toString(sumOfProduct(price)));
}
private void decrement(){
if(item<1){
Toast.makeText(this, "maaf Anda tidak dapat memesan kurang dari 1", Toast.LENGTH_SHORT).show();
return;
}
item =item-1;
sumTextView.setText(Integer.toString(item));
priceTotalTextView.setText(Integer.toString(sumOfProduct(price)));
}
private int sumOfProduct(int price){
return item * price;
}
}
`
and the error message is here [ at com.dicoding.picodiploma.kedaikopi.Models.DrinkDetailActivity.onCreate(DrinkDetailActivity.java:69)]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2760)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2821)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1541)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:181)
at android.app.ActivityThread.main(ActivityThread.java:6295)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:793)
Caused by: java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.e(Log.java:236)
at com.dicoding.picodiploma.kedaikopi.Models.DrinkDetailActivity.onCreate(DrinkDetailActivity.java:69)
at android.app.Activity.performCreate(Activity.java:6834)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1125)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2713)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2821) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1541) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:181) 
at android.app.ActivityThread.main(ActivityThread.java:6295) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:793) 
When using Intent.putExtra, you need to specify a name (first argument) and a value (second argument). The name is always a String and MUST have the package name as prefix.
From the documentation:
The name must include a package prefix, for example the app com.android.contacts would use names like "com.android.contacts.ShowAll".
In your example, when you create the Intent to start an Activity, use intent.putExtra(getPackageName() + ".name", "my name"). And when you want to extract the extra, use String name = getIntent().getStringExtra(getPackageName() + ".name").

Android studio, loading 2 spinners with different data from different MYSQL databases

My app has an itinerary function, the part where you create a new itinerary involves selecting from 2 spinners which drop down to present different options. The data coming from MQsql database and the JSON response is correct for both sets. Currently i have been able to get either one set of the data to load in the correct spinner (being which either just transport info or attraction info but not both), or i have been able to get both sets of data to load but both are displayed in the same 2 spinners. I need them to be separated into there allocated spinners but need help doing this as i dont undertand what im doing wrong.
createItinerary class:
public class CreateItinerary extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
TextView txtDate;
private Spinner spinnerAttraction;
private Spinner spinnerTransport;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
ProgressDialog pDialog;
List<String> lables = new ArrayList<String>();
private ArrayList<ItineraryAdapter>Entities;
private ArrayList<ItineraryAdapter>finalEntities;
LayoutInflater myInflator;
View myView;
DBManager db;
myAdapter adapter;
String NAME;
String LOCATION;
String TIME;
static final int DIALOG_ID = 0;
int hour_x;
int min_x;
TextView TextTime;
String ItineraryName;
private String URL_ATTRACTIONS = "http://10.0.2.2/TravelApp/get_all_spinner.php";
private String URL_TRANSPORT = "http://10.0.2.2/TravelApp/get_all_transport_minor.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_itinerary);
txtDate = (TextView) findViewById(R.id.tvSelectDate);
myInflator = getLayoutInflater();
myView = myInflator.inflate(R.layout.list_create_itinerary, null);
spinnerAttraction = (Spinner) findViewById(R.id.spinnerAttraction);
spinnerTransport = (Spinner) findViewById(R.id.spinnerTransport);
db = new DBManager(this);
categoriesList = new ArrayList<Category>();
Entities = new ArrayList<ItineraryAdapter>();
finalEntities = new ArrayList<ItineraryAdapter>();
// spinner item select listener
spinnerAttraction.setOnItemSelectedListener(this);
spinnerTransport.setOnItemSelectedListener(this);
new GetAttractions().execute();
new GetTransport().execute();
showTimePickerDialog();
Bundle bundle = getIntent().getExtras();
ItineraryName = bundle.getString("Itinerary Name");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_button, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if(id == R.id.go_home){
final TextView alertMessage = new TextView(this);
alertMessage.setText(" All changes will be lost are you sure you want to return back to the home page? ");
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Unsaved changes")
.setView(alertMessage)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(), QavelNav.class);
startActivity(i);
}
})
.setNegativeButton("No", null)
.create();
dialog.show();
}
return super.onOptionsItemSelected(item);
}
public void pickDate(View v) {
DatePickerClass datepicker = new DatePickerClass();
datepicker.setText(v);
datepicker.show(getSupportFragmentManager(), "datepicker");
System.out.println(getDate());
}
public String getDate() {
String date;
date = txtDate.getText().toString();
return date;
}
public void addAttractionToItinerary(View v){
Entities.add(new ItineraryAdapter(NAME,LOCATION,null));
loadAttractions();
System.out.println(ItineraryName);
}
public void loadAttractions(){
adapter = new myAdapter(Entities);
ListView ls = (ListView) findViewById(R.id.listCreateItinerary);
ls.setAdapter(adapter);
for(int i =0; i < finalEntities.size(); i++){
System.out.println(finalEntities.get(i).NAME + " " + finalEntities.get(i).LOCATION + " " + finalEntities.get(i).TIME);
}
}
public void onSave(View v){
ContentValues values = new ContentValues();
for(int i = 0; i <finalEntities.size();i++) {
values.put(DBManager.ColItineraryName,ItineraryName);
values.put(DBManager.ColDate,txtDate.getText().toString());
values.put(DBManager.ColName,finalEntities.get(i).NAME );
values.put(DBManager.ColLocation,finalEntities.get(i).LOCATION);
values.put(DBManager.ColTime,finalEntities.get(i).TIME);
long id = db.Insert("Itinerary",values);
if (id > 0)
Toast.makeText(getApplicationContext(),"Added to Itinerary", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();
}
}
public void showTimePickerDialog(){
TextTime = (TextView) myView.findViewById(R.id.tvCreateItineraryTime);
TextTime.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
showDialog(DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id){
if(id== DIALOG_ID)
return new TimePickerDialog(CreateItinerary.this,KTimePickerListner, hour_x, min_x,false);
return null;
}
protected TimePickerDialog.OnTimeSetListener KTimePickerListner = new TimePickerDialog.OnTimeSetListener(){
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
hour_x = hourOfDay;
min_x = minute;
Toast.makeText(CreateItinerary.this,hour_x+" : " + min_x, Toast.LENGTH_LONG).show();
setTime(hour_x, min_x);
TIME = hour_x + ":" + min_x;
finalEntities.add(new ItineraryAdapter(NAME,LOCATION,TIME));
}
};
public void setTime(int hour, int min){
TextTime.setText(hour_x+":"+min_x);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
NAME = categoriesList.get(position).getName();
LOCATION = categoriesList.get(position).getLocation();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
/**
* Adding spinner data
* */
private void populateSpinner() {
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName() + " - " + categoriesList.get(i).getLocation());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerAttraction.setAdapter(spinnerAdapter);
spinnerTransport.setAdapter(spinnerAdapter);
}
/**
* Async task to get all food categories
* */
private class GetAttractions extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching attraction categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_ATTRACTIONS, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("attraction");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
private class GetTransport extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching transport categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_TRANSPORT, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("transport");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
class myAdapter extends BaseAdapter {
public ArrayList<ItineraryAdapter> listItem;
ItineraryAdapter ac;
public myAdapter(ArrayList<ItineraryAdapter> listItem) {
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ac = listItem.get(position);
TextView Name = (TextView) myView.findViewById(R.id.tvCreateItineraryName);
Name.setText(ac.NAME);
TextView Location = (TextView) myView.findViewById(R.id.tvCreateItineraryLocation);
Location.setText(ac.LOCATION);
/*
Button buttonDelete = (Button)myView.findViewById(R.id.buttonDelete);
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Entities.remove(position);
finalEntities.remove(position);
loadAttractions();
}
});*/
return myView;
}
}
}
Thank you to anyone who can help me with this.

Android IndexOutOfBoundsException Invalid index , size is 0

I'm creating an app that has an add to cart feature. I follow this tutorial and it works fine, but when i try to add the add to cart in the profile of the product instead in listview, i got an error which is IndexOutOfBoundsException Invalid index 51, size is 0
ProductDetails.java
public class ProductDetails extends Fragment {
static ConnectivityManager cm;
AlertDialog dialog2;
AlertDialog.Builder build;
TextView txtproduct,
txtprice,
txtcategorytype,
txtpieces,
txtdescription;
ImageView imgimage;
Button btncart,
btnview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.product_details, container, false);
final Controller ct = (Controller) getActivity().getApplicationContext();
cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);// checking
build = new AlertDialog.Builder(getActivity()); // connectivity
// Create default options which will be used for every
// displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity())
.defaultDisplayImageOptions(defaultOptions)
.build();
if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)// if connection is
// there screen goes
// to next screen
// else shows
// message
.isConnectedOrConnecting()
|| cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.isConnectedOrConnecting()) {
Log.e("cm value",
""
+ cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.isConnectedOrConnecting());
int teaProfileId = getArguments().getInt("teaProfileId");
String teaProfileName = getArguments().getString("teaProfileName");
Float teaProfilePrice = getArguments().getFloat("teaProfilePrice");
String teaProfileImage = getArguments().getString("teaProfileImage");
String teaProfileLabel = getArguments().getString("teaProfileLabel");
int teaProfilePieces = getArguments().getInt("teaProfilePieces");
String teaProfilePiecesType = getArguments().getString("teaProfilePiecesType");
String teaProfileDescription = getArguments().getString("teaProfileDescription");
try {
JSONObject jsonObject1 = new JSONObject(String.valueOf(teaProfileId));
JSONObject jsonObject2 = new JSONObject(teaProfileName);
JSONObject jsonObject3 = new JSONObject(Float.toString(teaProfilePrice));
JSONObject jsonObject4 = new JSONObject(teaProfileImage);
JSONObject jsonObject5 = new JSONObject(teaProfileLabel);
JSONObject jsonObject6 = new JSONObject(String.valueOf(teaProfilePieces));
JSONObject jsonObject7 = new JSONObject(teaProfilePiecesType);
JSONObject jsonObject8 = new JSONObject(teaProfileDescription);
} catch (JSONException e) {
e.printStackTrace();
}
txtproduct = (TextView) rootView.findViewById(R.id.txtproduct);
txtprice = (TextView) rootView.findViewById(R.id.txtprice);
txtcategorytype = (TextView) rootView.findViewById(R.id.txtcategorytype);
txtpieces = (TextView) rootView.findViewById(R.id.txtpieces);
txtdescription = (TextView) rootView.findViewById(R.id.txtdescription);
txtproduct.setText(teaProfileName);
txtprice.setText(("PHP ") + String.format("%.2f", teaProfilePrice));
txtcategorytype.setText(teaProfileLabel);
txtpieces.setText((teaProfilePieces)+" "+(teaProfilePiecesType));
txtdescription.setText(teaProfileDescription.replaceAll("<br />",""));
imgimage = (ImageView)rootView.findViewById(R.id.imgimage);
final ProgressBar progressBar = (ProgressBar)rootView.findViewById(R.id.progressBar);
ImageLoader.getInstance().displayImage(teaProfileImage, imgimage, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
progressBar.setVisibility(View.GONE);
}
});
}
else {
build.setMessage("This application requires Internet connection. Would you connect to internet ?");
build.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
});
build.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
getActivity().finish();
}
});
dialog2 = build.create();
dialog2.show();
}
btncart = (Button) rootView.findViewById(R.id.btncart);
btncart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int teaProfileId = getArguments().getInt("teaProfileId");
String teaProfileName = getArguments().getString("teaProfileName");
Float teaProfilePrice = getArguments().getFloat("teaProfilePrice");
String teaProfileImage = getArguments().getString("teaProfileImage");
String teaProfileLabel = getArguments().getString("teaProfileLabel");
int teaProfilePieces = getArguments().getInt("teaProfilePieces");
String teaProfilePiecesType = getArguments().getString("teaProfilePiecesType");
String teaProfileDescription = getArguments().getString("teaProfileDescription");
Toast.makeText(getActivity(), teaProfileName+" was added to cart.", Toast.LENGTH_LONG).show();
ProductModel productsObject = ct.getProducts(teaProfileId);
ct.getCart().setProducts(productsObject);
}
});
btnview = (Button) rootView.findViewById(R.id.btnview);
btnview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(getActivity(),Screen1.class);
startActivity(in);
}
});
return rootView;
}
}
Controller.java
public class Controller extends Application {
private ArrayList<ProductModel> myproducts = new ArrayList<ProductModel>();
private ModelCart myCart = new ModelCart();
public ProductModel getProducts(int id){
return myproducts.get(id);
}
public void setProducts(ProductModel products){
myproducts.add(products);
}
public ModelCart getCart(){
return myCart;
}
}
ModelCart.java
public class ModelCart {
private ArrayList<ProductModel> cartItems = new ArrayList<ProductModel>();
public ProductModel getProducts(int position){
return cartItems.get(position);
}
public void setProducts(ProductModel Products){
cartItems.add(Products);
}
public int getCartsize(){
return cartItems.size();
}
public boolean CheckProductInCart(ProductModel aproduct){
return cartItems.contains(aproduct);
}
}
This is the error in logcat.
java.lang.IndexOutOfBoundsException: Invalid index 51, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
.Controller.getProducts(Controller.java:19)
.ProductDetails$4.onClick(ProductDetails.java:192)
This is line 19: return myproducts.get(id);
This is line 192: ProductModel productsObject = ct.getProducts(teaProfileId);

Android App crashes when intent a new activity

I need help to find out why it wont go to the next activity (case R.id.Signin_Btn), I've got this issue in another Activity which was perfectly working before this class was made.
I've been through and checked everything and cant find a way to resolve this issue.
public class Login extends ActionBarActivity implements View.OnClickListener {
ArrayList<Driver> DriverArrayList;
DriverAdapter Dadapter;
ArrayList<Vehicle> VehicleArrayList;
VehicleAdapter Vadapter;
ArrayList<Plot> PlotArrayList;
PlotAdapter Padapter;
ImageButton Driver_Btn;
ImageButton Vehicle_Btn;
ImageButton Plot_Btn;
Button Signin_Btn;
private Intent myIntent;
private int DriverID = 0;
private int VehicleID = 0;
private int PlotID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Driver_Btn = (ImageButton) findViewById(R.id.Select_Driver);
Driver_Btn.setOnClickListener(this);
Vehicle_Btn = (ImageButton) findViewById(R.id.Select_Vehicle);
Vehicle_Btn.setOnClickListener(this);
Plot_Btn = (ImageButton) findViewById(R.id.Select_Plot);
Plot_Btn.setOnClickListener(this);
Signin_Btn = (Button) findViewById(R.id.Signin_Btn);
Signin_Btn.setOnClickListener(this);
//ArrayList
DriverArrayList = new ArrayList<Driver>();
VehicleArrayList = new ArrayList<Vehicle>();
PlotArrayList = new ArrayList<Plot>();
new JSONAsyncTask().execute("N/A");
ListView DlistView = (ListView) findViewById(R.id.DriverList);
ListView VlistView = (ListView) findViewById(R.id.VehicleList);
ListView PlistView = (ListView) findViewById(R.id.PlotList);
Dadapter = new DriverAdapter(getApplicationContext(), R.layout.driver_row, DriverArrayList);
Vadapter = new VehicleAdapter(getApplicationContext(), R.layout.vehicle_row, VehicleArrayList);
Padapter = new PlotAdapter(getApplicationContext(), R.layout.plot_row, PlotArrayList);
DlistView.setAdapter(Dadapter);
VlistView.setAdapter(Vadapter);
PlistView.setAdapter(Padapter);
Driver_Btn.setBackgroundColor(Color.GREEN);
DlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
ListView VehicleListView = (ListView) findViewById(R.id.VehicleList);
DriverID = DriverArrayList.get(position).getID();
ResetButtonColours();
arg1.setSelected(true);
Vehicle_Btn.setBackgroundColor(Color.GREEN);
VehicleListView.setVisibility(View.VISIBLE);
//Toast.makeText(getApplicationContext(), DriverArrayList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
VlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
VehicleID = VehicleArrayList.get(position).getID();
ListView PlotListView = (ListView) findViewById(R.id.PlotList);
ResetButtonColours();
Plot_Btn.setBackgroundColor(Color.GREEN);
PlotListView.setVisibility(View.VISIBLE);
//Toast.makeText(getApplicationContext(), DriverArrayList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
PlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
PlotID = PlotArrayList.get(position).getID();
}
});
}
private void ResetButtonColours() {
ListView DriverListView = (ListView) findViewById(R.id.DriverList);
ListView VehicleListView = (ListView) findViewById(R.id.VehicleList);
ListView PlotListView = (ListView) findViewById(R.id.PlotList);
DriverListView.setVisibility(View.GONE);
VehicleListView.setVisibility(View.GONE);
PlotListView.setVisibility(View.GONE);
Driver_Btn.setBackgroundColor(Color.TRANSPARENT);
Vehicle_Btn.setBackgroundColor(Color.TRANSPARENT);
Plot_Btn.setBackgroundColor(Color.TRANSPARENT);
}
#Override
public void onClick(View v) {
ListView DriverListView = (ListView) findViewById(R.id.DriverList);
ListView VehicleListView = (ListView) findViewById(R.id.VehicleList);
ListView PlotListView = (ListView) findViewById(R.id.PlotList);
switch (v.getId()) {
case R.id.Select_Driver:
this.ResetButtonColours();
Driver_Btn.setBackgroundColor(Color.GREEN);
DriverListView.setVisibility(View.VISIBLE);
break;
case R.id.Select_Vehicle:
this.ResetButtonColours();
Vehicle_Btn.setBackgroundColor(Color.GREEN);
VehicleListView.setVisibility(View.VISIBLE);
break;
case R.id.Select_Plot:
this.ResetButtonColours();
Plot_Btn.setBackgroundColor(Color.GREEN);
PlotListView.setVisibility(View.VISIBLE);
break;
case R.id.Signin_Btn:
if (DriverID == 0) {
Toast.makeText(getApplicationContext(), "You haven't selected a Driver!", Toast.LENGTH_LONG).show();
} else if (VehicleID == 0) {
Toast.makeText(getApplicationContext(), "You haven't selected a Vehicle!", Toast.LENGTH_LONG).show();
} else if (PlotID == 0) {
Toast.makeText(getApplicationContext(), "You haven't selected a Plot!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Just a minute!", Toast.LENGTH_LONG).show();
myIntent = new Intent(this, Dashboard.class);
//myIntent.putExtra("key", value); //Optional parameters
startActivity(myIntent);
}
break;
}
}
public class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Login.this);
dialog.setMessage("Loading, Please Wait");
dialog.setTitle("Connecting to Server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet HttpPost = new HttpGet(urls[0]);
HttpClient HttpClient = new DefaultHttpClient();
HttpResponse Response = HttpClient.execute(HttpPost);
int Status = Response.getStatusLine().getStatusCode();
//if (Status == 200) {
HttpEntity Entity = Response.getEntity();
String Data = EntityUtils.toString(Entity);
JSONObject Object = new JSONObject(Data);
JSONArray DriverArray = Object.getJSONArray("drivers");
for (int i = 0; i < DriverArray.length(); i++) {
JSONObject Current = DriverArray.getJSONObject(i);
Driver Driver = new Driver();
Driver.setID(Current.getInt("id"));
Driver.setName(Current.getString("name"));
DriverArrayList.add(Driver);
}
JSONArray VehicleArray = Object.getJSONArray("vehicles");
for (int i = 0; i < VehicleArray.length(); i++) {
JSONObject Current = VehicleArray.getJSONObject(i);
Vehicle Vehicle = new Vehicle();
Vehicle.setID(Current.getInt("id"));
Vehicle.setName(Current.getString("make") + ' ' + Current.getString("model"));
Vehicle.setReg("(" + Current.getString("reg") + ")");
VehicleArrayList.add(Vehicle);
}
JSONArray PlotArray = Object.getJSONArray("plots");
for (int i = 0; i < PlotArray.length(); i++) {
JSONObject Current = PlotArray.getJSONObject(i);
Plot Plot = new Plot();
Plot.setID(Current.getInt("id"));
Plot.setName(Current.getString("name"));
PlotArrayList.add(Plot);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
Dadapter.notifyDataSetChanged();
if (result == false) {
Toast.makeText(getApplicationContext(), "Unable to Fetch Content from Server", Toast.LENGTH_LONG).show();
}
}
}
}
Have you added the new Activity to the manifest file?
Add this
<activity
android:name=".Dashboard"
android:label="Dashboard" />

cannot be resolved or is not a field with some EditTexts

Ok so i have the following situation : I create some Editexts dynamically and i want to add another row of Editexts when one of the EditTexts from the last row is clicked.
I tried doing it the following way :
When the last row of EditTexts is created,i assign each of them an id
et.setId(997);
et.setId(998);
et.setId(999);
I declared each of them ;
public EditText camp1;
public EditText camp2;
public EditText camp3;
camp1 = (EditText) findViewById(997);
camp2 = (EditText) findViewById(998);
camp3 = (EditText) findViewById(999);
camp1.setOnClickListener(this);
camp2.setOnClickListener(this);
camp3.setOnClickListener(this);
And when i try to do this
case R.id.camp1:
inside a switch i get "camp1 cannot be resolved or is not a field"
What am i doing wrong ?
Is there a better way to detect when the last Edittext is clicked and create a new one ?
EDIT:
public class MainActivity extends Activity implements OnClickListener,
TextWatcher {
public Button paginanoua;
// public Button calculeaza;
public Button produsnou;
public EditText camp1;
public EditText camp2;
public EditText camp3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
produsnou();
paginanoua = (Button) findViewById(R.id.paginanoua);
// calculeaza = (Button) findViewById(R.id.calculeaza);
produsnou = (Button) findViewById(R.id.produsnou);
camp1 = (EditText) findViewById(997);
camp2 = (EditText) findViewById(998);
camp3 = (EditText) findViewById(999);
paginanoua.setOnClickListener(this);
// calculeaza.setOnClickListener(this);
produsnou.setOnClickListener(this);
camp1.setOnClickListener(this);
camp2.setOnClickListener(this);
camp3.setOnClickListener(this);
}
public void onClick(View view) {
switch(view.getId())
{
case R.id.paginanoua:
ShowDialog();
case R.id.produsnou:
produsnou();
case R.id.997:///error
produsnou();
}
}
private void ShowDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Pagina noua..");
dialogBuilder.setMessage("Sigur doriti o pagina noua?");
dialogBuilder.setPositiveButton("Da",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),
"Am inceput o lista noua", Toast.LENGTH_SHORT)
.show();
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
dialogBuilder.setNegativeButton("Nu",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),
"Ramanem la lista curenta", Toast.LENGTH_SHORT)
.show();
}
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
}
List<EditText> allpret = new ArrayList<EditText>();
List<EditText> allcant = new ArrayList<EditText>();
List<Float> alltotal = new ArrayList<Float>();
float totaltest = 0;
public void produsnou() {
LinearLayout l1 = (LinearLayout) findViewById(R.id.layout1);
EditText et = new EditText(this);
et.setHint("Produs");
l1.addView(et);
et.addTextChangedListener(this);
et.setId(997);
LinearLayout l2 = (LinearLayout) findViewById(R.id.layout2);
EditText et2 = new EditText(this);
et2.setHint("Cantitate");
et2.setInputType(InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_NUMBER_FLAG_DECIMAL);
et2.setId(998);
allcant.add(et2);
l2.addView(et2);
et2.addTextChangedListener(this);
LinearLayout l3 = (LinearLayout) findViewById(R.id.layout3);
EditText et3 = new EditText(this);
et3.setHint("Pret");
et3.setInputType(InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_NUMBER_FLAG_DECIMAL);
l3.addView(et3);
et3.setId(999);
allpret.add(et3);
et3.addTextChangedListener(this);
}
float temp = 0;
public void calculeaza() {
totaltest = 0;
String[] cant = new String[allcant.size()];
for (int j = 0; j < allcant.size(); j++) {
cant[j] = allcant.get(j).getText().toString();
if (cant[j].matches("")) {
Toast.makeText(this,
"Ati omis cantitatea de pe pozitia " + (j + 1),
Toast.LENGTH_SHORT).show();
cant[j] = Float.toString(0);
}
}
String[] pret = new String[allcant.size()];
for (int k = 0; k < allpret.size(); k++) {
pret[k] = allpret.get(k).getText().toString();
if (pret[k].matches("")) {
Toast.makeText(this,
"Ati omis pretul de pe pozitia " + (k + 1),
Toast.LENGTH_SHORT).show();
pret[k] = Float.toString(0);
}
}
for (int l = 0; l < allpret.size(); l++) {
Float temp = Float.parseFloat(cant[l]) * Float.parseFloat(pret[l]);
alltotal.add(temp);
totaltest = totaltest + temp;
// totaluri[l] = temp ; }
TextView totalf = (TextView) findViewById(R.id.total);
totalf.setText(String.format("Total: %.2f", totaltest));
}
}
// Float[] totaluri = new Float[allcant.size()];
public void reload(View v) {
Intent intent = getIntent();
finish();
startActivity(intent);
calculeaza();
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
calculeaza();
}
}
All you care about is the last editText, right? Just give the last editText an onClickListener that creates another editText. Then give the new editText the onClickListener and remove it from the the previous "last one".
like this:
camp1 = (EditText) findViewById(997);
camp2 = (EditText) findViewById(998);
camp3 = (EditText) findViewById(999);
camp1.setOnClickListener(this);
camp2.setOnClickListener(this);
camp3.setOnClickListener(new myListener());
...
//put this private class in the same activity as the stuff above
private class myListener implements View.OnClickListener {
#Override
public void onClick(View view) {
EditText editText = new EditText(YourActivityName.this);
editText.setOnClickListener(new myListener());
//TODO put it in your viewGroup
//Give the old EditText your standard onClickListener
view.setOnClickListener(YourActivityName.this);
//To change body of implemented methods use File | Settings | File Templates.
}
}
setId() does not add any variables to the R.id class because setId() executes at run-time, but R is generated at compile-time. Since you are creating dynamic views, you need to rethink your onClick() method. You might want to consider using a ListView to help you. You can also set up the three TextViews using a separate XML file, such as row.xml.

Categories