How to correctly use the spinner - java

I have some items (strings) in my spinner and when I select one of these items, I want back an associated value, for example:
If I select SAE 1020, it returns me 250.0
If I select E-155, it returns me 300.0
The value is suposed to be shown in a EditText, but the only value I see is 250.0.
After all, this value should be sent to the next Activity (I also do not know if I'm doing the transfer correctly).
What is happening? What can I do?
Code:
package com.mateus.ligacoestubulares;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class Dados extends AppCompatActivity {
String [] AçoMontante = {"SAE 1020", "E-155"};
String [] AçoBanzo = {"SAE 1020", "E-155"};
String [] EspessuraT1 = {"0,75 mm", "0,90 mm", "0,95 mm"};
String [] EspessuraTo = {"0,75 mm", "0,90 mm", "0,95 mm"};
EditText campoFy1;
EditText campoFyo;
EditText campoT1;
EditText campoTo;
EditText normalM;
EditText normalB;
EditText momentoB;
EditText teta;
Button next;
Intent intentNext;
Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dados);
Spinner spinnerMont = (Spinner) findViewById(R.id.spinnerM);
ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, AçoMontante);
spinnerMont.setAdapter(arrayAdapter1);
campoFy1 = (EditText) findViewById(R.id.fy1);
String montStr = spinnerMont.getSelectedItem().toString();
String fy1 = Double.toString(choiceM(montStr));
campoFy1.setText(fy1);
Spinner spinnerBanzo = (Spinner) findViewById(R.id.spinnerB);
ArrayAdapter<String> arrayAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, AçoBanzo);
spinnerBanzo.setAdapter(arrayAdapter2);
campoFyo = (EditText) findViewById(R.id.fyo);
String banzoStr = spinnerBanzo.getSelectedItem().toString();
String fyo = Double.toString(choiceB(banzoStr));
campoFyo.setText(fyo);
next = (Button) findViewById(R.id.prosseguir);
intentNext = new Intent(Dados.this, ConferenciaDosDados.class);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String resistenciaM = campoFy1.getText().toString();
String resistenciaB = campoFyo.getText().toString();
bundle.putString("fy1",resistenciaM);
bundle.putString("fyo",resistenciaB);
intentNext.putExtras(bundle);
startActivity(intentNext);
}
});
}
public double choiceM(String str) {
Double f1 = 0.0;
if (str.equals(AçoMontante[0])) {
f1 = 250.0;
} else if (str.equals(AçoMontante[1])) {
f1 = 300.0;
}
return f1;
}
public double choiceB(String str) {
Double fo = 0.0;
if (str.equals(AçoMontante[0])) {
fo = 250.0;
} else if (str.equals(AçoMontante[1])) {
fo = 300.0;
}
return fo;
}
}

Try this. This code is working as you want it to.
String [] AçoMontante = {"SAE 1020", "E-155"};
String [] AçoBanzo = {"SAE 1020", "E-155"};
String [] EspessuraT1 = {"0,75 mm", "0,90 mm", "0,95 mm"};
String [] EspessuraTo = {"0,75 mm", "0,90 mm", "0,95 mm"};
EditText campoFy1;
EditText campoFyo;
Button next;
Intent intentNext;
Bundle bundle;
String montStr,banzoStr, f1,fo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
campoFy1 = (EditText) findViewById(R.id.fy1);
campoFyo = (EditText) findViewById(R.id.fyo);
Spinner spinnerMont = (Spinner) findViewById(R.id.spinnerM);
Spinner spinnerBanzo = (Spinner) findViewById(R.id.spinnerB);
ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, AçoMontante);
ArrayAdapter<String> arrayAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, AçoBanzo);
spinnerMont.setAdapter(arrayAdapter1);
spinnerBanzo.setAdapter(arrayAdapter2);
spinnerMont.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long l) {
montStr = (String) parent.getItemAtPosition(i);
if(montStr == "SAE 1020"){
f1 = "250.0";
}
else if (montStr == "E-155"){
f1 = "300.0";
}
else{}
campoFy1.setText(f1);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spinnerBanzo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long l) {
banzoStr = (String) parent.getItemAtPosition(i);
if(banzoStr == "SAE 1020"){
fo = "250.0";
}
else if (banzoStr == "E-155"){
fo = "300.0";
}
else{}
campoFyo.setText(fo);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
next = (Button) findViewById(R.id.prosseguir);
intentNext = new Intent(MainActivity.this, Second.class);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String resistenciaM = campoFy1.getText().toString();
String resistenciaB = campoFyo.getText().toString();
bundle.putString("fy1",resistenciaM);
bundle.putString("fyo",resistenciaB);
intentNext.putExtras(bundle);
startActivity(intentNext);
}
});
}
Also, instead of bundles, you can just use private static variables to pass the value.
set f1 and fo as
private static String f1,fo; instead of String f1,fo;.
And call them in another activity as Dados.f1 or Dados.fo [ Dados here is your current activity ]

