<string xmlns="http://tempuri.org/">"User Already Exists !"</string> - android

"User Already Exists !" how to get inner body value like "User Already Exists !" I am using DOM Parser
please post any example

private EditText email, name, mobile, password;
TextView tv;
private Button submit;
// private String Email, Name, Mobile, Password;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email = (EditText) findViewById(R.id.email);
name = (EditText) findViewById(R.id.name);
mobile = (EditText) findViewById(R.id.mobile);
password = (EditText) findViewById(R.id.password);
submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1 = email.getText().toString().trim();
String s2 = name.getText().toString().trim();
String s3 = mobile.getText().toString().trim();
String s4 = password.getText().toString().trim();
if (s1.length() > 0 && s2.length() > 0) {
new ExecuteTask().execute(s1, s2, s3, s4);
email.setText(s1);
name.setText(s2);
mobile.setText(s3);
password.setText(s4);
} else {
}
}
});
}
public String PostData(String[] valuse) {
String responseText = "";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(
"https://www.businessbook4u.com/bbm4u.asmx/XUsrSignup?Email="+valuse[0]+"&Name="+valuse[1]+"&Mobile="+valuse[2]+"&Password="+valuse[3]);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
responseText = EntityUtils.toString(entity);
} catch (Exception e) {
System.out.println(e);
}
return responseText;
}
class ExecuteTask extends AsyncTask<String, String, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String res = PostData(params);
return res;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView t=(TextView)findViewById(R.id.message);
t.setText(s);
}
}
}
}

Related

SharedPreferences variable is only received and can be shown on a second execution

