Here this is my code. It looks a bit complicated but it's working all fine. I just want to know how can I create when I click btnCreateProduct it should validate required edit text field and where to add those code?
package com.prinsapps.whatson;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.prinsapps.whatson.Addevent.CreateNewProduct;
public class Addevent extends Activity implements OnClickListener {
private ImageButton ib;
private Calendar cal;
private int day;
private int month;
private int year;
private EditText et;
//Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputDesc;
EditText inputCountry;
EditText inputdate;
EditText inputLink;
EditText inputOrg;
// url to create new product
private static String url_create_product = "http://-----------";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_event);
//Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputDesc = (EditText) findViewById(R.id.inputDesc);
inputCountry = (EditText) findViewById(R.id.inputCountry);
inputdate = (EditText) findViewById(R.id.inputdate);
inputLink = (EditText) findViewById(R.id.inputLink);
inputOrg = (EditText) findViewById(R.id.inputOrg);
// mDateButton = (Button) findViewById(R.id.date_button);
ib = (ImageButton) findViewById(R.id.imageButton1);
cal = Calendar.getInstance();
day = cal.get(Calendar.DAY_OF_MONTH);
month = cal.get(Calendar.MONTH);
year = cal.get(Calendar.YEAR);
et = (EditText) findViewById(R.id.inputdate);
ib.setOnClickListener(this);
// Create button
Button btnCreateProduct = (Button)
findViewById(R.id.btnCreateProduct);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
#Override
public void onClick(View v) {
showDialog(0);
}
#Override
#Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new
DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
et.setText(selectedYear+"/"+(selectedMonth+1)+"/"+selectedDay);
}
};
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Addevent.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
*
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String description = inputDesc.getText().toString();
String country = inputCountry.getText().toString();
String date = inputdate.getText().toString();
String link = inputLink.getText().toString();
String org = inputOrg.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("description", description));
params.add(new BasicNameValuePair("country", country));
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("link", link));
params.add(new BasicNameValuePair("org", org));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(),
AllProductsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
use editText watcher
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void afterTextChanged(Editable editable) {
//Add your validations here
}
});
Yes it working fine now
#Override
public void onClick(View view) {
if ( ( !inputName.getText().toString().equals("")) &&
( !inputDesc.getText().toString().equals("")) &&
( !inputCountry.getText().toString().equals("")) &&
( !inputdate.getText().toString().equals(""))
)
{
// creating new product in background thread
new CreateNewProduct().execute();
}
else if ( ( !inputName.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Please Enter Event Name", Toast.LENGTH_SHORT).show();
}
else if ( ( !inputDesc.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Please Enter Event Description", Toast.LENGTH_SHORT).show();
}
else if ( ( !inputCountry.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Please Enter Place or Country", Toast.LENGTH_SHORT).show();
}
else if ( ( !inputdate.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Please Select Date When Event Start", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),
"Event Details are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
As I'm assuming, that you don't want to get empty your Textfield empty if you creating a product, I'd suggest to check wether the Strings of your EditTexts are null or empty.
This could look like this:
if(inputName.getText().equals("") || inputName.getText().equals(null)){
//Maybe show some message, that the given field ist required to be filled out
}
I would suggest to add this into your onClick() Method, or write an extra method to check wether an EditText is empty and return a boolean value. This could look like this:
public boolean notEmpty(EditText et){
if(et.getText().equals("") || et.getText().equals(null)){
return false;
}
return true;
}
And then check this for every EditText et before you create a new product.
Related
I am having trouble trying to get my andoid app to return a list view of all search results returned from a PHP files. I am using a wamp server to host the php files then I call them in the application using Volley. My problem is I can't get it to work with multiple return values. I have tried many different ways using videos online and resources from this site but i cant seem to get to work. This is my first Android application so I am new enough of the idea of a list view and json.
package com.example.mullally.newloginregister;
import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class HomeScreen extends AppCompatActivity {
String status = "";
ArrayAdapter<String> adapter;
ArrayList<String> items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
final TextView createLink = (TextView) findViewById(R.id.tvCreate);
final TextView lostLink = (TextView) findViewById(R.id.tvLost);
final TextView foundLink = (TextView) findViewById(R.id.tvFound);
final Button btTest = (Button) findViewById(R.id.btTest);
createLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(HomeScreen.this, CreateAdvert.class);
HomeScreen.this.startActivity(registerIntent);
}
});
lostLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status="Lost";
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String title = jsonResponse.getString("title");
String location = jsonResponse.getString("location");
Intent intent = new Intent(HomeScreen.this, BrowseLost.class);
intent.putExtra("title", title);
intent.putExtra("location", location);
HomeScreen.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(HomeScreen.this);
builder.setMessage("Something Went Wrong")
.setNegativeButton("Back", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
BrowseRequest browseRequest = new BrowseRequest(status, responseListener);
RequestQueue queue = Volley.newRequestQueue(HomeScreen.this);
queue.add(browseRequest);
}
});
foundLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status = "Found";
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String title = jsonResponse.getString("title");
String location = jsonResponse.getString("location");
Intent intent = new Intent(HomeScreen.this, BrowseFound.class);
intent.putExtra("title", title);
intent.putExtra("location", location);
HomeScreen.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(HomeScreen.this);
builder.setMessage("Something Went Wrong")
.setNegativeButton("Back", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
BrowseRequest browseRequest = new BrowseRequest(status, responseListener);
RequestQueue queue = Volley.newRequestQueue(HomeScreen.this);
queue.add(browseRequest);
}
});
btTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status = "Found";
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String title = jsonResponse.getString("title");
String description = jsonResponse.getString("description");
String location = jsonResponse.getString("location");
String status = jsonResponse.getString("status");
String category = jsonResponse.getString("category");
Intent intent = new Intent(HomeScreen.this, ViewAdvert.class);
intent.putExtra("title", title);
intent.putExtra("description", description);
intent.putExtra("location", location);
intent.putExtra("status", status);
intent.putExtra("category", category);
HomeScreen.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(HomeScreen.this);
builder.setMessage("Something Went Wrong")
.setNegativeButton("Back", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
ViewRequest viewRequest = new ViewRequest(status, responseListener);
RequestQueue queue = Volley.newRequestQueue(HomeScreen.this);
queue.add(viewRequest);
}
});
This is the home screen. When a textview is clicked it would launch a request using volley in a seperate request class it is supposed to then return values add them to a json response opject and pass them into the Browse Lost class where it is then added to a listView.
This is the Request class:
package com.example.mullally.newloginregister;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
/**
* Created by mullally on 14/04/2016.
*/
public class BrowseRequest extends StringRequest {
//192.168.11.2
private static final String BROWSE_REQUEST_URL = "http://192.168.11.5/android_content/GetAdvert.php";
private Map<String,String> params;
public BrowseRequest(String status, Response.Listener<String> listener){
super(Request.Method.POST, BROWSE_REQUEST_URL,listener, null);
params=new HashMap<>();
params.put("status", status);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
And this is the activity that is launched to display the list :
package com.example.mullally.newloginregister;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class BrowseLost extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browse_lost);
final ListView listView = (ListView) findViewById(R.id.listView);
final Intent intent= getIntent();
String title = intent.getStringExtra("title");
String location = intent.getStringExtra("location");
String details = title + " Location: " + location;
List<String> foundArray = new ArrayList<>();
foundArray.add(details);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_2, android.R.id.text1, foundArray);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :" + itemPosition + " ListItem : " + itemValue, Toast.LENGTH_LONG)
.show();
}
});
}
}
So basically I am trying to populate the listview with all values returned from the PHP. The php encodes the values into a json response eg.
[{"title":"Phone Found","location":"Dublin 6"},{"title":"test","location":"Dublin"},{"title":"dog","location":"Dublin 1"},{"title":"new","location":"Dublin 6W"}]
I have created a LoginActivity with the inbuilt template under new activity of Android Studio. I am using a SqlDatabase with PHP script for login purpose using post method.When i execute this code i get 2 errors:
1) Error:(370, 9) error: method does not override or implement a method from a supertype
C:\Users\Chethan\AndroidStudioProjects\CleanMyChennai\app\src\main\java\com\exa mple\chethan\myapplication\LoginPage.java
2) Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Compilation failed; see the compiler error output for details.
How to fix these two errors. by the way i am a beginner in java coding.
Plz help me if you find where i have i gone wrong.. I haven't found any tutorial that makes use of Default "LoginActivity" layout provided in Android Studio. i want to connect loginactivity.java along with PHP-MySql connection
package com.example.chethan.myapplication;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import static android.Manifest.permission.READ_CONTACTS;
import static java.net.URLEncoder.encode;
/**
* A login screen that offers login via email/password.
*/
public class LoginPage extends AppCompatActivity implements LoaderCallbacks<Cursor> {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[]{
"foo#example.com:hello", "bar#example.com:world"
};
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
// Set up the login form.
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
private void populateAutoComplete() {
if (!mayRequestContacts()) {
return;
}
getLoaderManager().initLoader(0, null, this);
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
#Override
#TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
});
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
populateAutoComplete();
}
}
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
// mAuthTask.execute((Void) null);
mAuthTask.execute();
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("#");
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
}
/**
* Shows the progress UI and hides the login form.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginPage.this,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
mEmailView.setAdapter(adapter);
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<String, String, String> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
#Override
protected String doInBackground(String... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
//Thread.sleep(2000);
String username = (String)params[0];
String password = (String)params[1];
String link="http://localhost/login.php";
String data = encode("username", "UTF-8") + "=" + encode(username, "UTF-8");
data += "&" + encode("password", "UTF-8") + "=" + encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}
catch (Exception e) {
//return false;
return new String("Exception: " + e.getMessage());
}
/*
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
*/
/* TODO: register the new account here. */
/* return true; */
}
#Override
protected void onPostExecute(final Boolean success) {
// super.onPostExecute(success);
mAuthTask = null;
showProgress(false);
if (success) {
finish();
Toast.makeText(getApplicationContext(),"login success",Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(LoginPage.this,Authorities.class);
LoginPage.this.startActivity(myIntent);
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
I saw your problem, is in your onPostExecute have Boolean success as a parameter, change the type of success to String success.
You are returning String from doInBackground
Final implementation should look like this:
protected void onPostExecute(final String success) {
// super.onPostExecute(success);
mAuthTask = null;
showProgress(false);
if (success.equals("true")) {
finish();
Toast.makeText(getApplicationContext(),"login success",Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(LoginPage.this,Authorities.class);
LoginPage.this.startActivity(myIntent);
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
For more info check this question Can't Override onPostExecute() method in AsyncTask Class or get it to trigger
Hope this helps!!
Its like there are many class like Login.java, Updatedetails.java, Result.java etc.
Here is the java code for Login.java
package com.example.catxam;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.catxam.JSONParser;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.EditText;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
public class Login extends Activity {
private EditText inputUserid, inputPassword, server;
TextView forgotPassword;
private Button b1;
public static String serve;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// JSON Node names
private static final String resp = "success";
private static final String Flag = "flag";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.login);
inputUserid = (EditText) findViewById(R.id.Username_edit);
inputPassword = (EditText) findViewById(R.id.User_password);
server = (EditText) findViewById(R.id.serverSelection);
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent passForget = new Intent(getApplicationContext(),
ForgotPassword.class);
startActivity(passForget);
}
});
b1 = (Button) findViewById(R.id.loginbutton); // login button
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new CreateNewUser().execute();
}
});
}
// this class is for the checking of the user login and password
//i.e. of first login and the next consecutive logins
class CreateNewUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
protected void shradu() {
//super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Failed Login");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Checking creditenials
* */
protected String doInBackground(String... args) {
String user = inputUserid.getText().toString();
String pswrd = inputPassword.getText().toString();
serve = server.getText().toString();
if (serve.equals("web"))
serve = "glydenlewis.esy.es";
else if (serve.equals("g"))
serve = "192.168.1.4";
else if (serve.equals("r"))
serve = "192.168.0.100";
else if (serve.equals("v"))
serve = "192.168.0.100";
else
serve = "glydenlewis.esy.es";
// URL to check username & password
final String url_check_user = "http://" + serve + "/catxam/android_check.php";
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uname", user));
params.add(new BasicNameValuePair("psd", pswrd));
// getting JSON Object
// Note that create product url accepts POST method
// this try is to catch if server address is wrong
JSONObject json = jsonParser.makeHttpRequest(url_check_user,"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(resp);
int flag_ck = json.getInt(Flag);
if (success == 1) {
if (flag_ck == 0)
{
//First Time Login By User
Intent i = new Intent(getApplicationContext(), UpdateDetails.class);
Toast.makeText(getApplicationContext(), "First Login, Please Update Your Details",Toast.LENGTH_SHORT).show();
startActivity(i);
finish(); // closing this screen
}
else
{
// successfully login
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish(); // closing this screen
}
} else {
// successfully login
Intent i = new Intent(getApplicationContext(), LogoStart.class);
startActivity(i);
finish(); // closing this screen
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
now for the UpdateDetails.java
package com.example.catxam;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.view.Window;
import android.view.WindowManager;
public class UpdateDetails extends Activity {
EditText inputName;
EditText inputAddress;
EditText inputPassword;
EditText confirmPassword;
EditText inputEmailId, inputMobileno;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// JSON Node names
private static final String resp = "success";
//private static final String Flag = "flag";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.updatedetails);
// Edit Text
inputName = (EditText) findViewById(R.id.editName);
inputAddress = (EditText) findViewById(R.id.editAddress);
inputPassword = (EditText) findViewById(R.id.editPassword);
confirmPassword=(EditText) findViewById(R.id.editConfirmPassword);
inputEmailId=(EditText) findViewById(R.id.editText2_emailid);
inputMobileno=(EditText) findViewById(R.id.editText1_mobile);
// Create button
Button update_details = (Button) findViewById(R.id.buttonUpdate);
// button click event
update_details.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (inputPassword == confirmPassword){
// updating user in background thread
new UpdateUserDetails().execute();
}
else {
//Some Sort Of Alert Box
Toast.makeText(getApplicationContext(), "Please Enter Valid Details", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Background Async Task to Create new product
* */
class UpdateUserDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UpdateDetails.this);
pDialog.setMessage("Updating User Details.. Please wait");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Updating User
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String address = inputAddress.getText().toString();
String password = inputPassword.getText().toString();
String mobileno = inputMobileno.getText().toString();
String emailid = inputEmailId.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("address", address));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("mobile_no", mobileno));
params.add(new BasicNameValuePair("email_id",emailid));
final String url_user = "http://"+ Login.serve +"/catxam/android_update.php";
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url_user,"POST", params);
// check log cat from response
Log.d("Update Response", json.toString());
// check for success tag
try {
int success = json.getInt(resp);
if (success == 1) {
// successfully update user
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
Toast.makeText(getApplicationContext(), "Unsuccessful Updation", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
Now my question is that as i have declared all the server option only in login.java, which can be accessed by other class as Login.serve.
so i just want to make it simple and save all the address in GlobalVariableCall.java. and then these address would be accessed by different classes.
you can pass variables thru one activity to an other with the intent method wich is very simple...
Intent myIntent = new Intent(firstActivity.this, secondActivity.class);
myIntent.putExtra("data", data); //Optional parameters or data to be send to the next activity
firstActivity.this.startActivity(myIntent);
in that case you declare the global variable in the firstActivity... and you can putExtras as you want those are the variables that you are sending to the next activity
or you can instanciate the global variable class but you will lose the value of the variable when passing it thru one class to another...
i want to make a single class called as GlobalVariableCall where i am
declaring few variables such as public static Sting server.
So you have declared:
class GlobalVariableCall
{
public static String server="http://stackoverflow.com/questions/21634112/i-want-to-call-variables-from-one-java-class-to-different-java-class-in-android";
}
Then You can call this server variable from other Activity say Login.java like this:
OnCreate()
{
............
..............
String abc = GlobalVariableCall.server; // In this way abc will get the value of server.
}
I have a case where my second server I get different results when a request to the API with jsonparser. Always fail..
Server 1 | Server 2
On both servers (server 1 and 2) I made an example of exactly the same data, but when I make the request on the application turns on the first server to respond well, but the second server always responds with a null. How do I use the second server in order to run properly? I am very confused on this case..
I made a simple application to perform experiments in case above :
package com.joris.androidjsonparsingfromurl;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView uid;
TextView name1;
TextView email1;
Button Btngetdata;
// URL to get JSON Array
//private static String url = "http://newapi.bacaberita.com/statis.php";
private static String url = "http://api.berthojoris.com/babe/statis.php";
// JSON Node Names
private static final String TAG_ITEM = "items";
private static final String TAG_ISDISPLAY = "IsDisplay";
private static final String TAG_TITLE = "Title";
private static final String TAG_POST = "Post";
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Utils.setPolicyThread();
Btngetdata = (Button) findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
uid = (TextView) findViewById(R.id.uid);
name1 = (TextView) findViewById(R.id.name);
email1 = (TextView) findViewById(R.id.email);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.setCanceledOnTouchOutside(false);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
if (result.length() > 0) {
pDialog.dismiss();
try {
// Getting JSON Array
user = result.getJSONArray(TAG_ITEM);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String status = c.getString(TAG_ISDISPLAY);
String title = c.getString(TAG_TITLE);
String post = c.getString(TAG_POST);
// Set JSON Data in TextView
uid.setText(status);
name1.setText(title);
email1.setText(post);
Log.e("HASILNYA", status+title+post);
} catch (JSONException e) {
e.printStackTrace();
}
}else{
pDialog.dismiss();
Toast.makeText(getBaseContext(),
"Data Kosong Gan...", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
finish();
}
}).setNegativeButton(R.string.no, null).show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
}
Is there a difference cause I can not make a request to the second server? Please help.. Thanks
im doing a login register for my application and i have to integrate them together with microsoft azure. However, despite after following the tutorial given by microsoft azure, i still fail to insert my "string" into their database. There are also no error in the codes, hence i'm not very sure where is wrong. Below is my codes.
package mp.memberuse;
import java.net.MalformedURLException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import com.microsoft.windowsazure.mobileservices.*;
public class LoginRegister extends Activity {
Button btn1, btn2, btn3;
EditText tf1, tf2, tf3, tf4, tf5, tf6, tf7, tf8, tf9, tf10, tf11;
TextView tv1, tv2;
private MobileServiceClient mClient;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabHost tabs = (TabHost) this.findViewById(R.id.lt2tabhost);
tabs.setup();
TabSpec ts1 = tabs.newTabSpec("Login");
ts1.setIndicator("Login");
ts1.setContent(R.id.c1);
tabs.addTab(ts1);
TabSpec ts2 = tabs.newTabSpec("Register");
ts2.setIndicator("Register");
ts2.setContent(R.id.c2);
tabs.addTab(ts2);
btn1 = (Button)findViewById(R.id.button1);
btn2 = (Button)findViewById(R.id.button2);
btn3 = (Button)findViewById(R.id.button3);
tf1=(EditText) findViewById(R.id.editText1);
tf2=(EditText) findViewById(R.id.editText2);
tf3=(EditText) findViewById(R.id.editText3);
tf4=(EditText) findViewById(R.id.editText4);
tf5=(EditText) findViewById(R.id.editText5);
tf6=(EditText) findViewById(R.id.editText6);
tf7=(EditText) findViewById(R.id.editText7);
tf8=(EditText) findViewById(R.id.editText8);
tf9=(EditText) findViewById(R.id.editText9);
tf10=(EditText) findViewById(R.id.editText10);
tv1=(TextView) findViewById(R.id.login);
tv2=(TextView) findViewById(R.id.register);
try {
MobileServiceClient mClient = new MobileServiceClient("https://testrun.azure-mobile.net/","FOJanABDYiJEVMHkCECAylrXJCnVwF77",this);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
btn1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
String username, password;
username = tf1.getText().toString();
password = tf2.getText().toString();
/**if(username.equals(sqlusername) && password.equals(sqlpassword))
{
SharedPreferences prefs = getSharedPreferences("myPreferences",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("fullname", fullname);
editor.commit();
Intent intent = new Intent(LoginRegister.this, SendMessage.class);
startActivity(intent);
}
else
{
tv1.setText("Invalid user");
} **/
}
}
);
btn2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
String username, password, cpassword, fullname, nric, address, phone, email;
username = tf3.getText().toString();
password = tf4.getText().toString();
cpassword = tf5.getText().toString();
fullname = tf6.getText().toString();
nric = tf7.getText().toString();
address = tf8.getText().toString();
phone = tf9.getText().toString();
email = tf10.getText().toString();
Members members = new Members();
members.username = username;
members.password = password;
members.fullname = fullname;
members.nric = nric;
members.address = address;
members.phone = phone;
members.email = email;
if(!password.equals(cpassword))
{
tv2.setText("Password & Confirm Password does not match.");
}
else if(username.equals("") || password.equals("") || cpassword.equals("") || fullname.equals("") || nric.equals("") || address.equals("") || phone.equals("") || email.equals(""))
{
tv2.setText("Do not leave any field empty.");
}
else
{
mClient.getTable(Members.class).insert(members, new TableOperationCallback<Members>()
{
public void onCompleted(Members entity, Exception exception, ServiceFilterResponse response)
{
if (exception == null)
{
tv2.setText("Register Complete.");
tf3.setText("");
tf4.setText("");
tf5.setText("");
tf6.setText("");
tf7.setText("");
tf8.setText("");
tf9.setText("");
tf10.setText("");
}
else
{
tv2.setText("Fail to register!");
}
}
});
tv2.setText("Register Complete.");
tf3.setText("");
tf4.setText("");
tf5.setText("");
tf6.setText("");
tf7.setText("");
tf8.setText("");
tf9.setText("");
tf10.setText("");
}
}
});
btn3.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
tf3.setText("");
tf4.setText("");
tf5.setText("");
tf6.setText("");
tf7.setText("");
tf8.setText("");
tf9.setText("");
tf10.setText("");
}
});
}
}
Here is an code snippet , hoping it will help you.
1)An function which carries the http get service
private String SendDataFromAndroidDevice() {
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet getMethod = new HttpGet("your url + data appended");
BufferedReader in = null;
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(getMethod);
in = new BufferedReader(new InputStreamReader(httpResponse
.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
2) An Class which extends AsyncTask
private class HTTPdemo extends
AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... params) {
String result = SendDataFromAndroidDevice();
return result;
}
#Override
protected void onProgressUpdate(Void... values) {}
#Override
protected void onPostExecute(String result) {
if (result != null && !result.equals("")) {
try {
JSONObject resObject = new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
3) Inside your onCreate method
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView("your layout");
if ("check here where network/internet is avaliable") {
new HTTPdemo().execute("");
}
}
The code snippet provided by me works in the following way,
1)Android device send the URL+data to server
2)Server [Azure platform used] receive the data and gives an acknowledgement
Now the Code which should be written at client side (Android) is provided to you, the later part of receiving that data at server is
Server needs to receive the data
An webservice should be used to do that
Implement an webservice at server side
The webservice will be invoked whenever android will push the URL+data
Once you have the data ,manipulated it as you want