Related

Android Restful API retrofit fetching data on Create method but not display

Here is complete code
(In first activity two values are taken from spinner and through a function data sent to second activity)
First Activity:
public class FindBloodActivity extends AppCompatActivity {
String API = "http://abdolqadir-001-site1.ctempurl.com/Account.svc";
TextView t;
Spinner spbgid;
Spinner spcityid;
ProgressBar pro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_blood);
t = (TextView) findViewById(R.id.tv);
pro=(ProgressBar) findViewById(R.id.progressBar2);
pro.setVisibility(View.INVISIBLE);
spbgid=(Spinner) findViewById(R.id.spinnerBG);
spcityid=(Spinner) findViewById(R.id.spinnerLocation);
t.setVisibility(View.INVISIBLE);
}
public void SearchOn(View v) {
String BGId = Integer.toString(spbgid.getSelectedItemPosition()+1);
String CityId =Integer.toString(spcityid.getSelectedItemPosition()+1);
Intent intent=new Intent(getApplicationContext(),SearchResult2.class);
intent.putExtra("bid",BGId);
intent.putExtra("cid",CityId);
startActivity(intent);
}
}
Second Activity: In second activity on tt.append(string.toString()); working fine, but when i add below code than application terminated if i try to debug than also application terminate.
public class SearchResult2 extends AppCompatActivity {
String API = "http://abdolqadir-001-site1.ctempurl.com/Account.svc";
Spinner sp;
TextView t;
TextView tt;
public int totalUsersCount = 0;
String[] allUserNames;
String[] allUserContacts;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result2);
tt=(TextView)findViewById(R.id.tvTest);
tt.setVisibility(View.INVISIBLE);
Bundle extras = getIntent().getExtras();
String BGId = extras.getString("bid");
String CityId = extras.getString("cid");
tt.setText("");
final RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API).build();
final gitapi git = restAdapter.create(gitapi.class);
git.SearchUsers(BGId, CityId, new Callback<String>() {
#Override
public void success(String string, Response response) {
tt.append(string.toString());
}
#Override
public void failure(RetrofitError retrofitError) {
tt.setText("No User Found");
}
});
String bigArray = tt.getText().toString();
listView = (ListView)findViewById(R.id.lvUsers);
bigArray = bigArray.substring(0, bigArray.length() - 1);
totalUsersCount = bigArray.split(",").length;
listView.clearTextFilter();
if (totalUsersCount > 0)
{
String[] allUsers = new String[totalUsersCount];
allUsers = bigArray.split(",");
allUserNames = new String[totalUsersCount];
allUserContacts = new String[totalUsersCount];
String[] temp = new String[3];
for (int i = 0; i < totalUsersCount; i++) {
temp = allUsers[i].split("-");
allUserNames[i] = temp[1];
allUserContacts[i] = temp[2];
}
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, allUserNames);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SendSMS(position);
}
});
}
}
}
This is log
02-08 12:40:51.433 9970-10008/com.example.abdulqadir.bd I/OpenGLRenderer: Initialized EGL, version 1.4
02-08 12:40:51.457 9970-10008/com.example.abdulqadir.bd W/linker: /vendor/lib64/libhwuibp.so: unused DT entry: type 0xf arg 0xe3a
02-08 12:40:51.458 9970-9970/com.example.abdulqadir.bd W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
02-08 12:40:51.548 9970-10008/com.example.abdulqadir.bd E/hwaps: APS: SSR : The platform cannot support SSR !: 0x0,0x0,8
This code below is working fine for me but when i changed this to above than getting errors, here is code please check
public class FindBloodActivity extends AppCompatActivity {
String API = "http://abdolqadir-001-site1.ctempurl.com/Account.svc";
TextView t;
Spinner spbgid;
Spinner spcityid;
ProgressBar pro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_blood);
t = (TextView) findViewById(R.id.tv);
pro=(ProgressBar) findViewById(R.id.progressBar2);
pro.setVisibility(View.INVISIBLE);
spbgid=(Spinner) findViewById(R.id.spinnerBG);
spcityid=(Spinner) findViewById(R.id.spinnerLocation);
t.setVisibility(View.INVISIBLE);
}
public void SearchOn(View v) {
String BGId = Integer.toString(spbgid.getSelectedItemPosition()+1);
String CityId =Integer.toString(spcityid.getSelectedItemPosition()+1);
SearchAllUsers(BGId.toString(), CityId.toString());
}
public void SearchAllUsers(String BGId,String CityId) {
t.setText("");
final RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API).build();
final gitapi git= restAdapter.create(gitapi.class);
git.SearchUsers(BGId,CityId,new Callback<String>() {
#Override
public void success(String string, Response response) {
t.append(string.toString());
}
#Override
public void failure(RetrofitError retrofitError) {
t.setText("No User Found");
}
});
}
public void Search(View v){
try {
Thread.sleep(9000);
Intent intent=new Intent(getApplicationContext(),SearchResult.class);
intent.putExtra("users",t.getText().toString());
startActivity(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Second Activity:
public class SearchResult2 extends AppCompatActivity {
String API = "http://abdolqadir-001-site1.ctempurl.com/Account.svc";
Spinner sp;
TextView t;
TextView tt;
public int totalUsersCount = 0;
String[] allUserNames;
String[] allUserContacts;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result2);
tt=(TextView)findViewById(R.id.tvTest);
tt.setVisibility(View.INVISIBLE);
Bundle extras = getIntent().getExtras();
String BGId = extras.getString("bid");
String CityId = extras.getString("cid");
tt.setText("");
final RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API).build();
final gitapi git = restAdapter.create(gitapi.class);
git.SearchUsers(BGId, CityId, new Callback<String>() {
#Override
public void success(String string, Response response) {
tt.append(string.toString());
}
#Override
public void failure(RetrofitError retrofitError) {
tt.setText("No User Found");
}
});
String bigArray = tt.getText().toString();
listView = (ListView)findViewById(R.id.lvUsers);
bigArray = bigArray.substring(0, bigArray.length() - 1);
totalUsersCount = bigArray.split(",").length;
listView.clearTextFilter();
if (totalUsersCount > 0)
{
String[] allUsers = new String[totalUsersCount];
allUsers = bigArray.split(",");
allUserNames = new String[totalUsersCount];
allUserContacts = new String[totalUsersCount];
String[] temp = new String[3];
for (int i = 0; i < totalUsersCount; i++) {
temp = allUsers[i].split("-");
allUserNames[i] = temp[1];
allUserContacts[i] = temp[2];
}
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, allUserNames);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SendSMS(position);
}
});
}
}
Here are the things you can try, use this code in onCreate()
listView = (ListView)findViewById(R.id.lvUsers);
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, allUserNames);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SendSMS(position);
}
});
and where you were using the above code before replace it with i.e of inside of if condition
itemsAdapter.notifyDatasetChanged();
Hope this helps
Why not do your REST call from the onCreate() method?
Also component.setVisibility(View.INVISIBLE); retains space in the overall layout. You could use 'GONE' instead and see if that helps or hurts.
And try have your URL and other components in different methods or classes. This can help a WHOLE LOT to keep the code clean and easy to find errors.
With all this said, after using breakpoints and running in debug mode which line is the error?

