In below code i download json from internet and want to show in list.
if list is empty go to another activity but other activity not start.
no error but no start activity.
thanks for your help
package ir.mohammadi.android.nightly;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class AllNotes extends ListActivity {
ProgressDialog pDialog;
ArrayList<HashMap<String, String>> noteList;
JSONArray notes = null;
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR_MSG = "error_message";
private static String KEY_NOTE_ID = "note_id";
private static String KEY_NOTE_SUBJECT = "note_subject";
private static String KEY_NOTE_DATE = "note_date";
private static String EXECUTE_RESULT = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_list);
noteList = new ArrayList<HashMap<String, String>>();
new LoadAllNotes().execute();
ListView lv = getListView();
}
public class LoadAllNotes extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllNotes.this);
pDialog.setMessage("لطفا صبر کنید...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
UserFunctions userFunctions = new UserFunctions();
JSONObject jSon = userFunctions.getAllNotes("1");
Log.i("AllNotes >> jSon >>", jSon.toString());
try {
String success = jSon.getString(KEY_SUCCESS);
if (success == "1") {
notes = jSon.getJSONArray("notes");
for (int i = 0; i < notes.length(); i++) {
JSONObject c = notes.getJSONObject(i);
String id = c.getString(KEY_NOTE_ID);
String subject = c.getString(KEY_NOTE_SUBJECT);
String date = c.getString(KEY_NOTE_DATE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_NOTE_ID, id);
map.put(KEY_NOTE_SUBJECT, subject);
map.put(KEY_NOTE_DATE, date);
noteList.add(map);
}
} else {
finish();
Toast.makeText(getApplicationContext(),
jSon.getString(KEY_ERROR_MSG), Toast.LENGTH_SHORT).show();
Log.i("AllNotes >> No nightly >>", "...");
Intent i = new Intent(getApplicationContext(), login.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(AllNotes.this,
noteList, R.layout.list_item, new String[] {
KEY_NOTE_ID, KEY_NOTE_SUBJECT,
KEY_NOTE_DATE }, new int[] {
R.id.list_lbl_id, R.id.list_lbl_subject,
R.id.list_lbl_date });
setListAdapter(adapter);
}
});
}
}
}
Logcat json :
11-08 22:17:44.467: I/getAllNotes params before getting from net >>(599): [tag=getNotesList, user_id=1]
11-08 22:17:47.647: I/Input stream >>(599): org.apache.http.conn.EofSensorInputStream#44ededd8
11-08 22:17:47.767: I/JSON string builder >>(599): a{"error":"1","error_message":"\u0634\u0645\u0627 \u0647\u0646\u0648\u0632 \u0634\u0628\u0627\u0646\u0647 \u0627\u06cc \u0646\u0646\u0648\u0634\u062a\u0647 \u0627\u06cc\u062f."}
11-08 22:17:47.797: I/getAllNotes params after getting from net >>(599): {"error":"1","error_message":"dont have any note"}
11-08 22:17:47.797: I/AllNotes >> jSon >>(599): {"error":"1","error_message":"dont have any note"}
The most likely cause of your problem is this line:
String success = jSon.getString(KEY_SUCCESS);
You didn't post it, but I'll bet there is a JSONException stack trace below that last line. getString() will throw an exception if the key is not found, and in the JSON data you logged out, there is no "success" key. That exception is causing all the code you wrote after the fact to not get called at all, which is why you see nothing happening.
A couple other things to note:
success == "1" is not the proper way to do String equality. The == operator checks object equality (same object), if you want to check if two Strings are the same, us success.equals("1") instead.
onPostExecute() is always called on the main thread for you. You do not have to call runOnUiThread() from the method...it is redundant.
It is technically okay to start an Activity from a background thread like you have done, but you cannot show a Toast this way. When you fix your exception, the Toast.makeText() line will end up failing because you cannot show a Toast from a thread other than the main thread.
In general, it's best to do all UI operations on the main thread and as a point of design you should move any code that manipulates or changes the screen into onPostExecute() so it can be called at the right time. That's what it is there for.
This gets tricky. Some things to watch out for:
Intent i = new Intent(getApplicationContext(), login.class);
Make sure that the login class's type is in the manifest. Usually you reference the class by the class's name, not the instantiated variable. Honestly, it shouldn't make a difference but it's worth trying.
Sometimes you get weird side-effects using different contexts. I think startActivity is one that's pretty sensitive to this. You can try AllNotes.this to get the running activity's context. There's a slim chance that this needs to be run on the UI thread, so you can try runOnUiThread() if that doesn't work.
Related
I've been following a tutorial on how to show a Json arrays on android and I constantly get "Couldn't get json from server. Check internet connection!" and I can't figure out why. My Json is being generated from a php file and this works when I'm creating a list on my browser. So I'm sure my Json works.
EDIT: What adjustments do I have to do to be able to get a read from this url?
JSON array from "https://www.googleapis.com/books/v1/volumes?q=bond"
Android:
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class HomeScreen extends AppCompatActivity{
private ListView lv;
private ProgressDialog progress;
private String url="https://www.googleapis.com/books/v1/volumes?q=bond";
ArrayList<HashMap<String,String>> booklist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
booklist=new ArrayList<>();
lv= (ListView) findViewById(R.id.list);
new getBooks().execute();
}
public class getBooks extends AsyncTask<Void,Void,Void> {
protected void onPreExecute(){
super.onPreExecute();
progress=new ProgressDialog(HomeScreen.this);
progress.setMessage("Fetching JSON.,.");
progress.setCancelable(false);
progress.show();
}
protected Void doInBackground(Void...arg0){
HTTP_Handler hh = new HTTP_Handler();
String jString = hh.makeHTTPCall(url);
if (jString != null) {
try {
JSONObject jObj = new JSONObject(jString);
JSONArray books = jObj.getJSONArray("bookinfo");
for (int i = 0; i < books.length(); i++) {
JSONObject book = books.getJSONObject(i);
String name=book.getString("name");
String author=book.getString("author");
HashMap<String, String> bookdata = new HashMap<>();
bookdata.put("name", name);
bookdata.put("author", author);
booklist.add(bookdata);
}
} catch (final JSONException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check internet connection!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
protected void onPostExecute(Void Result){
super.onPostExecute(Result);
if(progress.isShowing()){
progress.dismiss();
}
ListAdapter adapter=new SimpleAdapter(
HomeScreen.this,
booklist,
R.layout.bucket_list,
new String[]{"name","author"},
new int[]{R.id.list_Name,R.id.list_author);
lv.setAdapter(adapter);
}
}
}
Does your browser have to authenticate against 'website/filename.php' to return JSON? I don't see any authentication steps going on in your code. If your code is freely available, this is probably not the issue. At first glance it appears that since now JSON is being returned from the server that this could be an issue.
I have the following error :
02-21 11:42:13.174: E/WindowManager(29845): Activity info.androidhive.tabsswipe.Party has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#420482c0 that was originally added here
02-21 11:42:13.174: E/WindowManager(29845): android.view.WindowLeaked: Activity info.androidhive.tabsswipe.Party has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#420482c0 that was originally added here
02-21 11:42:13.174: E/WindowManager(29845): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:376)
02-21 11:42:13.174: E/WindowManager(29845): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:296)
02-21 11:42:13.174: E/WindowManager(29845): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:228)
02-21 11:42:13.174: E/WindowManager(29845): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
02-21 11:42:13.174: E/WindowManager(29845): at android.view.Window$LocalWindowManager.addView(Window.java:549)
02-21 11:42:13.174: E/WindowManager(29845): at android.app.Dialog.show(Dialog.java:277)
02-21 11:42:13.174: E/WindowManager(29845): at info.androidhive.tabsswipe.Party$LoadParties.onPreExecute(Party.java:120)
02-21 11:42:13.174: E/WindowManager(298
Can anyone help me? This is my code :
package info.androidhive.tabsswipe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class Party extends ListActivity {
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> partyList;
// url to get all products list
private static String url = "http://192.168.1.6/politiciansnpolitics/appphp/parties.php" ;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PARTY = "party";
private static final String TAG_ID = "party_id";
private static final String TAG_NAME = "party_name";
private static final String TAG_PIC = "party_logo";
// products JSONArray
JSONArray party = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_party);
Drawable rightArrow = getResources().getDrawable(R.drawable.worldmap2);
// setting the opacity (alpha)
rightArrow.setAlpha(100);
// Hashmap for ListView
partyList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadParties().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String party_id = ((TextView) view.findViewById(R.id.id)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),Party_Desc.class);
// sending pid to next activity
in.putExtra(TAG_ID, party_id);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadParties extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Party.this);
pDialog.setMessage("Loading parties. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread
.penaltyLog().build());
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
party = json.getJSONArray(TAG_PARTY);
// looping through All Products
for (int i = 0; i <party.length(); i++) {
JSONObject c = party.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap <span class="vf7210h94y" id="vf7210h94y_22">key</span> => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
partyList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),TopRatedFragment.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter( Party.this,partyList,R.layout.list_item, new String[] { TAG_ID,
TAG_NAME},
new int[] { R.id.id, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
I think, you should try using your application context instead of Activity here:
...
pDialog = new ProgressDialog(Party.this);
...
Window leaked error comes when some function tries to access the activity while its in background!,
So make sure you terminate your dialog when the activity goes to background.
In your case, add this to your activity.
#Override
public void onPause() {
super.onPause();
if(pDialog != null){
pDialog.dismiss();
}
}
![here there are 3 edit text box. where i am using json to check the login id and password details and another text box is for the selection of the server address. the only criteria is that all these should be done with a single button ie the login button.
can any one help me with the code]1
the code is as follows
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 String serve;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// JSON Node names
private static final String TAG_SUCCESS = "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();
new SelectServerAddress().execute();
}
});
}
// this class is for selection of the server address
class SelectServerAddress extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... arg0) {
return null;
}
}
// 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
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Checking..");
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();
//if (serve == "")
//{
//serve = "192.168.0.101/gly_prov_V1";
//}
//else
//{
//serve = "glydenlewis.esy.es";
//}
// URL to check username & password
final String url_check_user = "http://" + serve +"/gly_prov_V1/android_check.php";
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uname", user));
params.add(new BasicNameValuePair("psd", pswrd));
params.add(new BasicNameValuePair("server",serve));
// getting JSON Object
// Note that create product url accepts POST method
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(TAG_SUCCESS);
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);
startActivity(i);
finish(); // closing this screen
}
else
{
// successfully login
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish(); // closing this screen
}
} else {
Toast.makeText(getApplicationContext(), "Wrong Credentials", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
You can execute tasks in serial manner. Take the output of first task as input to the second task.
But you have to implement a cancel mechanism if the activity is destroyed while your tasks is actually running. a simple approach is to make tasks references as a class member and cancel it when activity's onStop() method is called.
class static SelectServerAddress extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... urls) {
return getAddress(urls[0]);
}
#Override
protected void onPostExecute(String serverAddress) {
// Call login service
mLoginTask = new CreateNewUser(serverAddress);
mLoginTask.execute();
}
}
Edit:
Update button click listener code to this:
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new SelectServerAdress().execute();
}
});
Then update SelectServerAdress class and add this method:
#Override
protected void onPostExecute(String serverAddress) {
serve = serverAddress;
new SelectServerAddress().execute();
}
I'm using an async task to download a json string from my server. This is the code I'm using:
How I use it is, first I open the profile activity, then on the oncreate event on the profile activity, I call this async task to get the information. When this finishes it calls a function on the profile activity using its context to display the information. If some error occurred, then I call the finish function on the activity and display a message.
The problem is, the first time when I visit the profile activity, it works fine, then the second time it goes into a black screen. The interesting thing is I can press back and it will end the black screen but go back to previous activity (the one where I click the button to open the profile activity).
Does anyone know whats the problem here?
Thanks.
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import sord.http.Http;
import sord.ids_connect.Activity_Profile;
import sord.ids_connect.R;
import sord.object.User;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.util.Pair;
/*
* This asynchronous task gets profile data.
*
*/
public class Async_get_profile extends AsyncTask<String, Void, Pair<String,Integer>> {
Activity_Profile callerContext = null;
ProgressDialog progressDialog = null;
int targetID;
public Async_get_profile(Activity_Profile callerContext, int targetID) {
this.callerContext = callerContext;
this.targetID = targetID;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog((Context) callerContext);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Pair<String,Integer> doInBackground(String... params) {
List<NameValuePair> urlValues = new ArrayList<NameValuePair>();
urlValues.add(new BasicNameValuePair("taskID", "5"));
urlValues.add(new BasicNameValuePair("userID", Integer.toString(User.currentUser.id, 10)));
urlValues.add(new BasicNameValuePair("targetID", Integer.toString(targetID, 10)));
Pair<String,Integer> response = Http.GetHTTPResponse(((Context) callerContext).getResources().getString(R.string.host), urlValues);
return response;
}
#Override
protected void onPostExecute(Pair<String,Integer> responsePair) {
try {
JSONObject object = Http.ValidateObjectResponse(((Context) callerContext), responsePair);
if (object != null) {
String firstname = object.getString("firstname");
String lastname = object.getString("lastname");
String password = object.getString("password");
String email = object.getString("email");
String phone = object.getString("phone");
String website = object.getString("website");
String status = object.getString("status");
String biotext = object.getString("biotext");
int roldId = object.getInt("role_id");
String datejoined = object.getString("datejoined");
String datelastactive = object.getString("datelastactive");
int active = object.getInt("active");
String picURL = object.getString("picURL");
if (targetID == User.currentUser.id) {
User.currentUser.firstName = firstname;
User.currentUser.lastName = lastname;
User.currentUser.password = password;
User.currentUser.emailAddress = email;
User.currentUser.phoneNumber = phone;
User.currentUser.websiteLink = website;
User.currentUser.statusText = status;
User.currentUser.bioText = biotext;
User.currentUser.dateJoined = datejoined;
User.currentUser.dateLastActive = datelastactive;
User.currentUser.picURL = picURL;
callerContext.ProfileCallback(User.currentUser);
} else {
User user = new User(
false,
targetID,
firstname,
lastname,
password,
email,
phone,
website,
status,
biotext,
roldId,
datejoined,
datelastactive,
active,
picURL
);
callerContext.ProfileCallback(user);
}
} else {
callerContext.finish();
}
} catch (Exception e) {
Log.d("ERROR", e.getMessage());
callerContext.finish();
}
progressDialog.dismiss();
}
}
EDIT:
Logcat
log.txt
I am creating simple system that has a windows service running, complete with a table of users, and I want to validate someone's login credentials by sending something to the service. I am trying to send their username and password, but I keep getting an error with my Async Task. I know that you're not supposed to mess with UI stuff in there and I am not. Originally I had a call to another activity in there but I commented it out. Now the only thing in doInBackground is setting a boolean value to true if the validation was good. From there I read the value after the async has executed, and then put together a bundle to move to the next place. I just don't know what's wrong here. It has been awhile since I've programmed in Android so maybe I'm missing something stupid. If anyone could help me out I would greatly appreciate it! Thank you. This could also be an issue with sending the information to the service?
UPDATE: After adding in the internet usage in the manifest, if I have the log.d in the program in my doInBackground, it prints out. If I don't have it, the result value stays false. It looks like there is some issue with the connection between my service and android app...
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
private static final int DATA_FROM_MAIN_ACTIVITY = 1;
private static final String SERVICEURL = "http://localhost:56638/ClientService.svc";
private EditText userTextBox, passTextBox;
private Button loginButton;
private String uName, pass;
private Boolean result = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userTextBox = (EditText) findViewById(R.id.userTextBox);
passTextBox = (EditText) findViewById(R.id.passTextBox);
loginButton = (Button) findViewById(R.id.loginButton);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uName = userTextBox.getText().toString();
pass = passTextBox.getText().toString();
SendLoginMessage task = new SendLoginMessage();
task.execute(uName, pass);
if (result.equals(true)) {
Intent goToMainScreen = new Intent(getApplicationContext(),
MainActivity.class);
goToMainScreen.putExtra("username", uName);
goToMainScreen.putExtra("password", pass);
startActivityForResult(goToMainScreen,
DATA_FROM_MAIN_ACTIVITY);
} else {
Toast.makeText(
getApplicationContext(),
"There was an issue with your username or password.",
Toast.LENGTH_LONG).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;
}
private class SendLoginMessage extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// Log.d("message almost at server, " + textFromArea, selected,
// null);
}
#Override
protected Void doInBackground(String... names) {
ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("username", names[0]));
postParams.add(new BasicNameValuePair("password", names[1]));
String response = null;
try {
response = HttpClient.executeHttpPost(SERVICEURL, postParams);
String newResponse = response.toString();
newResponse = newResponse.replaceAll("\\s+", "");
// if user was authenticated...
if (newResponse.equals(true)) {
result = true;
// creating an intent to take user to next page.
// load their DB objects on the
// on create in other activity
// pass the username/password to next activity
// then make a request to the server for their database
// objects.
// Intent goToMainScreen = new
// Intent(getApplicationContext(), MainActivity.class);
// goToMainScreen.putExtra("username", names[0]);
// goToMainScreen.putExtra("password", names[1]);
// startActivityForResult(goToMainScreen,
// DATA_FROM_MAIN_ACTIVITY);
}
} catch (Exception e) {
Log.d("ERROR", "exception in background");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Toast.makeText(getApplicationContext(),
// .show();
}
}
}
Do it like this:
private class SendLoginMessage extends AsyncTask<String, String, Boolean> {
#Override
protected Boolean doInBackground(String... names) {
ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("username", names[0]));
postParams.add(new BasicNameValuePair("password", names[1]));
String response = null;
try {
response = HttpClient.executeHttpPost(SERVICEURL, postParams);
String newResponse = response.toString();
newResponse = newResponse.replaceAll("\\s+", "");
// if user was authenticated...
if (newResponse.equals("true")) {
return true;
}
} catch (Exception e) {
Log.d("ERROR", "exception in background");
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
Intent goToMainScreen = new Intent(getApplicationContext(),
MainActivity.class);
goToMainScreen.putExtra("username", uName);
goToMainScreen.putExtra("password", pass);
startActivityForResult(goToMainScreen,
DATA_FROM_MAIN_ACTIVITY);
} else {
Toast.makeText(
getApplicationContext(),
"There was an issue with your username or password.",
Toast.LENGTH_LONG).show();
}
}
}
and in your onClick() just call execute()
uName = userTextBox.getText().toString();
pass = passTextBox.getText().toString();
SendLoginMessage task = new SendLoginMessage();
task.execute(uName, pass);
After execution is finished onPostExecute() will be called and your Activity will start depending on result variable.
Don't check your result variable after you invoke execute() because execute() is invoked asynchronously. By the time you check your global result variable, your doInBackground() might not have been finished. Using my approach you don't need a global variable. Please read doc carefully before using any component.