I created a login activity for my Android app. After the user enters the correct credentials, the login activity will switch over to the homepage but I don't know why my code won't switch and there is no error shown in my logcat. The manifest was also properly defined.
This is my login activity:
public class LoginEmployerActivity extends Activity {
Button btnLoginEmployer;
Button btnLinkToEmployerRegisterScreen;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
TextView forgotPassword;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_CNAME = "cname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private ProgressDialog pDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_employer);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmployerEmail);
inputPassword = (EditText) findViewById(R.id.loginEmployerPassword);
btnLoginEmployer = (Button) findViewById(R.id.btnLoginEmployer);
btnLinkToEmployerRegisterScreen = (Button) findViewById(R.id.btnLinkToEmployerRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
forgotPassword = (TextView) findViewById(R.id.link_to_forgetPassword);
// Login button Click Event
btnLoginEmployer.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Checking for server respond
new LoginEmployer().execute();
}
}
});
// Link to Register Screen
btnLinkToEmployerRegisterScreen
.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterEmployerActivity.class);
startActivity(i);
finish();
}
});
// Link to forgot password link
forgotPassword.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Switching to forgot password screen
Intent i = new Intent(getApplicationContext(),
ForgotPasswordEmployerActivity.class);
startActivity(i);
}
});
}
// Background ASYNC Task to login by making HTTP Request
class LoginEmployer extends AsyncTask<String, String, String> {
// Before starting background thread Show Progress Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginEmployerActivity.this);
pDialog.setMessage("Authenticating...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
// Checking login in background
protected String doInBackground(String... params) {
runOnUiThread(new Runnable() {
public void run() {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
EmployerFunctions employerFunctions = new EmployerFunctions();
JSONObject json = employerFunctions.loginUser(email,
password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandlerEmployer dbe = new DatabaseHandlerEmployer(
getApplicationContext());
JSONObject json_user = json
.getJSONObject("user");
// Clear all previous data in database
employerFunctions
.logoutUser(getApplicationContext());
dbe.addUser(
json_user.getString(KEY_NAME),
//json_user.getString(KEY_CNAME),
json_user.getString(KEY_EMAIL),
json.getString(KEY_UID),
json_user.getString(KEY_CREATED_AT));
// Launch Employer homePage Screen
Intent homepage = new Intent(
getApplicationContext(),
HomepageEmployerActivity.class);
// Close all views before launching Employer
// homePage
homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homepage);
// Close Login Screen
finish();
} else {
// Error in login
loginErrorMsg
.setText("Invalid username/password");
}
}
} 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();
}
}
}
EDITED CODE AFTER MOVING INTENT STATEMENT TO onPostExecute METHOD
public class LoginEmployerActivity extends Activity {
Button btnLoginEmployer;
Button btnLinkToEmployerRegisterScreen;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
TextView forgotPassword;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_CNAME = "cname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private ProgressDialog pDialog;
boolean loginVerify= false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_employer);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmployerEmail);
inputPassword = (EditText) findViewById(R.id.loginEmployerPassword);
btnLoginEmployer = (Button) findViewById(R.id.btnLoginEmployer);
btnLinkToEmployerRegisterScreen = (Button) findViewById(R.id.btnLinkToEmployerRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
forgotPassword = (TextView) findViewById(R.id.link_to_forgetPassword);
// Login button Click Event
btnLoginEmployer.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Checking for server respond
new LoginEmployer().execute();
}
}
});
// Link to Register Screen
btnLinkToEmployerRegisterScreen
.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterEmployerActivity.class);
startActivity(i);
finish();
}
});
// Link to forgot password link
forgotPassword.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Switching to forgot password screen
Intent i = new Intent(getApplicationContext(),
ForgotPasswordEmployerActivity.class);
startActivity(i);
}
});
}
// Background ASYNC Task to login by making HTTP Request
class LoginEmployer extends AsyncTask<String, String, String> {
// Before starting background thread Show Progress Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginEmployerActivity.this);
pDialog.setMessage("Authenticating...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
// Checking login in background
protected String doInBackground(String... params) {
runOnUiThread(new Runnable() {
public void run() {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
EmployerFunctions employerFunctions = new EmployerFunctions();
JSONObject json = employerFunctions.loginUser(email,
password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
loginVerify = true;
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandlerEmployer dbe = new DatabaseHandlerEmployer(
getApplicationContext());
JSONObject json_user = json
.getJSONObject("user");
// Clear all previous data in database
employerFunctions
.logoutUser(getApplicationContext());
dbe.addUser(
json_user.getString(KEY_NAME),
json_user.getString(KEY_CNAME),
json_user.getString(KEY_EMAIL),
json.getString(KEY_UID),
json_user.getString(KEY_CREATED_AT));
} else {
// Error in login
loginErrorMsg
.setText("Invalid username/password");
}
}
} 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();
if ( loginVerify == true )
{
// Launch Employer homePage Screen
Intent homepage = new Intent(getApplicationContext(),
HomepageEmployerActivity.class);
// Close all views before launching Employer
// homePage
homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homepage);
// Close Login Screen
finish();
}
}
}
}
You are calling the intent to start a new activity inside the doInBackgorund() which runs on a non-UI thread and the Activity needs to be run on a UI thread. That is why your Login activity is never stopped.
Put the code to go to the new activity inside onPostExecute() or onProgressUpdate().
Here is something you can do.
Declare a global variable loginVerfied = false;
When your doInBackground verifies that the authenticity of the user, make loginVerified = true , otherwise keep it false.
Then inside onPostExecute()
if(loginVerifed == true)
{
Intent homepage = new Intent(getApplicationContext(),HomepageEmployerActivity.class
homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homepage);
finish();
}
EDIT :
Also, you have declared class LoginEmployer extends AsyncTask<String, String, String>, so to call it you need to use new LoginEmployer.execute(""); (you are missing the double quotes and not passing any String to the Task so it does not match it's parameters).
The first parameter in the definition of the AsyncTask is the datatype of the value being passed to it when execute() function is called. The second parameter is the datatype related to displaying progress during the time when the background thread runs. And the third parameter specifies the return value of the result.
More about AsyncTask here.
So, here is what you need to do now.
Declare the Async Task like this.
class LoginEmployer extends AsyncTask<String, Void, String> and make a call to it by using new LoginEmployer.execute(""). Make sure to return null from your doInBackground().
Hope this solves your problem now!
Add a checker to your AsyncTask such as
// Background ASYNC Task to login by making HTTP Request
class LoginEmployer extends AsyncTask<String, String, String> {
boolean validUser = false;
Then once the user is validated inside your background task set the value to true
if (Integer.parseInt(res) == 1) {
// user successfully logged in
// Store user details in SQLite Database
validUser = true; //set valid to true
Now in postExecute check if the user is valid
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
if ( validUser )
{
Intent homepage = new Intent( LoginEmployerActivity.this,
HomepageEmployerActivity.class);
// Close all views before launching Employer
// homePage
homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homepage);
}
I don't think you have added the Intent code here that will help you switch to another Activity.
protected void onPostExecute(String file_url) {
// dismiss the dialog once done // Intent Code Missing.
pDialog.dismiss();
You should do a UI work in UI thread and Non-UI work in Non-UI thread, thats a rule from the arrival of HoneyComb version of android.
You have added the below code in doInBackground(), That should be in onPostExcute()
Intent homepage = new Intent( getApplicationContext(), HomepageEmployerActivity.class);
homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homepage);
Related
So I have a static variable called isSuccessful all the variable is supposed to do is, be true if someone was able to login successfully or be false if they couldn't. I have it set to false by default. The php script I wrote sends the message "loginsuccess" and stores it in the onProgressUpdate parameters. I debugged to see if that's what was being stored in the parameters, and the compile says it is. well then I can't figure out why isSuccessful isn't being switched to true. I set it to do that. once that happens, I have the login activity call the homeScreen activity.
LoginTask:
public class LogInTask extends AsyncTask<String, String,String> {
public Scanner reader;
Formatter writer;
Context mcontext;
//if Login was successful
public static boolean isSuccessful;
LogInTask(Context context)
{
mcontext = context;
}
URL url;
URLConnection con;
String output = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
isSuccessful=false;
try {
url = new URL("http://192.168.1.75:1234/login.php");
con = url.openConnection();
//allows to send information
con.setDoOutput(true);
//allows to receive information
con.setDoInput(true);
writer = new Formatter(con.getOutputStream());
//Sends login information to SQL table
writer.format("user_name="+params[0]+"&password="+params[1]);
writer.close();
//Reads input
reader = new Scanner(con.getInputStream());
while(reader.hasNext())
{
output+= reader.next();
}
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
publishProgress(output);
return output;
}
#Override
protected void onProgressUpdate(String... values) {
Toast.makeText(mcontext, values[0],Toast.LENGTH_LONG).show();
if(values[0]=="loginsuccess")
isSuccessful = true;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
LogInActivity:
public class LogInActivity extends Activity {
private Typeface fontRobo;
private TextView logoText;
private EditText userName;
private EditText passWord;
private TextView dontHave;
private TextView signUp;
private Button logIn;
Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
i = new Intent(this, HomeActivity.class);
//Logo
logoText = (TextView)findViewById(R.id.Logo);
fontRobo = Typeface.createFromAsset(this.getAssets(),"fonts/ROBO.ttf");
logoText.setText("ArtSpace");
logoText.setTypeface(fontRobo);
//Don't have an account?
dontHave = (TextView) findViewById(R.id.Donthave);
dontHave.setTypeface(fontRobo);
//Sign Up
signUp = (TextView) findViewById(R.id.signUP);
signUp.setTypeface(fontRobo);
userName = (EditText) findViewById(R.id.userName);
passWord = (EditText) findViewById(R.id.passWord);
logIn = (Button) findViewById(R.id.LogIn);
}
//Log in button event
public void logInClick(View view)
{
final LogInTask task = new LogInTask(LogInActivity.this);
task.execute(userName.getText().toString(), passWord.getText().toString());
if(LogInTask.isSuccessful)
startActivity(i);
}
php:
<?php
require "conn.php";
$user_name = $_POST['user_name'];
$user_pass = $_POST['password'];
$mysql_qry = "SELECT * FROM login WHERE UserName LIKE '$user_name' AND Password LIKE '$user_pass';";
$result = mysqli_query($conn,$mysql_qry);
if(mysqli_num_rows($result) == true)
{
echo "login success";
}
else
{
echo "login not success";
}
?>
task.execute() is AsyncTask aka it takes time to execute. But you are checking right after you call it. You need to make the check for isSuccessful in onPostExecute() block.
Something like this:
final LogInTask task = new LogInTask(LogInActivity.this){
#Override
protected void onPostExecute(String s) {
if(LogInTask.isSuccessful)
startActivity(i);
}};
task.execute(userName.getText().toString(), passWord.getText().toString());
PS: Something else, do not compare Strings with == use .equals()
if(values[0].equals("loginsuccess"))
I have Splash Activity => Login Activity => Main Activity....
Once user Login My user Should redirect To the Main Activity Directly till LOGOUT.....
Give me a specific solution please...What to do in which Activity..
I am working with web services....suggest me if SQ Lite require or Shared-preference Or Session.Class.....
Please BE SPECIFIC ...what to do in which Activity/Class...
Before Login..
Splash Activity => Login Activity => Main Activity
I want flow after LOGIN like this..
Splash Activity =>Main Activity ....
Thank You in advance.....
SplashActivity.java
public class Splash extends Activity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Thread timerThread = new Thread(){
public void run(){
try{
sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
String sharedPrefId = "MyAppPreference";
SharedPreferences prefs = getSharedPreferences(sharedPrefId, 0);
boolean isLoggedIn = prefs.getBoolean("isLoggedIn", false);
if(isLoggedIn)
{
// Show Main Activity
Intent intent1= new Intent(Splash.this,SnetHome.class);
startActivity(intent1);
}
else
{
// Show Login activity
Intent intent2= new Intent(Splash.this,Login.class);
startActivity(intent2);
}
//if{
//if user redirect to LoginActivity
//Intent intent = new Intent(Splash.this,Login.class);
//startActivity(intent);
//}else{
//otherwise redirect to SnetHome activity
// }
}
}
};
timerThread.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Login.java
public class Login extends AppCompatActivity implements OnClickListener {
private EditText user, pass;
private Button mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// php login script location:
// localhost :
// testing on your device
// put your local ip instead, on windows, run CMD > ipconfig
// or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL =
// "http://xxx.xxx.x.x:1234/webservice/login.php";
// testing on Emulator:
private static final String LOGIN_URL = "http://192.168.1.106/SnetWebservice/login.php";
// testing from a real server:
// private static final String LOGIN_URL =
// "http://www.mybringback.com/webservice/login.php";
// JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//toolbar
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
// setup input fields
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
// setup buttons
mSubmit = (Button) findViewById(R.id.login);
mRegister = (Button) findViewById(R.id.register);
// register listeners
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent inte = new Intent(Login.this, Register.class);
startActivity(inte);
}
});
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
/* case R.id.register:
Intent i = new Intent(this, Register.class);
startActivity(i);
break;
*/
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
// save user data
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = prefs.edit();
edit.putString("username", username);
edit.commit();
prefs.edit().putBoolean("isLoggedIn", true).commit();
Intent i = new Intent(Login.this, SnetHome.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
} else if (success == 0) {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
You can use SharedPreference for achieving this. You need to implement the logic in your SplashActivity. You need to check whether already logged in or not using the value stored in shared preference and show next activity based on that.
In your SplashActivity (Where you launch the login activity), add the logic like:
// Retrieving your app specific preference
String sharedPrefId = "MyAppPreference";
SharedPreferences prefs = getSharedPreferences(sharedPrefId, 0);
boolean isLoggedIn = prefs.getBoolean("isLoggedIn", false);
if(isLoggedIn)
{
// Show Main Activity
}
else
{
// Show Login activity
}
And in your LoginActivity, after successful login set the value to true:
prefs.edit().putBoolean("isLoggedIn", true).commit();
Like this
onCreate of Spalsh Activity
if(isLogin) //value comes from Shared Preference
{
Go to Main
}else
{
Go to Login
}
Use SharedPreference which will store a boolean variable as isUserLoggedIn if user has logged in then it will store true otherwise false and then check the value of SharedPreference at splash screen.
i want to have a search bar that searches a number that has been typed in (for example: 115048) and put that in a listview. the json file looks like this http://api.ccapp.it/v1/student/115048/schedule/11
hope someone can help me, the code that i use right now to search a link is like this but it doesnt have a search bar:
public class RoosterviewMd extends ListActivity {
Button mButton;
EditText mEdit;
private ProgressDialog pDialog;
// URL to get contacts JSON
//private static String id = null;
//private static String url = "http://api.ccapp.it/v1/student/" + id + "/schedule/11";
private static String url = "http://api.ccapp.it/v1/student/115048/schedule/12";
// JSON Node names
private static final String TAG_LESSON = "class";
private static final String TAG_ROOM = "room";
private static final String TAG_TEACHER = "teacher";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.roosterviewmd);
//Number input
final EditText input = (EditText) findViewById(R.id.editText2);
//buttons for all the days
Button btn2 = (Button) findViewById(R.id.button29);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Toast.makeText(getBaseContext(), "Je ziet je rooster voor maandag al" , Toast.LENGTH_SHORT ).show();
}
});
Button btnOne = (Button)findViewById(R.id.button30);
btnOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewDi.class);
startActivity(intent);
}
});
Button btnTwo = (Button)findViewById(R.id.button31);
btnTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewWo.class);
startActivity(intent);
}
});
Button btnThree = (Button)findViewById(R.id.button32);
btnThree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewDo.class);
startActivity(intent);
}
});
Button btnFour = (Button)findViewById(R.id.button33);
btnFour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewVr.class);
startActivity(intent);
}
});
//Buttons end here
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String lesson = ((TextView) view.findViewById(R.id.lesson))
.getText().toString();
String teacher = ((TextView) view.findViewById(R.id.teacher))
.getText().toString();
String room = ((TextView) view.findViewById(R.id.room))
.getText().toString();
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(RoosterviewMd.this);
pDialog.setMessage("Give me a second please");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray arr1 = jsonObj.getJSONArray("lessons");
JSONArray arr2 = arr1.getJSONArray(0); //Dag
for (int b = 0; b < arr2.length(); b++) {
JSONObject c = arr2.getJSONObject(b);
String lesson = c.getString(TAG_LESSON);
String teacher = c.getString(TAG_TEACHER);
String room = c.getString(TAG_ROOM);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_LESSON, lesson);
contact.put(TAG_TEACHER, teacher);
contact.put(TAG_ROOM, room);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("CCApp", "Couldn't get any data from the url");
Toast.makeText(getBaseContext(),"We are aware of this error and are working on it, in the mean time eat a cookie", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(RoosterviewMd.this, contactList,
R.layout.list_item, new String[] {TAG_LESSON, TAG_TEACHER,
TAG_ROOM }, new int[] { R.id.lesson,
R.id.teacher, R.id.room });
setListAdapter(adapter);
}
}
}
i hope someone can help me with this
Check out this answer: Get text from web page to string
Basically, you can simply get the text from the page and pass it into a string, and search the string application side for the contents of your edit text.
If you're looking for more functionality with the data from the web site, I would pull the Json into an array of Jsonobjects using something like Gson. You'd then be able to use the data from the web page in a bit more of a structured manner.
Edit: Now to actually answer your question.
You can include an edit text and button in your xml in order to search using a basic search bar kinda thing.
To set a listener on the button, you would do something like:
findViewById(R.id.button).setOnClickListener(new OnClickListener(){
#Override
protected void onClick(View v){
//Here, we can control what the response to the button press is, and grab the text in the edit text field.
String editTextString = findViewById(R.id.edittext).getEditableText().toString();
//Now we have a string used to parse the json or whatever else you need to do.
//May want to add a case here if editTextString is null to prevent runtime errors.
}
}
(Forgive me if there's any minor syntatic errors, just wrote that up quick here in the browser, no API to check on it. :))
I have two class DashboardActivity.class and ProfileActivity.class,
In Dashboard class I would like to pass a value through button to ProfileActivity class. But it keep getting me error and the response JSON telling me that the 'Required field(s) is missing'. When I checked, the value from Dashboard didn't pass to ProfileActivity, that's why the response keep telling me 'Required filed(s) is missing'.
My, question is, How to pass a value through button to another activity. I already use this code :
btnLinkToProfile = (Button) findViewById(R.id.btnProfile);
btnLinkToProfile.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
//userFunctions.userProfil(INPUT_METHOD_SERVICE);
Intent i = new Intent(getApplicationContext(),ProfileActivity.class);
i.putExtra(KEY_NAME, name);
startActivityForResult(i,0);
}
But I get forced close when I try to run.
Here's the complete code of Dashboard Activity :
public class DashboardActivity extends Activity {
UserFunctions userFunctions;
Button btnLogout;
Button btnLinkToProfile;
private static final String KEY_NAME = "name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Dashboard Screen for the application
* */
// Check login status di database
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
// user already logged in show dashboard
setContentView(R.layout.dashboard);
//JSONObject json = jParserr.getJSONFromUrl(dashboardURL, "GET", params);
btnLinkToProfile = (Button) findViewById(R.id.btnProfile);
btnLinkToProfile.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
//userFunctions.userProfil(INPUT_METHOD_SERVICE);
Intent i = new Intent(getApplicationContext(),ProfileActivity.class);
i.putExtra(KEY_NAME, name);
startActivityForResult(i,0);
//startActivity(i);
//finish();
}
});
btnLogout = (Button) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(), MainActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Keluar dari dashboard screen
finish();
}
});
}else{
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(), MainActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
}
}
And here's for ProfileActivity class :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
// Loading user Profile in Background Thread
new showUserProfile().execute();
}
///...
/**
* Background Async Task to Load user profile by making HTTP Request
* */
private class showUserProfile extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ProfileActivity.this);
pDialog.setMessage("Loading User Profile. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting user profile from url
* */
protected String doInBackground(String... args) {
//String name = name.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(profileURL, "GET", params);
/* UserFunctions userFunction = new UserFunctions();
if (params.length != 0)
return null;
JSONObject json = userFunction.userProfil(params[0]);
return json; */
// Check your log cat for JSON reponse
Log.d("User Profile: ", json.toString());
...
return null;
}
}
}
You are creating a new Intent in the Profile Activity.
You should actually use getIntent() to receive the intent the activity was called with.
That will return an intent object with your "name" extra.
EDIT: Actually, I can't tell precisely where you are trying to read the value sent from the Dashboard.
In ProfileActivity you should have
Intent intent = getIntent();
String name = intent.getStringExtra("name");
Then you can use the name from Dashboard in Profile.
Also look into implementing onNewIntent() for ProfileActivity.
EDIT: I edited your post to re-include where you call the AsyncTask. Notice your AsyncTask accepts a String parameter but you don't pass it one.
So do this in your ProfileActivity.onCreate():
Intent intent = getIntent();
String name = intent.getStringExtra("name");
new showUserProfile().execute(name);
Now in your doInBackground you should be able to get the name with args[0]
EDIT: Your AsyncTask should probably be:
private class showUserProfile extends AsyncTask<String, Void, Void>
Because you only accept the parameter, other don't use the progress or return values.
You are passing the extra properly, you just aren't retrieving it at all from your next activity.
Use Bundle var = getIntent().getExtras()
followed by
if(var != null){
myString = var.getString(KEY_NAME);
}
i am currently doing a page which retrieve data from php server and now trying to retrieve and image from drawable by using setImageResource but is not working, i dunno what wrong with it and is it possible for me to just save image name in database then retrieve image by using image name?
beside that, i try to do a simple plus minus button for quantity but the apps force stop once i click on the button..
public class FoodDetailActivity extends Activity
{
TextView FoodName;
TextView FoodDesc;
TextView FoodPrice;
ImageView FoodImg;
EditText Number;
Button plus;
Button minus;
Button Addcart;
String fid;
int number;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_food_details = "http://10.0.2.2/android_user/FoodDetail.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_FOOD = "food";
private static final String TAG_FID = "fid";
private static final String TAG_FOODNAME = "food_name";
private static final String TAG_FOODPRICE = "food_price";
private static final String TAG_FOODDESCRIPTION = "food_description";
private static final String TAG_FOODURL = "food_url";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_detail);
// button
plus = (Button)findViewById(R.id.btn_plus);
plus.setOnClickListener(increase);
minus = (Button)findViewById(R.id.btn_minus);
minus.setOnClickListener(decrease);
Addcart = (Button)findViewById(R.id.btn_submit);
Number = (EditText)findViewById(R.id.text_number);
// getting food details from intent
Intent i = getIntent();
// getting food id (fid) from intent
fid = i.getStringExtra(TAG_FID);
// Getting complete product details in background thread
new GetFoodDetails().execute();
}
// Increase number of quantity
private OnClickListener increase = new OnClickListener()
{
public void onClick(View v)
{
String quantity = Number.getText().toString().trim();
number = Integer.parseInt(quantity);
if(number > 0 && number < 99)
{
number = number + 1;
Number.setText(Integer.toString(number));
}
else if(number == 99)
{
number = 1;
Number.setText(Integer.toString(number));
}
}
};
// Decrease number of quantity
private OnClickListener decrease = new OnClickListener()
{
public void onClick(View v)
{
String quantity = Number.getText().toString();
number = Integer.valueOf(quantity);
if(number > 1 && number <= 99)
{
number = number - 1;
Number.setText(Integer.toString(number));
}
else if(number == 1)
{
number = 99;
Number.setText(Integer.toString(number));
}
}
};
class GetFoodDetails extends AsyncTask<String, String, String>
{
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(FoodDetailActivity.this);
pDialog.setMessage("Loading food details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params)
{
// updating UI from Background Thread
runOnUiThread(new Runnable()
{
public void run()
{
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("fid", fid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = JSONParser.makeHttpRequest(url_food_details, "GET", params);
// check your log for json response
Log.d("Single Food Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1)
{
// successfully received food details
JSONArray foodObj = json.getJSONArray(TAG_FOOD); // JSON Array
// get first product object from JSON Array
JSONObject food = foodObj.getJSONObject(0);
// Loader image - will be shown before loading image
int loader = R.drawable.loader;
String image_url = food.getString(TAG_FOODURL);
// product with this fid found
// Edit Text
FoodName = (TextView)findViewById(R.id.food_name);
FoodPrice = (TextView)findViewById(R.id.food_price);
FoodDesc = (TextView)findViewById(R.id.food_desc);
FoodImg = (ImageView)findViewById(R.id.img_food);
// display product data in EditText
FoodName.setText(food.getString(TAG_FOODNAME));
FoodPrice.setText("RM" + food.getString(TAG_FOODPRICE));
FoodDesc.setText(food.getString(TAG_FOODDESCRIPTION));
// ImageLoader class instance
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
// display image
imgLoader.DisplayImage(image_url, loader, FoodImg);
}
else
{
// no food detail found
// Launch error message
AlertDialog.Builder ad = new AlertDialog.Builder(FoodDetailActivity.this);
ad.setTitle("Error");
ad.setMessage("Food Detail is empty!");
ad.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialoginterface, int i)
{
}
});
ad.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
protected void onPostExecute(String file_url)
{
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
}
The problem had been solve, i using the ImageLoader retrieve image at server side with url store in database.
In here:
Drawable d = getResources().getDrawable(R.drawable.mcchicken); //<<<<
you are trying to use context of Activity before onCreate call. move Drawable d initialization inside onCreate method of Activity after setContentView as:
Drawable d; //<<< declare d here
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_detail);
d = getResources().getDrawable(R.drawable.mcchicken); //<< initialize d here
....
}
Edit : : inside doInBackground method you are trying to access UI element. instead of updating UI from doInBackground using runOnUiThread. you will need to move all UI related code in onPostExecute which call on Ui thread after doInBackground execution complete.
In your code is much messy material. So nicely from the beginning. First is only question.
Why you are putting inside doInBackground() method runOnUiThread()? If you want to update your UI with some information from task running in background, for this you have onProgressUpdate() or onPostExecute() method which are synchronized with UI Thread and allow its updates. doInBackground() method is directly designated for background processing and you shouldn't broke it.
Then this line:
if (food.getString(TAG_FOODNAME) == "McChicken")
will always return false because you are comparing references and not values. Always you are comparing strings, you have to use equals() method that makes a trick.
And last thing is this:
Drawable d = getResources().getDrawable(R.drawable.mcchicken);
You can't call that before setContentView() is called. Reason is that main purpose of setContentView() is that it creates all instances of UI elements and resources and if you something that requires resources call before this method, always you will get NPE