Make arraylist parcelable in my code?

Can anybody help me making the arraylist final ArrayList<PieEntry> entries = new ArrayList<>();
Parcelable in my code so I can access it in methods in both fragment a and b
- Fragment a code:
public class SecondFragment extends Fragment {
// Store instance variables
private String title;
private int page;
// newInstance constructor for creating fragment with arguments
public static SecondFragment newInstance(int page, String title) {
SecondFragment fragmentSecond = new SecondFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentSecond.setArguments(args);
return fragmentSecond;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
// Inflate the view for the fragment based on layout XML
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_second, container, false);
TextView tvLabel2 = (TextView) view.findViewById(R.id.textView2);
//Alle Objekte hier einfügen (wie textview tvavel2)
final Button button = (Button) view.findViewById(R.id.button);
final TextView textView = (TextView) view.findViewById(R.id.textView);
final TextView textView2 = (TextView) view.findViewById(R.id.textView2);
final EditText editText = (EditText) view.findViewById(R.id.editText);
final EditText editText2 = (EditText) view.findViewById(R.id.editText2);
final EditText editText3 = (EditText) view.findViewById(R.id.editText3);
final ArrayList<PieEntry> entries = new ArrayList<>();
button.setOnClickListener(new View.OnClickListener() {
public void onClick (View view) {
if (editText3.getText().toString().matches("")) {
Toast.makeText(getActivity(), "You did not enter a Valid Item ID", Toast.LENGTH_LONG).show();
return;
}
else if (editText2.getText().toString().matches("")) {
Toast.makeText(getActivity(), "You did not enter a Valid Quantitiy", Toast.LENGTH_LONG).show();
return;
}
else {
String nomen = (editText3.getText().toString());
float number = Float.parseFloat(editText2.getText().toString());
entries.add(new PieEntry(number, nomen));
editText3.setText("");
editText2.setText("");
editText3.requestFocus();
}
}
});
return view;
}
}
Fragment b code:
public class FirstFragment extends Fragment {
private String title;
private int page;
public static FirstFragment newInstance(int page, String title) {
FirstFragment fragmentFirst = new FirstFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
EditText editText = (EditText) view.findViewById(R.id.editText);
final PieChart piechart = (PieChart) view.findViewById(R.id.piechart);
final Button button2 = (Button) view.findViewById(R.id.button2);
new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int position) {
}
};
button2.setOnClickListener(new View.OnClickListener() {
public void onClick (View view) {
getResources().getColor(R.color.violp);
getResources().getColor(R.color.bluep);
getResources().getColor(R.color.redp);
getResources().getColor(R.color.greenp);
getResources().getColor(R.color.yellowp);
getResources().getColor(R.color.orangep);
getResources().getColor(R.color.lightbluep);
getResources().getColor(R.color.purplep);
getResources().getColor(R.color.darkredp);
PieDataSet set = new PieDataSet(entries, "");
set.setColors(new int[]{R.color.bluep, R.color.greenp, R.color.violp, R.color.redp, R.color.yellowp, R.color.orangep, R.color.lightbluep, R.color.purplep, R.color.darkredp}, getActivity());
PieData datax = new PieData(set);
piechart.setData(datax);
Toast.makeText(getActivity(), (R.string.loading),
Toast.LENGTH_SHORT).show();
piechart.setNoDataText(String.valueOf(R.string.nodata));
piechart.notifyDataSetChanged();
piechart.animateX(2000, Easing.EasingOption.EaseInExpo);
piechart.animateY(2000, Easing.EasingOption.EaseInExpo);
}
});
return view;
}
I have tried a number of options so far but I could not get the programm to run.
Any help is apprediated.
Thanks!
In order to transfer data, we need to parcel it or serialize it. Android OS by default promoting Parcelable instead to Serialization. Serialization is a java concept. In your case, you need to create the "PieEntry" class as Parcelable. For that, you need to implement the Parcelable interface in your model.
Check below implementation.
package com.cludprinting.mysample;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by nithinjith.pp on 05-01-2017.
* Implement Parcelable in PieEntry.
*
*/
public class PieEntry implements Parcelable {
public static final Parcelable.Creator<PieEntry> CREATOR = new Parcelable.Creator<PieEntry>() {
#Override
public PieEntry createFromParcel(Parcel source) {
return new PieEntry(source);
}
#Override
public PieEntry[] newArray(int size) {
return new PieEntry[size];
}
};
// These are sample instance variables
// Add your own instance variable
private String mName;
private String mDOB;
private int mAge;
public PieEntry(Parcel parcel) {
this.mName = parcel.readString();
this.mDOB = parcel.readString();
this.mAge = parcel.readInt();
}
public int getmAge() {
return mAge;
}
public void setmAge(int mAge) {
this.mAge = mAge;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.mName);
dest.writeString(this.mDOB);
dest.writeInt(this.mAge);
}
public String getmDOB() {
return mDOB;
}
public void setmDOB(String mDOB) {
this.mDOB = mDOB;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
}
The instance variable and access methods may change based on your implemenaton.

