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();
Related
I've been working on this app that collects information, then sends it in email form. All of my other EditTexts are working with the exception of the very first one, pilot (the hint is name, as in the name of the pilot). I've gone through this thoroughly for multiple hours but I just cant seem to find what is the problem. The only reason I know its null is because when it goes into the email format all it says is null
public class InfoSheet extends AppCompatActivity {
private double VesselUnits;
private EditText pilot, ship, to, from, LOA, MBDTH, CUSD, zone1, zone2, CallSign;
private Spinner agent_spinner;
private Button btnSubmit;
private String date, agent, Spilot, Sship, Sto, Sfrom, Szone1, Szone2, SCallSign, SVesselUnits;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_sheet);
date=getTodaysDate();
addListenerOnButton();
}
public void collectNCalc(){
//grab all of our info
agent_spinner = (Spinner) findViewById(R.id.agent_spinner);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
pilot = (EditText) findViewById(R.id.Pilot);
ship = (EditText) findViewById(R.id.ship);
to = (EditText) findViewById(R.id.to);
from = (EditText) findViewById(R.id.from);
LOA = (EditText) findViewById(R.id.LOA);
MBDTH = (EditText) findViewById(R.id.MBDTH);
CUSD = (EditText) findViewById(R.id.CUSD);
zone1 = (EditText) findViewById(R.id.zone1);
zone2 = (EditText) findViewById(R.id.zone2);
CallSign = (EditText) findViewById(R.id.CallSign);
//convert what we need to int to do equations
String sLOA = LOA.getText().toString();
double intLOA = Integer.valueOf(sLOA);
intLOA = intLOA*3.281;
String sMBDTH = MBDTH.getText().toString();
double intMBDTH = Integer.valueOf(sMBDTH);
intMBDTH = intMBDTH*3.281;
String sCUSD = CUSD.getText().toString();
double intCUSD = Integer.valueOf(sCUSD);
intCUSD = intCUSD*3.281;
VesselUnits = intLOA*intMBDTH*intCUSD;
VesselUnits = VesselUnits/10000;
Spilot=pilot.getText().toString();
Sship=ship.getText().toString();
Sto=to.getText().toString();
Sfrom=from.getText().toString();
Szone1=zone1.getText().toString();
Szone2=zone2.getText().toString();
SCallSign=CallSign.getText().toString();
agent=agent_spinner.getSelectedItem().toString();
//SVesselUnits=String.valueOf(VesselUnits);
}
public void addListenerOnButton() {
final Context context2 = this;
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i2 = new Intent(context2, DigitalSignature.class);
//do the Calc
collectNCalc();
//pass to next activity
i2.putExtra("Pilot",Spilot);
i2.putExtra("ship",Sship);
i2.putExtra("to",Sto);
i2.putExtra("from",Sfrom);
i2.putExtra("zone1",Szone1);
i2.putExtra("zone2",Szone2);
i2.putExtra("callsign",SCallSign);
i2.putExtra("agent",agent);
i2.putExtra("vessleunits",VesselUnits);
i2.putExtra("date",date);
startActivity(i2);
}
});
}
its sent to the next and final activity:
public class DigitalSignature extends AppCompatActivity {
String pilot, ship, to, from, zone1, zone2, CallSign, agent, date;
Toolbar toolbar;
Button btn_get_sign, mClear, mGetSign, mCancel, btn_send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_digital_signature);
Bundle extras = getIntent().getExtras();
if (extras != null) {
pilot = extras.getString("pilot");
ship = extras.getString("ship");
to = extras.getString("to");
from = extras.getString("from");
zone1 = extras.getString("zone1");
zone2 = extras.getString("zone2");
CallSign = extras.getString("callsign");
agent = extras.getString("agent");
vesselUnit = extras.getDouble("vesselunits");
date = extras.getString("date");
}
btn_send.setOnClickListener(new OnClickListener() {
public void onClick(View v){
Uri path = Uri.parse("file://" + file);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_TEXT, pilot+"\n"+ship+"\n"+to+"\n"+from+"\n"+zone1+"\n"+zone2+"\n"+CallSign+"\n"+agent+"\n"+vesselUnit);
// set the type to 'email'
emailIntent.setType("image/png");
String to[] = {"metropilottickets#gmail.com"};
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
// the attachment
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
// the mail subject
emailIntent.putExtra(Intent.EXTRA_SUBJECT, pilot+"'s Ticket for "+ship);
startActivity(Intent.createChooser(emailIntent , "Send email..."));
}
});
}
I left out a lot of the other code that's irrelevant to my question, but if anyone can point out why I'm getting null you'd be a life saver!
You need to use extras.getString("Pilot");
insteadof extras.getString("pilot");
//error here
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference myRef = database.getReference("Runtime");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ping);
btn1 = (Button) findViewById(R.id.ping);
lstPing = (ListView) findViewById(R.id.listPing);
editText = (EditText) findViewById(R.id.edit_query);
// Write a message to the database
}
public void fExecutePing (View view) {
Editable host = editText.getText();
List<String> listResponsPing = new ArrayList<String>();
ArrayAdapter<String> adapterList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listResponsPing);
try {
String cmdPing = "ping -c 2 "+host;
Runtime r = Runtime.getRuntime();
Process p = r.exec(cmdPing);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String inputLine;
String time_part = "";
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
while ((inputLine = in.readLine())!= null){
for(String time:listResponsPing){
if(time.contains("time=")){
String[] parts = time.split("time\\=");
time_part = parts[1];
myRef.push().setValue(time_part + " " + dateFormat.format(date));
}
}
listResponsPing.add(inputLine);
lstPing.setAdapter(adapterList);
}
Toast.makeText(this, " Command Execute Success", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, " Error: "+e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}
}
I'm new in firebase and android. My apps are about network testing. I have a problem in my PingActivity. I cannot insert the result from ping activity to Firebase. I've tried all the solution that I found. But its not working. Please help. Thank you.
The error at the code that I've comment.
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
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);
}
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?