I searched all forums and solutions but none did the trick. I have an app that scans some text and receive the scan text and show it. This is the file where I get the scan results:
#Override
public void extractData(RomaniaIdFrontRecognizer.Result result) {
super.extractData(result);
savePreferences("selected", result.getLastName());
add(R.string.PPLastName, result.getLastName());
add(R.string.PPFirstName, result.getFirstName());
add(R.string.PPIdentityCardNumber, result.getCardNumber());
add(R.string.PPSeries, result.getIdSeries());
add(R.string.PPCNP, result.getCnp());
add(R.string.PPNationality, result.getNonMRZNationality());
add(R.string.PPPlaceOfBirth, result.getPlaceOfBirth());
add(R.string.PPAddress, result.getAddress());
add(R.string.PPIssuingAuthority, result.getIssuedBy());
add(R.string.PPSex, result.getNonMRZSex());
add(R.string.PPValidFrom, result.getValidFrom());
add(R.string.PPValidUntil, result.getValidUntil());
}
private void savePreferences(String key, String value){
SharedPreferences sharedPreferences = mContext.getSharedPreferences("weightSetting", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
This part is being executed because if I put a toast, the message shows.
And this is the file where I would want to receive the variable sent with sharedpreferences:
public class ResultActivity extends FragmentActivity implements
ResultFragment.IResultFragmentActivity,
FieldByFieldResultFragment.IFieldByFieldResultFragmentActivity {
String a;
String TempName, TempEmail ;
String e;
Bitmap bitmap;
ByteArrayOutputStream baos;
byte[] imageInByte;
private LayoutInflater mInflater;
Toast toast;
LoginDataBaseAdapter loginDataBaseAdapter;
EditText nume;
EditText prenume;
EditText nr;
EditText serie;
EditText cnp;
EditText nationalitate;
EditText loc;
EditText adresa;
EditText emis;
EditText sex;
EditText start;
EditText stop;
String usern;
public static final String EXTRAS_RESULT_TYPE = "EXTRAS_RESULT_TYPE";
public enum ResultType {
RECOGNIZER_BUNDLE,
FIELD_BY_FIELD_BUNDLE
}
protected ViewPager mPager;
protected RecognizerBundle mRecognizerBundle;
protected FieldByFieldBundle mFieldByFieldBundle;
protected ResultType mResultType;
private ArrayList<Recognizer> mRecognizersWithResult;
#SuppressLint("InlinedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setActivityContentView();
// loginDataBaseAdapter=new LoginDataBaseAdapter(getApplicationContext());
// loginDataBaseAdapter=loginDataBaseAdapter.open();
// String aa=loginDataBaseAdapter.getMagazin();
String s = loadPreferences("selected");
Toast.makeText(getApplicationContext(), s,Toast.LENGTH_LONG).show();
Intent intent = getIntent();
mResultType = (ResultType) intent.getSerializableExtra(EXTRAS_RESULT_TYPE);
mRecognizerBundle = new RecognizerBundle();
mFieldByFieldBundle = new FieldByFieldBundle();
if (mResultType == null) {
if (mRecognizerBundle.existsInIntent(intent)) {
mResultType = ResultType.RECOGNIZER_BUNDLE;
} else if (mFieldByFieldBundle.existsInIntent(intent)) {
mResultType = ResultType.FIELD_BY_FIELD_BUNDLE;
}
}
if (mResultType == null) {
throw new IllegalStateException("Results must be passed to ResultActivity!");
}
mPager = findViewById(R.id.resultPager);
switch (mResultType) {
case RECOGNIZER_BUNDLE:
mRecognizersWithResult = new ArrayList<>();
mRecognizerBundle.loadFromIntent(intent);
for ( Recognizer< Recognizer, Recognizer.Result > r : mRecognizerBundle.getRecognizers() ) {
if ( r.getResult().getResultState() != Recognizer.Result.State.Empty ) {
mRecognizersWithResult.add( r );
// String text = mRecognizersWithResult.get(0).toString();
// Toast.makeText(getApplicationContext(), text,Toast.LENGTH_LONG).show();
}
}
mPager.setAdapter(new RecognizerListFragmentAdapter(getSupportFragmentManager()));
break;
case FIELD_BY_FIELD_BUNDLE:
// mFieldByFieldBundle.loadFromIntent(intent);
// mPager.setAdapter(new FieldByFieldBundleFragmentAdapter(getSupportFragmentManager()));
// break;
}
TabPageIndicator indicator = findViewById(R.id.resultIndicator);
indicator.setViewPager(mPager);
indicator.setClipChildren(false);
}
#Override
protected void onResume() {
super.onResume();
// clear saved state to be sure that data is cleared from cache and from file when
// intent optimisation is used
mRecognizerBundle.clearSavedState();
mFieldByFieldBundle.clearSavedState();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mResultType == ResultType.RECOGNIZER_BUNDLE) {
mRecognizerBundle.saveState();
} else if (mResultType == ResultType.FIELD_BY_FIELD_BUNDLE) {
mFieldByFieldBundle.saveState();
}
}
public void setActivityContentView() {
setContentView(R.layout.result_menu);
}
private String loadPreferences(String key){
SharedPreferences sharedPreferences =getApplicationContext().getSharedPreferences("weightSetting", MODE_PRIVATE);
String load = sharedPreferences.getString(key, "");
return load;
}
#Override
public Recognizer< Recognizer, Recognizer.Result > getRecognizerAtPosition(int resultPosition) {
if (resultPosition < 0 || resultPosition >= mRecognizersWithResult.size()) {
throw new IllegalStateException("Recognizer with non empty result on requested position"
+ " does not exist. Possible cause is that recognizer bundle state has been lost"
+ " in intent transactions.");
}
//noinspection unchecked
return mRecognizersWithResult.get(resultPosition);
}
#Override
public FieldByFieldBundle getFieldByFieldBundle() {
return mFieldByFieldBundle;
}
private class RecognizerListFragmentAdapter extends FragmentPagerAdapter {
RecognizerListFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ResultFragment.newInstance(position);
}
#Override
public int getCount() {
return mRecognizersWithResult.size();
}
#Override
public CharSequence getPageTitle(int position) {
return ResultUtils.getRecognizerSimpleName(mRecognizersWithResult.get(position));
}
}
private class FieldByFieldBundleFragmentAdapter extends FragmentPagerAdapter {
FieldByFieldBundleFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return FieldByFieldResultFragment.newInstance();
}
#Override
public int getCount() {
return 1;
}
#Override
public CharSequence getPageTitle(int position) {
return ResultActivity.this.getString(R.string.title_field_by_field_results);
}
}
public void footerButtonClickHandler(View view) {
// String sessionId= getIntent().getStringExtra("test");
// Toast.makeText(getApplicationContext(), "da", Toast.LENGTH_LONG).show();
// new RegisterAsyntaskNew().execute();
ImageView img=(ImageView) findViewById(R.id.resultValueee);
// img.buildDrawingCache();
// Bitmap bitmap = img.getDrawingCache();
BitmapDrawable drawable = (BitmapDrawable) img.getDrawable();
Bitmap bitmap = drawable.getBitmap();
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageInByte = baos.toByteArray();
// RomanianIDFrontSideRecognitionResultExtractor myActivity2 = new RomanianIDFrontSideRecognitionResultExtractor();
// myActivity2.InsertData();
Img(imageInByte,e);
// InsertData(nume.getText().toString(), prenume.getText().toString(), nr.getText().toString(), serie.getText().toString(),cnp.getText().toString(),nationalitate.getText().toString(), loc.getText().toString(),adresa.getText().toString(),emis.getText().toString(),sex.getText().toString(),start.getText().toString(),stop.getText().toString(),usern);
finish();
}
public void InsertData(final String nume, final String prenume, final String nr, final String serie, final String cnp, final String nationalitate
, final String locn, final String adresa, final String emis, final String sex, final String start, final String sfarsit,final String username){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String name = nume ;
String pren = prenume ;
String nr1 = nr;
String serie1 = serie ;
String cnp1 = cnp ;
String nat = nationalitate ;
String locn1 = locn ;
String adresa1 = adresa ;
String emis1 = emis ;
String sex1 = sex ;
String start1 = start ;
String sfarsit1 = sfarsit ;
String user1 = username ;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("email", pren));
nameValuePairs.add(new BasicNameValuePair("nr", nr1));
nameValuePairs.add(new BasicNameValuePair("serie", serie1));
nameValuePairs.add(new BasicNameValuePair("cnp", cnp1));
nameValuePairs.add(new BasicNameValuePair("nat", nat));
nameValuePairs.add(new BasicNameValuePair("locn", locn1));
nameValuePairs.add(new BasicNameValuePair("adresa", adresa1));
nameValuePairs.add(new BasicNameValuePair("emis", emis1));
nameValuePairs.add(new BasicNameValuePair("sex", sex1));
nameValuePairs.add(new BasicNameValuePair("start", start1));
nameValuePairs.add(new BasicNameValuePair("sfarsit", sfarsit1));
nameValuePairs.add(new BasicNameValuePair("username", user1));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("url");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
a = EntityUtils.toString(httpResponse.getEntity());
// return EntityUtils.toString(httpEntity).trim();
ResultActivity.this.runOnUiThread(new Runnable() {
public void run() {
// Toast.makeText(ResultActivity.this, a, Toast.LENGTH_LONG).show();
toast = Toast.makeText(ResultActivity.this, a, Toast.LENGTH_SHORT);
TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
v.setTextColor(Color.parseColor("#66ff33"));
int toastDuration = 5000;
CountDownTimer countDownTimer;
countDownTimer = new CountDownTimer(toastDuration, 1000) {
public void onTick(long millisUntilFinished) {
toast.show();
}
public void onFinish() {
toast.cancel();
}
};
toast.show();
countDownTimer.start();
}
});
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "Data Inserted Successfully";
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(nume, prenume,nr,serie,cnp,nationalitate,locn,adresa,emis,sex,start,sfarsit,username);
}
public void Img(final byte[] data,final String cnpimg){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String cnp1 = cnpimg ;
Bitmap bitmapOrg = BitmapFactory.decodeByteArray(data, 0, data.length);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
String ba1 = Base64.encodeBytes(ba);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image", ba1));
nameValuePairs.add(new BasicNameValuePair("cnp", cnp1));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://promotii.grupsapte.ro/php/scanid/img.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// a = EntityUtils.toString(httpResponse.getEntity());
// return EntityUtils.toString(httpEntity).trim();
// ResultActivity.this.runOnUiThread(new Runnable() {
// public void run() {
// Toast.makeText(ResultActivity.this, a, Toast.LENGTH_LONG).show();
// }
// });
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "Data Inserted Successfully";
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute();
}
}
The send-receive variable with shared preferences worked but now, i don't know the cause, first time I get a null variable and if I try it again then I receive what I scan first. So, the variable is shown only the second time with the value scan for the first time. Even if I try to put a simple text and send it, it will show only the second time I make the action. But I repeat, the file is getting executed because if I put a toast, it will show. I think that the receiving of the shared preferences variable is done first and then the code from the first file is being executed. I tried to put the code in oncreate, onresume but nothing did the trick. Any help would be much appreciated.
The solution for me was to put a delay of 1 second for the process of receiving thorugh shared preferences. See below:
#Override
protected void onResume() {
super.onResume();
// clear saved state to be sure that data is cleared from cache and from file when
// intent optimisation is used
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
// Your logic here...
// When you need to modify a UI element, do so on the UI thread.
// 'getActivity()' is required as this is being ran from a Fragment.
ResultActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
String a = loadPreferences("nume");
String b= loadPreferences("prenume");
String c= loadPreferences("nr");
String d= loadPreferences("serie");
e= loadPreferences("cnp");
String f= loadPreferences("nationalitate");
String g= loadPreferences("locn");
String h= loadPreferences("adresa");
String i= loadPreferences("emis");
String j= loadPreferences("sex");
String k= loadPreferences("start");
String l= loadPreferences("sfarsit");
usern= "";
String s = Normalizer.normalize(f, Normalizer.Form.NFD);
String bla = s.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
String t = Normalizer.normalize(h, Normalizer.Form.NFD);
String bla1 = t.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
String a1 = Normalizer.normalize(a, Normalizer.Form.NFD);
String bla2 = a1.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
String b1 = Normalizer.normalize(b, Normalizer.Form.NFD);
String bla3 = b1.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
String g1 = Normalizer.normalize(g, Normalizer.Form.NFD);
String bla4 = g1.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
nume = (EditText) findViewById(R.id.nume);
nume.setText(bla2);
prenume = (EditText) findViewById(R.id.prenume);
prenume.setText(bla3);
nr = (EditText) findViewById(R.id.nrserie);
nr.setText(c);
serie = (EditText) findViewById(R.id.serie);
serie.setText(d);
cnp = (EditText) findViewById(R.id.cnp);
cnp.setText(e);
nationalitate = (EditText) findViewById(R.id.nationalitate);
nationalitate.setText(bla);
loc = (EditText) findViewById(R.id.loc);
loc.setText(bla4);
adresa = (EditText) findViewById(R.id.adresa);
adresa.setText(bla1);
emis = (EditText) findViewById(R.id.emis);
emis.setText(i);
sex = (EditText) findViewById(R.id.sexx);
sex.setText(j);
start = (EditText) findViewById(R.id.start);
start.setText(k);
stop = (EditText) findViewById(R.id.stop);
stop.setText(l);
// String s = loadPreferences("selected");
// Toast.makeText(getApplicationContext(), a,Toast.LENGTH_LONG).show();
}
});
}
}, 1000); // End of your timer code.
mRecognizerBundle.clearSavedState();
mFieldByFieldBundle.clearSavedState();
}