how to refresh listview after deleting data from database?

All Transaction Activity is used to to fetch data from database
public class AllTransactionActivity extends MainActivity {
ArrayList<String> price = new ArrayList<String>();
ArrayList<String> category = new ArrayList<String>();
ArrayList<String> date = new ArrayList<String>();
ArrayList<String> id = new ArrayList<String>();
ArrayList<String> payment_mode = new ArrayList<String>();
ArrayList<String> description = new ArrayList<String>();
RadioButton rb1 , rb2 ;
ListView listView ;
Cursor cv;
LinearLayout list_lay;
RelativeLayout no_data_lay;
String date_change;
Boolean check_btn = false;
Transactiondata data ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_transaction);
findViewById();
Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar);
TextView mTitle = (TextView) toolbarTop.findViewById(R.id.title);
mTitle.setText("All Transaction");
data = new Transactiondata(AllTransactionActivity.this);
data.open();
cv = data.incomeDisplayData();
id.clear();
price.clear();
category.clear();
date.clear();
payment_mode.clear();
description.clear();
if (cv.moveToFirst()) {
do {
category.add(cv.getString(cv.getColumnIndex(Transactiondata.KEY_CATEGORY)));
id.add(cv.getString(cv.getColumnIndex(Transactiondata.KEY_ID)));
// date.add(cv.getString(cv.getColumnIndex(Transactiondata.KEY_DATE)));
SimpleDateFormat simpleDateFormate = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
try {
date1 = simpleDateFormate.parse(cv.getString(cv.getColumnIndex(Transactiondata.KEY_DATE)));
SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy");
date_change = fmtOut.format(date1);
} catch (ParseException e) {
e.printStackTrace();
}
date.add(date_change);
price.add(cv.getString(cv.getColumnIndex(Transactiondata.KEY_PRICE)));
payment_mode.add(cv.getString(cv.getColumnIndex(Transactiondata.KEY_PAYMENT_MODE)));
description.add(cv.getString(cv.getColumnIndex(Transactiondata.KEY_DESCRIPTION)));
} while (cv.moveToNext());
}else {
list_lay.setVisibility(View.GONE);
no_data_lay.setVisibility(View.VISIBLE);
}
listView.setAdapter(new DisplayAllDataAdapter(this, AllTransactionActivity.this , check_btn , id , category , date , price , payment_mode , description ));
cv.close();
}
public void findViewById(){
listView = (ListView)findViewById(R.id.list);
rb1 =(RadioButton)findViewById(R.id.rb1) ;
rb2 =(RadioButton)findViewById(R.id.rb2) ;
no_data_lay = (RelativeLayout)findViewById(R.id.no_data_lay);
list_lay = (LinearLayout)findViewById(R.id.list_lay);
}
}
Custom Adapter Class which is used to bind data with list view
package app.dailyexpensemanager.adapters;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import app.dailyexpensemanager.R;
import app.dailyexpensemanager.activity.EditReminderActivity;
import app.dailyexpensemanager.activity.PaymentTransactionActivity;
import app.dailyexpensemanager.db.Transactiondata;
public class DisplayAllDataAdapter extends BaseAdapter {
private Context mContext;
private static Cursor cursor;
private static Activity activity;
private static Boolean check_btn;
private ArrayList<String> category_list;
private ArrayList<String> date_list;
private ArrayList<String> id_list ;
private ArrayList<String> price_list ;
private ArrayList<String> payment_mode_list ;
private ArrayList<String> description_list ;
public DisplayAllDataAdapter(Context cv, Activity activity, Boolean check_btn, ArrayList<String> id, ArrayList<String> category, ArrayList<String> date,
ArrayList<String> price, ArrayList<String> payment_mode, ArrayList<String> description) {
this.check_btn = check_btn;
this.id_list = id;
this.category_list = category;
this.date_list = date;
this.price_list = price;
this.payment_mode_list = payment_mode;
this.description_list = description;
this.mContext = cv;
this.activity = activity;
}
public DisplayAllDataAdapter(Context cv, Activity activity,Cursor cursor , Boolean check_btn, ArrayList<String> id, ArrayList<String> category, ArrayList<String> date,
ArrayList<String> price, ArrayList<String> payment_mode, ArrayList<String> description) {
this.check_btn = check_btn;
this.id_list = id;
this.category_list = category;
this.date_list = date;
this.price_list = price;
this.payment_mode_list = payment_mode;
this.description_list = description;
this.mContext = cv;
this.activity = activity;
this.cursor = cursor;
}
#Override
public int getCount() {
return date_list.size();
}
#Override
public Object getItem(int position) {
return date_list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View child, ViewGroup parent) {
final Holder mHolder;
LayoutInflater layoutInflater = null;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.activity_list_all_transaction, null);
mHolder = new Holder();
mHolder.txt_category = (TextView) child.findViewById(R.id.category);
mHolder.txt_date = (TextView) child.findViewById(R.id.date);
mHolder.txt_id = (TextView) child.findViewById(R.id.id);
mHolder.txt_price = (TextView) child.findViewById(R.id.price);
mHolder.txt_payment = (TextView) child.findViewById(R.id.payment);
mHolder.txt_description = (TextView) child.findViewById(R.id.description);
child.setTag(mHolder);
}
else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_category.setText(category_list.get(position));
mHolder.txt_date.setText(date_list.get(position));
mHolder.txt_id.setText(id_list.get(position));
mHolder.txt_price.setText(price_list.get(position));
mHolder.txt_payment.setText(payment_mode_list.get(position));
mHolder.txt_description.setText(description_list.get(position));
child.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setBackgroundResource(R.drawable.item_pressed);
/*Animation animation1 = new AlphaAnimation(0.3f, 1.0f);
animation1.setDuration(2000);
v.startAnimation(animation1);*/
String price_lv = mHolder.txt_price.getText().toString();
String id_lv = mHolder.txt_id.getText().toString();
String category_lv = mHolder.txt_category.getText().toString();
String payment_lv = mHolder.txt_payment.getText().toString();
String date_lv = mHolder.txt_date.getText().toString();
String description_lv = mHolder.txt_description.getText().toString();
showCustomeDialogBox(mContext, false, price_lv, id_lv, category_lv, payment_lv,
date_lv, description_lv);
// notifyDataSetChanged();
}
});
return child;
}
public class Holder {
TextView txt_category;
TextView txt_price;
TextView txt_id;
TextView txt_date;
TextView txt_payment;
TextView txt_description;
}
public static void showCustomeDialogBox(final Context context, final boolean activityVisibility,String price,
final String id , String category , String payment , String date , String description ) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.activity_custom_dailog);
Button positivebtn = (Button) dialog.findViewById(R.id.positive);
Button negativebtn = (Button) dialog.findViewById(R.id.negative);
LinearLayout category_lay = (LinearLayout) dialog.findViewById(R.id.category_lay);
TextView dialog_title = (TextView) dialog.findViewById(R.id.dialog_title);
TextView price_tv = (TextView) dialog.findViewById(R.id.price);
TextView category_tv = (TextView) dialog.findViewById(R.id.category);
TextView payment_tv = (TextView) dialog.findViewById(R.id.payment_mode);
TextView date_tv = (TextView) dialog.findViewById(R.id.date);
TextView description_tv = (TextView) dialog.findViewById(R.id.description);
category_lay.setVisibility(View.GONE);
dialog_title.setText(category);
price_tv.setText(price);
category_tv.setText(category);
payment_tv.setText(payment);
date_tv.setText(date);
description_tv.setText(description);
positivebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!check_btn) {
Transactiondata delete = new Transactiondata(context);
delete.open();
delete.deleteIncomeEntry(id);
this.notifyDataSetChanged();
delete.close();
/*recreate all transaction Activity .... to refresh data ..........*/
activity.recreate();
dialog.dismiss();
} else {
Transactiondata delete = new Transactiondata(context);
delete.open();
delete.deleteExpenseEntry(id);
this.notifyDataSetChanged();
delete.close();
/*recreate all transaction Activity .... to refresh data ..........*/
activity.recreate();
dialog.dismiss();
}
}
});
negativebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
Window window = dialog.getWindow();
window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
}
In dialog box code I have done it with recreate activity but I think it is not good solution. Now how to delete and refresh same time listview data only? hlep me :(
Try this,
positivebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!check_btn) {
Transactiondata delete = new Transactiondata(context);
delete.open();
delete.deleteIncomeEntry(id);
notifyDataSetChanged();
delete.close();
/*recreate all transaction Activity .... to refresh data ..........*/
activity.recreate();
dialog.dismiss();
} else {
Transactiondata delete = new Transactiondata(context);
delete.open();
delete.deleteExpenseEntry(id);
notifyDataSetChanged();
delete.close();
/*recreate all transaction Activity .... to refresh data ..........*/
activity.recreate();
dialog.dismiss();
}
}
});
Try to Write mContext.notifyDataSetChanged();.
After this.
delete.deleteIncomeEntry(id);
mContext.notifyDataSetChanged();
EDIT 1:
Just do this.
this.notifyDataSetChanged();
EDIT 2:
Look your data is deleted from database that is sure. so in your Base Adapter to refresh your List View you need to again call the method which is getting data from database. and then do notifydatasetchanged().I hope you will understand.
try this code
adapter=new CustomListAdapter(getActivity(),List);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
And Also add notifyDataSetChanged(); in GetView method below Where you set value.
Check edited first method, just change your showDialog method by below nothing else.
One more thing pass position in your method at last as like below.
showCustomeDialogBox(mContext, false, price_lv, id_lv, category_lv, payment_lv,
date_lv, description_lv, position);
See new DialogBox method below,
public static void showCustomeDialogBox(final Context context, final boolean activityVisibility,String price,
final String id , String category , String payment , String date , String description, int position ) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.activity_custom_dailog);
Button positivebtn = (Button) dialog.findViewById(R.id.positive);
Button negativebtn = (Button) dialog.findViewById(R.id.negative);
LinearLayout category_lay = (LinearLayout) dialog.findViewById(R.id.category_lay);
TextView dialog_title = (TextView) dialog.findViewById(R.id.dialog_title);
TextView price_tv = (TextView) dialog.findViewById(R.id.price);
TextView category_tv = (TextView) dialog.findViewById(R.id.category);
TextView payment_tv = (TextView) dialog.findViewById(R.id.payment_mode);
TextView date_tv = (TextView) dialog.findViewById(R.id.date);
TextView description_tv = (TextView) dialog.findViewById(R.id.description);
category_lay.setVisibility(View.GONE);
dialog_title.setText(category);
price_tv.setText(price);
category_tv.setText(category);
payment_tv.setText(payment);
date_tv.setText(date);
description_tv.setText(description);
positivebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!check_btn) {
Transactiondata delete = new Transactiondata(context);
delete.open();
delete.deleteIncomeEntry(id);
this.notifyDataSetChanged();
delete.close();
/*recreate all transaction Activity .... to refresh data ..........*/
//activity.recreate();
//dialog.dismiss();
} else {
Transactiondata delete = new Transactiondata(context);
delete.open();
delete.deleteExpenseEntry(id);
this.notifyDataSetChanged();
delete.close();
/*recreate all transaction Activity .... to refresh data ..........*/
//activity.recreate();
//dialog.dismiss();
}
id_list.remove(position);
category_list.remove(position);
date_list.remove(position);
price_list.remove(position);
payment_mode_list.remove(position);
description_list.remove(position);
dialog.dismiss();
notifyDataSetChanged();
}
});
negativebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
Window window = dialog.getWindow();
window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
Try Below Code It will help you,
First comment your dialog box method, and write below method to use.
public void deleteData(int position)
{
String id = id_list.get(position);
if (!check_btn) {
Transactiondata delete = new Transactiondata(context);
delete.open();
delete.deleteIncomeEntry(id);
delete.close();
}
else
{
Transactiondata delete = new Transactiondata(context);
delete.open();
delete.deleteExpenseEntry(id);
delete.close();
}
id_list.remove(position);
category_list.remove(position);
date_list.remove(position);
price_list.remove(position);
payment_mode_list.remove(position);
description_list.remove(position);
notifyDataSetChanged();
}
Now, replace your onCLick method by below.
child.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setBackgroundResource(R.drawable.item_pressed);
deleteData(position);
}
});

