Android Spinner SetSelection getCount() - android

I want my spinner to setselection() from a string which retrieved from php mysql.
private class RetrievePersonal extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(VirtualIC.this);
pDialog.setMessage("Loading personal details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("accountID", accountID));
JSONObject json = jParser.makeHttpRequest(url_personal_details, "GET", params);
Log.d("Personal Details>>", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
JSONArray personalObj = json.getJSONArray(TAG_PERSONAL);
JSONObject prsl = personalObj.getJSONObject(0);
FindViewById();
name = prsl.getString("name");
nric = prsl.getString("nric");
nationality = prsl.getString("nationality");
religion = prsl.getString("religion");
races = prsl.getString("races");
gender = prsl.getString("nationality");
dob = prsl.getString("dob");
email = prsl.getString("email");
mobile = prsl.getString("mobileNum");
home = prsl.getString("homeNum");
address = prsl.getString("address");
postcode = prsl.getString("postcode");
city = prsl.getString("city");
state = prsl.getString("state");
country = prsl.getString("country");
}else{
}
} catch (Exception e) {
e.printStackTrace();
e.toString();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
FindViewById();
inputName.setText(name);
inputNric.setText(nric);
inputNationality.setText(nationality);
inputReligion.setText(nationality);
inputRaces.setText(nationality);
if(gender.equals("M")){
inputGender.setSelection(getIndex(inputGender, "Male"));
}else{
inputGender.setSelection(getIndex(inputGender, "Female"));
}
inputDay.setSelection(getIndex(inputDay, day));
inputMonth.setSelection(getIndex(inputMonth, month));
inputYear.setSelection(getIndex(inputYear, year));
inputEmail.setText(email);
inputMobileNum.setText(mobile);
inputHomeNum.setText(home);
inputAddress.setText(address);
inputPostcode.setText(postcode);
inputCity.setText(city);
inputState.setSelection(getIndex(inputDay, state));
if(getIndex(inputCountry, country) > 0) {
inputCountry.setSelection(getIndex(inputCountry, country));
}else{
inputCountry.setSelection(getIndex(inputCountry, "Others"));
countryOtherLayout.setVisibility(View.VISIBLE);
inputCountryOther.setText(country);
}
}
}
getIndex() which return the position...
private int getIndex(Spinner spinner, String string){
int index = 0;
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(string)) {
index = i;
break;
}else{
index = -1;
break;
}
}
return index;
}
this is what i get.....
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.Spinner.getCount()' on a null object reference
Please help? Thank you.
private void FindViewById(){
inputGender = (Spinner) findViewById(R.id.gender);
inputMonth = (Spinner) findViewById(R.id.month);
inputState = (Spinner) findViewById(R.id.state);
inputName = (EditText) findViewById(R.id.name);
inputNric = (EditText) findViewById(R.id.nric);
inputNationality = (EditText) findViewById(R.id.nationality);
inputReligion = (EditText) findViewById(R.id.religion);
inputRaces = (EditText) findViewById(R.id.races);
inputEmail = (EditText) findViewById(R.id.email);
inputMobileNum = (EditText) findViewById(R.id.contactnum_hp);
inputHomeNum = (EditText) findViewById(R.id.contactnum_home);
inputAddress = (EditText) findViewById(R.id.address);
inputPostcode = (EditText) findViewById(R.id.postcode);
inputCity = (EditText) findViewById(R.id.city);
inputCountryOther = (EditText) findViewById(R.id.countryOther);
countryLayout = (LinearLayout) findViewById(R.id.countryLayout);
nameLayout = (TextInputLayout) findViewById(R.id.nameLayout);
nricLayout = (TextInputLayout) findViewById(R.id.nricLayout);
nationalityLayout = (TextInputLayout) findViewById(R.id.nationalityLayout);
religionLayout = (TextInputLayout) findViewById(R.id.religionLayout);
racesLayout = (TextInputLayout) findViewById(R.id.racesLayout);
emailLayout = (TextInputLayout) findViewById(R.id.emailLayout);
hpLayout = (TextInputLayout) findViewById(R.id.contactHPLayout);
homeLayout = (TextInputLayout) findViewById(R.id.contactHomeLayout);
addressLayout = (TextInputLayout) findViewById(R.id.addressLayout);
postcodeLayout = (TextInputLayout) findViewById(R.id.postcodeLayout);
cityLayout = (TextInputLayout) findViewById(R.id.cityLayout);
countryOtherLayout = (TextInputLayout) findViewById(R.id.countryOtherLayout);
}