Move One activity to Another Activity using function

MainActivity.java
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_name = (EditText) findViewById(R.id.user_name);
password = (EditText)findViewById(R.id.password);
submit_btn = (Button) findViewById(R.id.submit);
submit_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Sender s = new Sender(v.getContext(),urlAddress,user_name,password);
s.execute();
cxt = getApplicationContext();
}
});
}
public void GoUserActivity(){
Intent i = new Intent(MainActivity.this,com.example.prakash.cinihive.UserActivity.class);
startActivity(i);
}
}
Sender.java
package com.example.prakash.cinihive;
public class Sender extends AsyncTask<Void,Void,String> {
Context c;
String urlAddress;
EditText user_name,password;
String UserName,Password;
ProgressDialog pd;
MainActivity main = new MainActivity();
public Sender(Context c, String urlAddress, EditText user_name, EditText password) {
this.c = c;
this.urlAddress = urlAddress;
this.user_name = user_name;
this.password = password;
UserName = user_name.getText().toString();
Password = password.getText().toString();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("send");
pd.setMessage("Sending..Please wait");
pd.show();
}
#Override
protected String doInBackground(Void... voids) {
return this.send();
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
pd.dismiss();
if(response !=null){
//Toast.makeText(c,response,Toast.LENGTH_LONG).show();
//Log.d("Response",response);
if(response.equals("false")){
Toast.makeText(c,"Invalid Credentials",Toast.LENGTH_LONG).show();
}
else{
main.GoUserActivity();
//Toast.makeText(c,response,Toast.LENGTH_LONG).show();
}
user_name.setText("");
password.setText("");
}
else{
Toast.makeText(c,"Un succesfullll",Toast.LENGTH_LONG).show();
}
}
public String send(){
HttpURLConnection con = Connector.connect(urlAddress);
//Toast.makeText(c,con.toString(),Toast.LENGTH_LONG).show();
if(con==null){
Toast.makeText(c,"Connection Null",Toast.LENGTH_LONG).show();
return null;
}
try{
// Log.d("Connection status","Connection not null");
OutputStream os = con.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
bw.write(new DataPack(UserName,Password).Packdata());
bw.flush();
bw.close();
os.close();
int responseCode = con.getResponseCode();
Log.d("MYINT","Response Id :"+responseCode);
if(responseCode==con.HTTP_OK){
Log.d("Response code","Response code success");
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer response = new StringBuffer();
String line;
while((line=br.readLine())!=null){
response.append(line);
}
br.close();
return response.toString();
}else{
Log.d("Response code","Failure");
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This is my code My problem was Intent Statement Not working in GoUserActivity funtion
At the same time Intent Statement Working well in OnCreate function.
When I try to run inside GoUserActivity,it will raise the runtime error(NullPoniterException "Intent i = new Intent(MainActivity.this,com.example.prakash.cinihive.UserActivity.class);")
I think you'll find things work better if you move your AsyncTask inside MainActivity as an inner class. You'll be able to call GoUserActivity() without having to new another instance of MainActivity, which you should never do.

Sentence is not inserted into online database not from all devices

When I insert a sentence from my android phone, the data is not inserted to my database. But when I use my friend's mobile, it works successfully.
It actually does not work when I use space between two words. But, when I use a single word, it works.
I use VARCHAR in my database.
Here is my java code:
EditText cname, location, num, email, pass;
Button submit;
private static final String REGISTER_URL = "https://alex456.000webhostapp.com/Register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
cname = (EditText)findViewById(R.id.editText8);
location = (EditText)findViewById(R.id.editText9);
num = (EditText)findViewById(R.id.editText10);
email = (EditText)findViewById(R.id.editText11);
pass = (EditText)findViewById(R.id.editText3);
submit = (Button) findViewById(R.id.button6);
submit.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
#Override
public void onClick(View v) {
registerUser();
}
});
}
private void registerUser(){
String CNAME, LOCATION, NUM, PASS ,EMAIL;
CNAME = cname.getText().toString().trim();
LOCATION = location.getText().toString().trim();
NUM = num.getText().toString().trim();
EMAIL = email.getText().toString().trim();
PASS = pass.getText().toString().trim();
register(CNAME, LOCATION, NUM, EMAIL, PASS);
}
private void register(String CNAME,String LOCATION,String NUM,String EMAIL, String PASS ) {
String urlSuffix = "?cnamePHP=" + CNAME + "&locationPHP=" + LOCATION + "&numPHP=" + NUM + "&emailPHP=" + EMAIL + "&passPHP=" + PASS;
class RegisterUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(RegisterActivity.this, "Please Wait", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String s = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(REGISTER_URL + s);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Intent i;
i = new Intent(RegisterActivity.this, RegisterActivity.class);
RegisterActivity.this.startActivity(i);
}
}
RegisterUser ur = new RegisterUser();
ur.execute(urlSuffix);
}
}