Set the Data of a Spinner based on a result of previous Spinner

I'm trying to fill a spinner based on a choice in a previous spinner,and I'm trying to get the id of the selected item in the previous spinner and the with an if statement I'm trying to add data to the another spinner.The string array are define in the Strings.xml.Any Help Please and this is my code.
public class Set_Info extends AppCompatActivity {
int i;
RadioButton btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set__info);
final EditText CompanyName = (EditText) findViewById(R.id.companyName);
final EditText OwnerName = (EditText) findViewById(R.id.ownerName);
final Spinner CompanyType = (Spinner) findViewById(R.id.companyType);
final Spinner Mohafaza = (Spinner) findViewById(R.id.spinnerMohafaza);
final Spinner Kadaa = (Spinner) findViewById(R.id.spinnerKadaa);
final EditText Village = (EditText) findViewById(R.id.village);
final EditText Street = (EditText) findViewById(R.id.street);
final EditText PhoneNumber = (EditText) findViewById(R.id.phoneNumber);
final EditText PolicyNumber = (EditText) findViewById(R.id.policyNumber);
final DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker);
final TimePicker timePicker = (TimePicker) findViewById(R.id.timePicker);
final EditText AuditName = (EditText) findViewById(R.id.auditName);
final EditText AuditNumber = (EditText) findViewById(R.id.auditNumber);
final RadioGroup RadioGroup = (RadioGroup) findViewById(R.id.radio);
if(RadioGroup.getCheckedRadioButtonId()!=-1){
int id= RadioGroup.getCheckedRadioButtonId();
View Rd = RadioGroup.findViewById(id);
int radioId = RadioGroup.indexOfChild(Rd);
RadioButton btn = (RadioButton) RadioGroup.getChildAt(radioId);
}
final List<String> Facilities = Arrays.asList(getResources().getStringArray(R.array.Facilities));
ArrayAdapter<String> FaciltiesAdapter = new ArrayAdapter<String>(this, R.layout.spinner_style, Facilities);
final List<String> Mohafazat = Arrays.asList(getResources().getStringArray(R.array.Mohafazat));
ArrayAdapter<String> MohazatAdapter = new ArrayAdapter<String>(this, R.layout.spinner_style, Mohafazat);
CompanyType.setAdapter(FaciltiesAdapter);
Mohafaza.setAdapter(MohazatAdapter);
final List<String> KadaaBeirut = Arrays.asList(getResources().getStringArray(R.array.KadaaBeirut));
final List<String> KadaaJabal = Arrays.asList(getResources().getStringArray(R.array.KadaaJabal));
final List<String> KadaaNorth = Arrays.asList(getResources().getStringArray(R.array.KadaaNorth));
final List<String> KadaaSouth = Arrays.asList(getResources().getStringArray(R.array.KadaaSouth));
final List<String> KadaaNabatieh = Arrays.asList(getResources().getStringArray(R.array.KadaaNabatieh));
final List<String> KadaaBekaa = Arrays.asList(getResources().getStringArray(R.array.KadaaBekaa));
;
final ArrayAdapter<String> BeirutAdapter = new ArrayAdapter<String>(this, R.layout.spinner_style,KadaaBeirut);
final ArrayAdapter<String> JabalAdapter = new ArrayAdapter<String>(this, R.layout.spinner_style,KadaaJabal);
final ArrayAdapter<String> NorthAdapter = new ArrayAdapter<String>(this, R.layout.spinner_style,KadaaNorth);
final ArrayAdapter<String> SouthAdapter = new ArrayAdapter<String>(this, R.layout.spinner_style,KadaaSouth);
final ArrayAdapter<String> NabatiehAdapter = new ArrayAdapter<String>(this, R.layout.spinner_style,KadaaNabatieh);
final ArrayAdapter<String> BekaaAdapter = new ArrayAdapter<String>(this, R.layout.spinner_style,KadaaBekaa);
Mohafaza.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
i = parent.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
if(i==0){
Kadaa.setAdapter(BeirutAdapter);
}else if(i==1){
Kadaa.setAdapter(JabalAdapter);
}else if(i==2){
Kadaa.setAdapter(NorthAdapter);
}else if(i==3){
Kadaa.setAdapter(SouthAdapter);
}else if(i==4){
Kadaa.setAdapter(NabatiehAdapter);
}else if(i==5){
Kadaa.setAdapter(BekaaAdapter);
}
Button Submit = (Button) findViewById(R.id.submit);
final ParseObject data = new ParseObject("General_Data");
Submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.put("CompanyName", CompanyName.getText().toString().trim());
data.put("OwnerName", OwnerName.getText().toString().trim());
data.put("CompanyType", CompanyType.getSelectedItem().toString().trim());
data.put("Mohafaza", Mohafaza.getSelectedItem().toString().trim());
data.put("Kadaa", Kadaa.getSelectedItem().toString().trim());
data.put("Village", Village.getText().toString().trim());
data.put("Street", Street.getText().toString().trim());
data.put("PhoneNumber", PhoneNumber.getText().toString().trim());
data.put("PolicyNumber", PolicyNumber.getText().toString().trim());
data.put("AuditName", AuditName.getText().toString().trim());
data.put("AuditNumber", AuditNumber.getText().toString().trim());
data.put("Inspect_Type",btn.getText().toString());
data.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Intent i = new Intent(Set_Info.this, MainActivity.class);
startActivity(i);
}
});
}
});
}
}