Related

Spinner - How to get value? Android Studio

I would like to insert values from a form into my database. I had problems with values from spinners and I did something wrong, because when I intent in my next activity where the form is the app stops. I will be really grateful.
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText UsernameEt, PasswordEt;
private static Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UsernameEt = (EditText) findViewById(R.id.etUserName);
PasswordEt = (EditText) findViewById(R.id.etPassword);
OnClickButtonListener();
}
public void OnClickButtonListener() {
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(".SecondPan");
startActivity(intent);
}
}
);
}
public void OnLogin(View view)
{
String username = UsernameEt.getText().toString();
String password = PasswordEt.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type,username,password);
}
public void OpenReg(View view){
startActivity(new Intent(this,Register.class));
}
}
Second Panel where user should've been intented and where spinners are:
public class SecondPan extends AppCompatActivity implements AdapterView.OnItemClickListener {
private Spinner sspnOption6, sspn2;
private TextView ttxOption6, ttx;
EditText umowa,nazwa,kategorie,opis,zabezpieczenia,dane;
String czy_dane, transfer;
#SuppressLint("CutPasteId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_pan);
Spinner sspn2 = (Spinner)findViewById(R.id.sspn);
czy_dane = sspn2.getSelectedItem().toString();
Spinner sspnOption6 = (Spinner)findViewById(R.id.sspn2);
transfer = sspnOption6.getSelectedItem().toString();
umowa = (EditText) findViewById(R.id.scnd_txt1);
nazwa = (EditText) findViewById(R.id.scnd_txt2);
kategorie = (EditText) findViewById(R.id.scnd_txt3);
opis = (EditText) findViewById(R.id.scnd_tx4);
zabezpieczenia = (EditText) findViewById(R.id.scnd_tx6);
dane = (EditText) findViewById(R.id.scnd_tx7);
sspnOption6 = findViewById(R.id.sspn);
ArrayAdapter<CharSequence> FirstAdapter = ArrayAdapter.createFromResource(this, R.array.tab1, android.R.layout.simple_spinner_item);
FirstAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sspn2=findViewById(R.id.sspn2);
ArrayAdapter<CharSequence> Secondadapter = ArrayAdapter.createFromResource(this, R.array.transfer, android.R.layout.simple_spinner_item);
Secondadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sspn2.setAdapter(Secondadapter);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
String text = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
public void OnInsert(View view ) {
String str_czy_dane = sspn2.getSelectedItem().toString();
String str_umowa = umowa.getText().toString();
String str_nazwa = nazwa.getText().toString();
String str_kategorie = kategorie.getText().toString();
String str_opis = opis.getText().toString();
String str_transfer = sspn2.getSelectedItem().toString();
String str_zabezpieczenia = zabezpieczenia.getText().toString();
String str_dane = dane.getText().toString();
String type = "insert";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, str_czy_dane,str_umowa, str_nazwa, str_kategorie, str_opis,str_transfer, str_zabezpieczenia, str_dane);
}
}
And there is a script to POST data:
BackgroundWorker.java
else if(type.equals("insert")){
try {
String umowa = params[1];
String czy_dane = params[2];
String nazwa = params[3];
String kategorie = params[4];
String opis = params[5];
String transfer = params[6];
String zabezpieczenia = params[7];
String dane = params[8];
URL url = new URL (insert_url);
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String post_data = URLEncoder.encode("czy_dane","UTF-8")+"="+URLEncoder.encode(czy_dane,"UTF-8")+"&"+
URLEncoder.encode("umowa","UTF-8")+"="+URLEncoder.encode(umowa,"UTF-8")+"&"
+URLEncoder.encode("nazwa","UTF-8")+"="+URLEncoder.encode(nazwa,"UTF-8")+"&"
+URLEncoder.encode("kategorie","UTF-8")+"="+URLEncoder.encode(kategorie,"UTF-8")+"&"
+URLEncoder.encode("opis","UTF-8")+"="+URLEncoder.encode(opis,"UTF-8")+"&"
+URLEncoder.encode("transfer","UTF-8")+"="+URLEncoder.encode(transfer,"UTF-8")+"&"
+URLEncoder.encode("zabezpieczenia","UTF-8")+"="+URLEncoder.encode(zabezpieczenia,"UTF-8")+"&"
+URLEncoder.encode("dane","UTF-8")+"="+URLEncoder.encode(dane,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1")) ;
String result="";
String line="";
while((line = bufferedReader.readLine())!=null) {
result+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
In your code, you are twice assigning Spinner.
Spinner sspn2 = (Spinner)findViewById(R.id.sspn); /// FIRST SPINNER 1 time
czy_dane = sspn2.getSelectedItem().toString();
Spinner sspnOption6 = (Spinner)findViewById(R.id.sspn2);/// SECOND SPINNER 1 time
transfer = sspnOption6.getSelectedItem().toString();
umowa = (EditText) findViewById(R.id.scnd_txt1);
nazwa = (EditText) findViewById(R.id.scnd_txt2);
kategorie = (EditText) findViewById(R.id.scnd_txt3);
opis = (EditText) findViewById(R.id.scnd_tx4);
zabezpieczenia = (EditText) findViewById(R.id.scnd_tx6);
dane = (EditText) findViewById(R.id.scnd_tx7);
sspnOption6 = findViewById(R.id.sspn); /// FIRST SPINNER 2 time
ArrayAdapter<CharSequence> FirstAdapter = ArrayAdapter.createFromResource(this, R.array.tab1, android.R.layout.simple_spinner_item);
FirstAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sspn2=findViewById(R.id.sspn2); /// SECOND SPINNER 2 time
ArrayAdapter<CharSequence> Secondadapter = ArrayAdapter.createFromResource(this, R.array.transfer, android.R.layout.simple_spinner_item);
Secondadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sspn2.setAdapter(Secondadapter);
SOLUTION:
Spinner sspn2 ;
Spinner sspnOption6 ;
umowa = (EditText) findViewById(R.id.scnd_txt1);
nazwa = (EditText) findViewById(R.id.scnd_txt2);
kategorie = (EditText) findViewById(R.id.scnd_txt3);
opis = (EditText) findViewById(R.id.scnd_tx4);
zabezpieczenia = (EditText) findViewById(R.id.scnd_tx6);
dane = (EditText) findViewById(R.id.scnd_tx7);
sspnOption6 = findViewById(R.id.sspn);
ArrayAdapter<CharSequence> FirstAdapter = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item, getResources()
.getStringArray(R.array.tab1));
FirstAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sspnOption6.setAdapter(FirstAdapter);
sspn2=findViewById(R.id.sspn2);
ArrayAdapter<CharSequence> Secondadapter = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item, getResources()
.getStringArray(R.array.transfer));
Secondadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sspn2.setAdapter(Secondadapter);
czy_dane = sspn2.getSelectedItem().toString();
transfer = sspnOption6.getSelectedItem().toString();

how do i apply a condition when the fields are empty then it never post the data to the mysql data base

I am trying to post data to mysql data base and it post it. But now i am trying to apply check if the fields in activity are empty - and data isn't posted to database.
public class Accepter extends Activity implements OnClickListener{
private EditText etName,etAge,etCity,etContact,etQuantity;
private Spinner spBloodGroup;
private ImageView imCancel,imSave;
private String message = "POST";
private static String[] BLOOD_GROUPS = {"Select Blood Group","A +Ve","B +Ve","AB +Ve","O +Ve","A -Ve","B -Ve","AB -Ve","O -Ve"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.accepter_entry_form);
etName = (EditText)findViewById(R.id.etNameAcc);
etAge = (EditText)findViewById(R.id.etAgeAcc);
etCity = (EditText)findViewById(R.id.etCityAcc);
etContact = (EditText)findViewById(R.id.etPhoneNoAcc);
etQuantity = (EditText)findViewById(R.id.etQuantityAcc);
spBloodGroup = (Spinner)findViewById(R.id.spBloodGroupAcc);
imCancel = (ImageView)findViewById(R.id.imCancelAcc);
imSave = (ImageView)findViewById(R.id.imSaveAcc);
imCancel.setOnClickListener(this);
imSave.setOnClickListener(this);
ArrayAdapter<String> bgAdapter = new ArrayAdapter<String>(Accepter.this,android.R.layout.simple_spinner_item,BLOOD_GROUPS);
bgAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spBloodGroup.setAdapter(bgAdapter);
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.imSaveAcc:
String name = etName.getText().toString();
String blood = spBloodGroup.getSelectedItem().toString();
String quantity = etQuantity.getText().toString();
String phone = etContact.getText().toString();
int age = Integer.parseInt(etAge.getText().toString());
String city = etCity.getText().toString();
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month= c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String date = String.valueOf(day) + "-" + String.valueOf(month) + "-" + String.valueOf(year);
if(name.length()>1 && blood.length()>1 && phone.length()>1 && age>15 && city.length()>1)
{
AccepterTask task = new AccepterTask(v.getContext());
task.execute(message ,name, blood, phone, String.valueOf(age),city,quantity,date);
etName.setText("");
spBloodGroup.setSelection(0);
etContact.setText("");
etAge.setText("");
etCity.setText("");
etQuantity.setText("");
finish();
}
else
{
Toast.makeText(Accepter.this, "Any field is empty or invalid", Toast.LENGTH_LONG).show();
}
break;
case R.id.imCancelAcc:
Intent i = new Intent(v.getContext(),MainView.class);
i.putExtra("type", "Accepter");
startActivity(i);
break;
}
}
public class AccepterTask extends AsyncTask<String, Void, String>{
private Context context;
private JSONParser jsonParser = new JSONParser();
private JSONObject json;
private String accepter_url = //"http://192.168.0.6/accepter.php";
"http://10.0.2.2/accepter.php";
private String s;
public AccepterTask(Context c)
{
context = c;
}
#Override
protected String doInBackground(String... params)
{
String message = params[0];
if(message.equals("POST"))
{
List<NameValuePair> list = new ArrayList<NameValuePair>();
final String names = params[1];
final String blood = params[2];
final String phone = params[3];
final String age = params[4];
final String city = params[5];
final String quantity = params[6];
final String date = params[7];
list.add(new BasicNameValuePair("name", names));
list.add(new BasicNameValuePair("blood", blood));
list.add(new BasicNameValuePair("quantity", quantity));
list.add(new BasicNameValuePair("phone", phone));
list.add(new BasicNameValuePair("age", age));
list.add(new BasicNameValuePair("city", city));
list.add(new BasicNameValuePair("date", date));
json = jsonParser.makeHttpRequest(accepter_url, params[0], list);
}
try
{
s = json.getString("message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
#Override
protected void onPostExecute(String result)
{
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
}
here for updates

TextView update not happening when selected item from ListView

Hi I have Listview in that when I select an item I display another page where I am setting the text views with appropriate informations but when i select an item and go back and select another item the textviews are not getting updated ?BTW there are 10 text views can somebody provide me the solution for this? Thanks.
super.onCreate(savedInstanceState);
setContentView(R.layout.lastl);
Intent i = getIntent();
ACK = i.getStringExtra("ack-no");
NAME = i.getExtras().getString("appl name");
TRADE = i.getExtras().getString("trade");
PIN = i.getExtras().getString("pin");
MOBILE = i.getExtras().getString("mobile");
EMAIL = i.getExtras().getString("email");
LVO1 = i.getExtras().getString("LVO1");
LVO2 = i.getExtras().getString("LVO2");
tv1 = (TextView) findViewById(R.id.set_ack);
tv1.setText(ACK);
tv2 = (TextView) findViewById(R.id.set_apl);
tv2.setText(NAME);
tv3 = (TextView) findViewById(R.id.set_trd);
tv3.setText(TRADE);
tv4 = (TextView) findViewById(R.id.set_dr);
tv4.setText(ArrayAdapter.ar.get(0));
tv5 = (TextView) findViewById(R.id.set_flr);
tv5.setText(ArrayAdapter.ar.get(1));
tv6 = (TextView) findViewById(R.id.set_bdg);
tv6.setText(ArrayAdapter.ar.get(2));
tv7 = (TextView) findViewById(R.id.set_str);
tv7.setText(ArrayAdapter.ar.get(3));
tv8 = (TextView) findViewById(R.id.set_area);
tv8.setText(ArrayAdapter.ar.get(4));
tv9 = (TextView) findViewById(R.id.set_dis);
//tv9.setText(ArrayAdapter.ar.get(5));
tv10 = (TextView) findViewById(R.id.set_pin);
tv10.setText(PIN);
tv11 = (TextView) findViewById(R.id.set_mb);
tv11.setText(MOBILE);
tv12 = (TextView) findViewById(R.id.set_email);
tv12.setText(EMAIL);
tv13 = (TextView) findViewById(R.id.set_pn);
tv14 = (TextView) findViewById(R.id.set_bdgg);
tv15 = (TextView) findViewById(R.id.set_dt);
tv16 = (TextView) findViewById(R.id.set_lvo);
tv16.setText(LVO1);
String lvo2 = LVO2.substring(0, LVO2.length() - 1);
Log.d("sssssss", lvo2);
tv17 = (TextView) findViewById(R.id.set_lvo2);
tv17.setText(lvo2);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
break;
case R.id.button2:
break;
}
}
this is my listView code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listmain);
pv = getIntent().getStringArrayListExtra("Array_list");
System.out.println("ARRAYLIST---->" + pv);
final ListView list = (ListView) findViewById(R.id.listView1);
mylistData = new ArrayList<HashMap<String, String>>();
String[] columnTags = new String[]{"col1", "col2", "col3", "col4", "col5", "col6", "col7", "col8"};
int[] columnIds = new int[]{R.id.col1, R.id.col2, R.id.col3, R.id.col4, R.id.col5, R.id.col6, R.id.col7, R.id.col8};
int k = 0;
for (int i = 0; i <= 9; i++) {
HashMap<String, String> map = new HashMap<String, String>();
//initialize row data
for (int j = 0; j <= 7/*pv.size()-1*/; j++) {
map.put(columnTags[j], pv.get(k));
put(columnTags[j], "row" + i + "col" + j);
k++;
}
mylistData.add(map);
}
SimpleAdapter arrayAdapter = new SimpleAdapter(this, mylistData, R.layout.rowmain, columnTags, columnIds);
list.setAdapter(arrayAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parnet, android.view.View view, int position, long id) {
new LongOperation().execute();
String text = list.getItemAtPosition(position).toString();
String g = text.replace("{col5=", "");
String g1 = g.replace(" col4=", "");
String g2 = g1.replace(" col7=", "");
String g3 = g2.replace(" col6=", "");
String g4 = g3.replace(" col1=", "");
String g5 = g4.replace(" col3=", "");
String g6 = g5.replace(" col2=", "");
String g7 = g6.replace(" col8=", "");
String val[] = g7.split(",");
for (int m = 0; m < val.length; m++) {
Log.d("VALUE", val[m]);
ar1.add(val[m]);
}
System.out.println(ar1);
Log.d("VALUES-------->", text);
mob = ar1.get(0);
Log.d("VALUE1", mob);
pin = ar1.get(1);
Log.d("VALUE2", pin);
lvo = ar1.get(2);
Log.d("VALUE3", lvo);
email = ar1.get(3);
Log.d("VALUE4", email);
ack = ar1.get(4);
Log.d("VALUE5", ack);
trade = ar1.get(5);
Log.d("VALUE6", trade);
name = ar1.get(6);
Log.d("VALUE7", name);
lvo2 = ar1.get(7);
Log.d("VALUE8", lvo2);
}
});
}
From your code: ar1.add(val[m]);
I guess that ar1 is a List<String> variable of your listview activity?
If that's true, maybe add a call to clear() may work:
ar1.clear();
for(int m =0 ; m< val.length ; m++)
{
Log.d("VALUE",val[m]);
ar1.add(val[m]);
}