need help, got confuse with AsyncTask

I'm new in android and i need to make AsyncTask, so my application can work on ICS. But after I read tutorials i still got confuse. Anyone, please help me to fix my code, i don't know what and where i must put in AsyncTask with my code like this. thank you
Login.java
package com.karismaelearning;
public class Login extends Activity {
public Koneksi linkurl;
String SERVER_URL;
private Button login, register, setting;
private EditText username, password;
public ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
setting = (Button)findViewById(R.id.bsetting);
login = (Button) findViewById(R.id.login);
register = (Button) findViewById(R.id.reg);
username = (EditText) findViewById(R.id.uname);
password = (EditText) findViewById(R.id.pass);
setting.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intentSet = new Intent(Login.this, UrlSetting.class);
startActivity(intentSet);
}
});
register.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intentReg = new Intent(Login.this, Register.class);
startActivity(intentReg);
}
});
login.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String response = null;
String mUsername = username.getText().toString();
String mPassword = password.getText().toString();
response = tryLogin(mUsername, mPassword).trim();
Log.d("Check","Here");
Log.d("Response",response);
if(response.toLowerCase().contains("berhasil"))
{
String nama = username.getText().toString();
Intent newIntent = new Intent(Login.this, MainPage.class);
Bundle bundle = new Bundle();
bundle.putString("nama", nama);
newIntent.putExtras(bundle);
startActivityForResult(newIntent, 0);
}
else
{
//Optional
//Kalau bisa dibuat constant untuk menghindari salah penulisan
String RoleError = "ROLE SALAH";
String UserError = "USER SALAH";
createDialog("Maaf", response.equals(RoleError) ? "Role Anda bukan Student!" : "Username Atau Password Salah!");
}
}
});
}
protected String tryLogin(String mUsername, String mPassword)
{
Log.d(" TryLoginCheck ","Here");
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String temp=null;
String parameters = "username="+mUsername+"&password="+mPassword;
System.out.println("UserName"+mUsername+"\n"+"password"+mPassword);
Log.d("Parameters",parameters);
try
{
;
linkurl = new Koneksi(this);
SERVER_URL = linkurl.getUrl();
SERVER_URL += "/mobile/Login.php";
url = new URL(SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
temp=sb.toString();
Log.d("Temp",temp);
response = sb.toString();
Log.d("Response",response);
Log.d("Sb Value",sb.toString());
isr.close();
reader.close();
}
catch(IOException e) {
Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();
}
return response;
}
class LoginTask extends AsyncTask<String, Void, Integer> {
public LoginTask(Login activity, ProgressDialog progressDialog){
}
#Override
protected void onPreExecute(){
progressDialog.show();
}
#Override
protected Integer doInBackground(String... arg0){
}
private void createDialog(String title, String text) {
AlertDialog ad = new AlertDialog.Builder(this)
.setPositiveButton("Ok", null)
.setTitle(title)
.setMessage(text)
.create();
ad.show();
}
}
login.java - edited -> is it like this?
package com.karismaelearning;
public class Login extends Activity {
public Koneksi linkurl;
String SERVER_URL;
private Button login, register, setting;
private EditText username, password;
public ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
setting = (Button)findViewById(R.id.bsetting);
login = (Button) findViewById(R.id.login);
register = (Button) findViewById(R.id.reg);
username = (EditText) findViewById(R.id.uname);
password = (EditText) findViewById(R.id.pass);
setting.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intentSet = new Intent(Login.this, UrlSetting.class);
startActivity(intentSet);
}
});
register.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intentReg = new Intent(Login.this, Register.class);
startActivity(intentReg);
}
});
login.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new LoginTask().execute();
}
});
}
protected String tryLogin(String mUsername, String mPassword){
Log.d(" TryLoginCheck ","Here");
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String temp=null;
String parameters = "username="+mUsername+"&password="+mPassword;
System.out.println("UserName"+mUsername+"\n"+"password"+mPassword);
Log.d("Parameters",parameters);
try{
linkurl = new Koneksi(this);
SERVER_URL = linkurl.getUrl();
SERVER_URL += "/mobile/Login.php";
url = new URL(SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
temp=sb.toString();
Log.d("Temp",temp);
response = sb.toString();
Log.d("Response",response);
Log.d("Sb Value",sb.toString());
isr.close();
reader.close();
}
catch(IOException e) {
Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();
}
return response;
}
public class LoginTask extends AsyncTask<String, Void, String> {
String response = null;
public LoginTask() {
}
#Override
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
String mUsername = username.getText().toString();
String mPassword = password.getText().toString();
response = tryLogin(mUsername, mPassword).trim();
return response;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
Log.d("Check","Here");
Log.d("Response",response);
if(response.toLowerCase().contains("berhasil")){
String nama = username.getText().toString();
Intent newIntent = new Intent(Login.this, MainPage.class);
Bundle bundle = new Bundle();
bundle.putString("nama", nama);
newIntent.putExtras(bundle);
startActivityForResult(newIntent, 0);
}
else{
//Optional
//Kalau bisa dibuat constant untuk menghindari salah penulisan
String RoleError = "ROLE SALAH";
String UserError = "USER SALAH";
createDialog("Maaf", response.equals(RoleError) ? "Role Anda bukan Student!" : "Username Atau Password Salah!");
}
}
}
private void createDialog(String title, String text) {
AlertDialog ad = new AlertDialog.Builder(this)
.setPositiveButton("Ok", null)
.setTitle(title)
.setMessage(text)
.create();
ad.show();
}
}
use like that
class LoginTask extends AsyncTask<String, Void, Integer> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog.show();
}
#Override
protected Integer doInBackground(String... arg0)
{
// do all login request here only
}
#Override
protected String onPostExecute(String arg0)
{
progressDialog.dismiss();
// get the response here and show where you want
}
Put in your OnClick method
new LoginTask().execute(stringParam);
to execute your method after clicking element.
In short:
You need to put your tryLogin() code into the doInBackground() method of the AsyncTask.
Incidentally, you should really take a look at your variable naming, the scope of your methods etc. Does tryLogin() really need to be protected? mUsername and mPassword are not member variables of the class, they are local variables.
http://source.android.com/source/code-style.html
Try below code:
public class Login extends Activity {
public Koneksi linkurl;
String SERVER_URL;
private Button login, register, setting;
private EditText username, password;
public ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
setting = (Button)findViewById(R.id.bsetting);
login = (Button) findViewById(R.id.login);
register = (Button) findViewById(R.id.reg);
username = (EditText) findViewById(R.id.uname);
password = (EditText) findViewById(R.id.pass);
setting.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intentSet = new Intent(Login.this, UrlSetting.class);
startActivity(intentSet);
}
});
register.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intentReg = new Intent(Login.this, Register.class);
startActivity(intentReg);
}
});
login.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new LoginTask.execute();
}
});
}
protected String tryLogin(String mUsername, String mPassword)
{
Log.d(" TryLoginCheck ","Here");
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String temp=null;
String parameters = "username="+mUsername+"&password="+mPassword;
System.out.println("UserName"+mUsername+"\n"+"password"+mPassword);
Log.d("Parameters",parameters);
try
{
;
linkurl = new Koneksi(this);
SERVER_URL = linkurl.getUrl();
SERVER_URL += "/mobile/Login.php";
url = new URL(SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
temp=sb.toString();
Log.d("Temp",temp);
response = sb.toString();
Log.d("Response",response);
Log.d("Sb Value",sb.toString());
isr.close();
reader.close();
}
catch(IOException e)
{
Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();
}
return response;
}
class LoginTask extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private Login activity;
private int id = -1;
public LoginTask(Login activity, ProgressDialog progressDialog)
{
this.activity = activity;
this.progressDialog = progressDialog;
}
#Override
protected void onPreExecute()
{
progressDialog.show();
}
#Override
protected Integer doInBackground(String... arg0)
{
String mUsername = username.getText().toString();
String mPassword = password.getText().toString();
response = tryLogin(mUsername, mPassword).trim();
return response;
}
protected Void onPostExecute(String result){
super.onPostExecute(result);
if(response.toLowerCase().contains("berhasil"))
{
String nama = username.getText().toString();
Intent newIntent = new Intent(Login.this, MainPage.class);
Bundle bundle = new Bundle();
bundle.putString("nama", nama);
newIntent.putExtras(bundle);
startActivityForResult(newIntent, 0);
}
else
{
String RoleError = "ROLE SALAH";
String UserError = "USER SALAH";
createDialog("Maaf", response.equals(RoleError) ? "Role Anda bukan Student!" : "Username Atau Password Salah!");
}
}
}
private void createDialog(String title, String text) {
AlertDialog ad = new AlertDialog.Builder(this)
.setPositiveButton("Ok", null)
.setTitle(title)
.setMessage(text)
.create();
ad.show();
}
}