Android Spinner

I am working in Spinner.. I am having three spinners and i am going to display days (i,e) 1,2,3,4,5...30,31 in 1st spinner and months in 2nd spinner (i,e)1,2,3,...11,12 and Year in 3rd spinner 2010,.... What i want is that that i wanna to display current date,month,year in 1st,2nd,3rd spinner resp when the page loads..from that it is possible to select any day,month,Year
Here is my code::
public class NoteEdit extends Activity implements OnItemSelectedListener {
private EditText mTitleText;
private EditText mBodyText;
private Long mRowId;
private NotesDbAdapter mDbHelper;
private String array_spinner[];
private int currentDayOfMonth=0;
private int currentDayOfDays=0;
private final String[] months = {"1","2","3","4","5","6","7","8","9","10","11","12"};
Spinner s1,s,s2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.note_edit);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH,month);//month starts from 0
cal.set(Calendar.YEAR,year);
int noOfDayInMonthyear = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
Log.v("noOfDayInMonthyear",""+noOfDayInMonthyear);
ArrayList<Integer> obj=new ArrayList();
ArrayList<Integer> obj1=new ArrayList();
for(int i=1;i<=noOfDayInMonthyear;i++){
obj.add(i);
}
Log.v("Size",""+obj.size());
for(int i=2010;i<=2020;i++){
obj1.add(i);
}
Log.v("Size1",""+obj1.size());
s = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,obj);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s.setOnItemSelectedListener(NoteEdit.this);
s1 = (Spinner) findViewById(R.id.Spinner02);
ArrayAdapter adapter1 = new ArrayAdapter(this,android.R.layout.simple_spinner_item,months);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter1);
s1.setOnItemSelectedListener(NoteEdit.this);
s2 = (Spinner) findViewById(R.id.Spinner03);
ArrayAdapter adapter2 = new ArrayAdapter(this,android.R.layout.simple_spinner_item,obj1);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s2.setAdapter(adapter2);
s2.setOnItemSelectedListener(NoteEdit.this);
s2.setAdapter(adapter2);
mTitleText = (EditText) findViewById(R.id.title);
mBodyText = (EditText) findViewById(R.id.body);
Button confirmButton = (Button) findViewById(R.id.confirm);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(NotesDbAdapter.KEY_ROWID)
: null;
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
: null;
}
populateFields();
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
setResult(RESULT_OK);
finish();
}
});
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
}
public void onNothingSelected(AdapterView<?> arg0) {
}
if i understand your question right, i think you're asking how to set the value for each spinner?
figure out what value you want to select for each spinner and do something like this for each
http://developer.android.com/reference/android/widget/AbsSpinner.html#setSelection(int, boolean)
int dateId = <date id in the spinner>;
s2.setSelection(dateId);

Categories