Activity with two JSONClasses

I have an activity that suppose to use JSON twice. In the first time it works perfectly, but on the second time it seems that the JSON class goes directly to the onPostExecute function without activating the doInBackground function. This is the activity that calls the JSON:
public class Registration extends ActionBarActivity {
public void regis(View view) {
EditText userName = (EditText) findViewById(R.id.userNameTxt);
EditText pass1 = (EditText) findViewById(R.id.PassTxt);
EditText pass2 = (EditText) findViewById(R.id.RePassTxt);
EditText displayName = (EditText) findViewById(R.id.DisplayTxt);
EditText mail = (EditText) findViewById(R.id.eMailTxt);
CheckBox agree = (CheckBox) findViewById(R.id.checkAgree);
TextView err = (TextView) findViewById(R.id.err);
String uName = userName.getText().toString(), pss1 = pass1.getText().toString(),
pss2 = pass2.getText().toString(), disName = displayName.getText().toString(),
eMail = mail.getText().toString();
if ((uName.length() > 0) && (pss1.length() > 0) && (pss2.length() > 0) && (disName.length() > 0)
&& (eMail.length() > 0)) {
if (pss1.equals(pss2)) {
if (agree.isChecked()) {
err.setVisibility(TextView.INVISIBLE);
String str = "?uname=" + uName;
new JSONClass(this, 2, str, this).execute();
} else {
err.setText("You must approve the use terms");
err.setVisibility(TextView.VISIBLE);
}
} else {
err.setText("The two passwords must match!");
err.setVisibility(TextView.VISIBLE);
}
} else {
err.setText("You must insert values in every cell");
err.setVisibility(TextView.VISIBLE);
}
}
public void checkExist(JSONArray ans) {
try {
int cnt = Integer.parseInt(ans.getJSONObject(0).getString("cnt"));
if (cnt == 1) {
TextView err = (TextView) findViewById(R.id.err);
err.setText("User name already exists!");
err.setVisibility(TextView.VISIBLE);
} else {
EditText userName = (EditText) findViewById(R.id.userNameTxt);
EditText pass = (EditText) findViewById(R.id.PassTxt);
EditText displayName = (EditText) findViewById(R.id.DisplayTxt);
EditText mail = (EditText) findViewById(R.id.eMailTxt);
String uName = userName.getText().toString(), pss = pass.getText().toString(),
disName = displayName.getText().toString(), eMail = mail.getText().toString();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss yyyy-MM-dd");
String currentDateandTime = sdf.format(new Date());
String str = "?uname=" + uName + "&password=" + pss + "&email=" + eMail + "&disnam=" +
disName + "&dt=" + currentDateandTime;
Log.e("log_tag", "Just for me: " + str);
new JSONClass(this, 3, str, this).execute();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void openLogin() {
Intent intent = new Intent(this, Login.class);
startActivity(intent);
finish();
}
}
I removed unnecessary functions. This is my JSON class:
public class JSONClass extends AsyncTask<String,Void,JSONArray>{
private String link;
private int flag;
private Login log = null;
private Registration reg = null;
private Context context;
public JSONClass(Context context, int queryNo, String params, Registration regg) {
this.context = context;
link = "http://pickupfriend.fulba.com/android_project/query" + queryNo + ".php" + params;
reg = regg;
flag = queryNo;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
protected JSONArray doInBackground(String... arg0) {
JSONArray arr = new JSONArray();
try{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(link);
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
arr = new JSONArray(result);
}catch(Exception e){
}
return arr;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public void onPostExecute(JSONArray result) {
switch (flag) {
case 1:
log.getResults(result);
break;
case 2:
reg.checkExist(result);
break;
case 3:
reg.openLogin();
break;
default:
break;
}
}
}
At first I activate the regis function that works perfectly with the json class. Afterwards it suppose to activate checkExist if the cnt parameter is 0, which is 0. Then it is suppose to activate the json class again but it seems that it goes directly to openLogin function without going to the php file and activating it. Am I doing something wrong?

Number format exception

What is wrong with this code? I've got NumberFormatException. Invalid int: ""
Everything looks correctly but I don't know am I doing my EditTexts correctly. Any help is welcome.
public class Wyslij extends Activity {
EditText et_nazwa;
EditText et_nip;
EditText et_adres;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.wyslij);
et_nazwa = (EditText) findViewById(R.id.et_nazwa);
et_nip = (EditText) findViewById(R.id.et_nip);
et_adres = (EditText) findViewById(R.id.et_adres);
ib_wyslij = (ImageButton) findViewById(R.id.ib_wyslij);
String nazwa_firmy = et_nazwa.getText().toString();
String nip_firmowy = et_nip.getText().toString();
int nip_firmy = Integer.valueOf(nip_firmowy);
String adres_firmy = et_adres.getText().toString();
final Zamowienie zam = new Zamowienie();
zam.klient.nazwa = nazwa_firmy;
zam.klient.nip = nip_firmy;
zam.klient.adres = adres_firmy;
String suma_zamowienia = podaj_sume(TowarZamowienie.towary_zamowione);
int suma_zam = Integer.valueOf(suma_zamowienia);
zam.suma=suma_zam;
}
}
public class Wyslij extends Activity {
EditText et_nazwa;
EditText et_nip;
EditText et_adres;
int suma_zam;
int nip_firmy;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.wyslij);
et_nazwa = (EditText) findViewById(R.id.et_nazwa);
et_nip = (EditText) findViewById(R.id.et_nip);
et_adres = (EditText) findViewById(R.id.et_adres);
ib_wyslij = (ImageButton) findViewById(R.id.ib_wyslij);
String nazwa_firmy = et_nazwa.getText().toString();
String nip_firmowy = et_nip.getText().toString();
if(nip_firmowy != null && !nip_firmowy.equalsIgnoreCase(""){
nip_firmy = Integer.parseInt(nip_firmowy);
String adres_firmy = et_adres.getText().toString();
final Zamowienie zam = new Zamowienie();
zam.klient.nazwa = nazwa_firmy;
if(nip_firmy != null){
zam.klient.nip = nip_firmy;
}
if(adres_firmy != null){
zam.klient.adres = adres_firmy;
}
}
String suma_zamowienia = podaj_sume(TowarZamowienie.towary_zamowione);
if(suma_zamowienia != null && !suma_zamowienia.equalsIgnoreCase(""){
suma_zam = Integer.parseInt(suma_zamowienia);
zam.suma=suma_zam;}
}
}
I believe there is a white space when you are fetching value from EditText. So before you convert the string value to integer you need to trim the white space like below,
String nip_firmowy = et_nip.getText().toString().trim(); // use trim here
int nip_firmy = Integer.parseInt(nip_firmowy); // use parseInt() method

Categories

Resources