How to use ProgressBar to show a spinner while waiting a httpResponse from server

I'm trying to show a loading icon to the user when the application makes a query to online Database. I've tried using a AnimationDrawable (I gave up because there was no need of a custom icon), ProgressDialog and ProgressBar.
The ProgressBar seems most appropriate, since I don't want a message, just a spinning icon. But I can not even make a ProgressBar appear on the screen, doesn't matter where I call it.
I've got the ProgressDialog appearing in screen, but it only appears after the server's response, and if I use dismiss() or cancel() it doesn't even appear at all.
I've had any success using AsyncTasks or Threads.
In the app, there is a class JogarActivity.java that attemps to show a list of options. It receives some parameters like the user id, and calls UserFunctions:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jogar_layout);
Intent in = getIntent();
String url = this.getString(R.string.urlSite);
ArrayList<HashMap<String, String>> respostaList = new ArrayList<HashMap<String, String>>();
String idt = in.getStringExtra(TAG_ID);
primeiraPergunta = in.getBooleanExtra(TAG_PRIMEIRAPERGUNTA, true);
TextView insertPergunta = (TextView) findViewById(R.id.insertPergunta);
ListView insertRespostas = (ListView) findViewById(R.id.listResposta);
SharedPreferences settings = getSharedPreferences("PREFS_LOGIN", MODE_PRIVATE);
Integer idUsuario = settings.getInt("idUsuario", 0);
String idUser = idUsuario.toString();
if (primeiraPergunta){
UserFunctions userFunction = new UserFunctions();
json = userFunction.getJogar(idt, idUser);
}else{
try {
json = new JSONArray(in.getStringExtra(TAG_JSON));
json = json.getJSONArray(2);
} catch (JSONException e) {
e.printStackTrace();
}
}
Below is the getJogar function in userFunctions:
public JSONArray getJogar(String categoria, String usuarioId){
List params = new ArrayList();
params.add(new BasicNameValuePair("categoria", categoria));
params.add(new BasicNameValuePair("idUsuario", usuarioId));
JSONArray json = jsonParser.getJSONFromUrl(perguntaURL, params);
return json;
}
JSONParser.java is the class that makes the httpRequest:
public JSONArray getJSONFromUrl(String url, List params) {
// Making HTTP request
try {
// defaultHttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// json = EntityUtils.toString(httpEntity);
// HttpEntity httpEntity2 = httpEntity;
json = EntityUtils.toString(httpEntity);
// is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//then makes the JSON manipulation
As long as JSONParser and userFunctions aren't activities, I couldn't use ProgressDialogs inside them (Can't get the application context). All server requests are made in JSONParser.java, that's why i've first tried to put the ProgressDialog/ProgressBar there.
The closest that i've reached was using this code in JogarActivity (It shows the ProgressDialog, but after getting server's response. And if I use dismiss, it doesn't even appears)
final ProgressDialog loader = new ProgressDialog(JogarActivity.this);
loader.show();
//...the if-else code i've pasted above
loader.dismiss();
Even using runOnUiThread it doesn't works! I'm getting without options...
Thanks for all help.
this worked:
public class RegisterActivity extends Activity{
EditText reg_fullname;
EditText reg_email;
EditText reg_login;
EditText reg_password;
EditText reg_password2;
Spinner reg_country;
Spinner reg_genre;
EditText reg_birthday;
EditText reg_promocode;
Button btnRegister;
Context ctx = this;
ProgressDialog pDialog;
JSONArray json;
String status;
String msg;
String fullname;
String email;
String login;
String password;
String password2;
String country;
String genre;
String birthday;
String promocode;
boolean finishActivity = false;
/**
* #see android.app.Activity#onCreate(Bundle)
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
TextView loginScreen = (TextView) findViewById(R.id.link_to_login);
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Closing registration screen
// Switching to Login Screen/closing register screen
finish();
}
});
reg_fullname = (EditText) findViewById(R.id.reg_fullname);
reg_email = (EditText) findViewById(R.id.reg_email);
reg_login = (EditText) findViewById(R.id.reg_login);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_password2 = (EditText) findViewById(R.id.reg_password2); //confirmação de senha
reg_country = (Spinner) findViewById(R.id.reg_country);
reg_genre = (Spinner) findViewById(R.id.reg_genre);
reg_birthday = (EditText) findViewById(R.id.reg_birthday);
reg_promocode = (EditText) findViewById(R.id.reg_promocode);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fullname = reg_fullname.getText().toString();
email = reg_email.getText().toString();
login = reg_login.getText().toString();
password = reg_password.getText().toString();
password2 = reg_password2.getText().toString();
country = reg_country.getSelectedItem().toString();
genre = reg_genre.getSelectedItem().toString();
birthday = reg_birthday.getText().toString();
promocode = reg_promocode.getText().toString();
boolean validation = true;
String message = "Campo de preencimento obrigatório";
if(fullname.equalsIgnoreCase("")){
reg_fullname.setError(message);
validation = false;
}
if(email.equalsIgnoreCase("")){
reg_email.setError(message);
validation = false;
}
if(!email.matches(".*#.*")){
reg_email.setError("O endereço de email não é válido");
validation = false;
}
if(login.equalsIgnoreCase("")){
reg_login.setError(message);
validation = false;
}
if(password.equalsIgnoreCase("")){
reg_password.setError(message);
validation = false;
}
if(password2.equalsIgnoreCase("")){
reg_password2.setError(message);
validation = false;
}
if(!password.equals(password2)){
reg_password2.setError("A confirmação de senha não confere");
validation = false;
}
if(birthday.equalsIgnoreCase("")){
reg_birthday.setError(message);
validation = false;
}
SimpleDateFormat bd = new SimpleDateFormat("dd/MM/yyyy");
if(bd.parse(birthday, new ParsePosition(0)) == null){
reg_birthday.setError("Esta data não é válida! Preencha novamente, usando o formato dd/mm/aaaa");
validation = false;
}
if(validation){
new Register().execute();
}
}
});
}
class Register extends AsyncTask<Void, Void, JSONArray>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ctx);
pDialog.setMessage("Aguarde...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected JSONArray doInBackground(Void... params) {
UserFunctions userFunction = new UserFunctions();
json = userFunction.newUser(fullname, email, login, password, country, genre, birthday, promocode);
return json;
}
protected void onPostExecute(JSONArray result) {
// dismiss the dialog once done
pDialog.dismiss();
final AlertDialog alertDialog = new AlertDialog.Builder(
RegisterActivity.this).create();
try {
status = json.getString(0);
msg = json.getString(1);
Log.d("Status", status);
} catch (JSONException e) {
Log.e("RegisterActiviry", "Error converting result " + e.toString());
e.printStackTrace();
status = null;
}
if (status.equalsIgnoreCase("erro")){
alertDialog.setTitle("Erro");
alertDialog.setMessage(msg);
}else if (status.equalsIgnoreCase("sucesso")){
alertDialog.setTitle("Sucesso!");
alertDialog.setMessage(msg);
finishActivity = true;
}else{
alertDialog.setTitle("Erro");
alertDialog.setMessage("Não foi possível realizar seu cadastro, tente novamente mais tarde.");
}
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if(finishActivity){
finish();
}else{
alertDialog.dismiss();
}
}
});
alertDialog.show();
}
}
}

Categories

Resources