Semi-noob with Java here.
I am trying to set a TextView inside my doInBackground() inside of my Async task. According to my research, I can not modify the main thread doing this so messing around with TextViews is out of the question here. So what I would like to do instead is use a string. I need this string to be accessible in the main class.
How can I do this?
I tried String loginresult = "Login Successful! Please Wait..."; but I am not able to access that string anywhere. I tried marking it as public but that is an illegal modifier inside a doInBackground().
Maybe strings is not the best way to go about doing this, if so, what would all you geniuses out there suggest?
Here is my async code, I put arrows in the areas I am having an issue. Any help would be appreciated for this noob :)
class PostTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("SENCIDE", "Execute HTTP Post Request");
//Executes link, login.php returns true if username and password match in db
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent()).toString();
Log.w("SENCIDE", str);
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("SENCIDE", "TRUE");
-----> result.setText("Login Successful! Please Wait...");
}else
{
Log.w("SENCIDE", "FALSE");
------> result.setText(str);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Dummy code
for (int i = 0; i <= 100; i += 5) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(i);
}
return "All Done!";
}//end doinbackground
StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}//end StringBuilder
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// turns the text in the textview "Tbl_result" into a text string called "tblresult"
TextView tblresult = (TextView) findViewById(R.id.tbl_result);
// If "tblresult" text string matches the string "Login Successful! Please Wait..." exactly, it will switch to next activity
if (tblresult.getText().toString().equals("Login Successful! Please Wait...")) {
Intent intent = new Intent(NewAndroidLogin.this, Homepage.class);
//take text in the username/password text boxes and put them into an extra and push to next activity
EditText uname2 = (EditText)findViewById(R.id.txt_username);
String username2 = uname2.getText().toString();
EditText pword2 = (EditText)findViewById(R.id.txt_password);
String password2 = pword2.getText().toString();
intent.putExtra("username2", username2 + "&pword=" + password2);
startActivity(intent);
}
}//end onPostExecute
}//end async task
Change your AsyncTask to use String as progress parameter type:
AsyncTask<String, String, String>
Change onProgressUpdate() to update progress
#Override
protected void onProgressUpdate(String... values) {
result.setText(values[0]);
}
And then report the progress:
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("SENCIDE", "TRUE");
publishProgress("Login Successful! Please Wait...");
}else
{
Log.w("SENCIDE", "FALSE");
publishProgress(str);
}
Make String loginresult = "Login Successful! Please Wait..."; as global and
runOnUiThread(new Runnable() {
#Override
public void run() {
str = inputStreamToString(response.getEntity().getContent()).toString();
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("SENCIDE", "TRUE");
result.setText("Login Successful! Please Wait...");
}
else
{
Log.w("SENCIDE", "FALSE");
result.setText(str);
}
}
} );
Declare Handler at class level:
Handler handler;
Initialize Handler in onCreate() method of Activity:
// Doing this inside the onCreate() method of Activity
// will help the handler to hold the reference to this Activity.
handler = new Handler();
Call it within the background thread:
#Override
protected String doInBackground(String... params) {
handler.post(new Runnable(){
public void run(){
// SET UI COMPONENTS FROM HERE.
}
});
}
Related
I am having trouble with my code where i have my Activity which i use to call google api's and retrieve jsons, deserialize them and use it's Polylines to draw on the map.
The problem is that getMapAsync() which sends the callback for onMapReady() (which is used to create the map) is executed immediately after executing my Async Tasks which retrieves necessary data to create the map.
How can i make this happen without stopping the UI thread? I tried doing this calling .execute.get() which freeze the UI thread. But if i do that, i won't be able to use ProgressDialog to inform the users about the delay for fetching data from the servers, which they will be exposed to a frozen UI until the task is complete. How can i do this?
public class RouteAssistantActivity extends Activity implements OnMapReadyCallback{
public GoogleMapsDirectionsResponse dirRes;
public GoogleMapsDistanceResponse disRes;
public String jsonString;
private String mapsAPIKey;
private String directionsBaseURL;
private String distanceBaseURL;
MapFragment mapFragment;
private ProgressDialog progress;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ra_route_assisstant);
mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.ra_map);
progress = new ProgressDialog(RouteAssistantActivity.this);
progress.setTitle("Please Wait");
progress.setMessage("Retrieving Data from the Server");
progress.setIndeterminate(true);
try {
ApplicationInfo appInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
if (appInfo.metaData != null) {
mapsAPIKey = appInfo.metaData.getString("com.google.android.maps.v2.API_KEY");
directionsBaseURL = appInfo.metaData.getString("com.google.android.maps.directions.baseURL");
distanceBaseURL = appInfo.metaData.getString("com.google.android.maps.distance.baseURL");
}
} catch (PackageManager.NameNotFoundException e) {
Log.e("Meta Error", "Meta Data not found. Please check the Manifest and the Meta Data Package Names");
e.printStackTrace();
}
//Test
String directionsURL = directionsBaseURL+"origin=6.948109,79.858191&destination=6.910176,79.894347&key="+mapsAPIKey;
String distanceURL = distanceBaseURL+"units=metric&origins=6.948109,79.858191&destinations=6.910176,79.894347&key="+mapsAPIKey;
Log.e("CA Debug","URL : " + directionsURL);
Log.e("CA Debug","URL : " + distanceURL);
new configurationSyncTask().execute(distanceURL,"distance");
new configurationSyncTask().execute(directionsURL, "direction");
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng rajagiriya = new LatLng(6.910176, 79.894347);
String points = dirRes.getRoutes().get(0).getOverviewPolyline();
List<LatLng> list = PolyUtil.decode(points);
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(rajagiriya, 13));
googleMap.addMarker(new MarkerOptions()
.title("Rajagiriya")
.snippet("My Place")
.position(rajagiriya));
googleMap.addPolyline(new PolylineOptions()
.geodesic(false)
.addAll(list)
.color(Color.RED)
.width(25));
}
private class configurationSyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
progress.show();
}
#Override
protected String doInBackground(String... params) {
String url = params[0];
String type = params[1];
Log.d("CA Debug", getClass().getSimpleName() + " --> Real URL : " + url);
Log.d("CA Debug", getClass().getSimpleName() + " --> doInBackground requesting content");
jsonString = requestContent(url);
// if the output is null, stop the current task
if (jsonString == null) {
Log.d("CA Debug", getClass().getSimpleName() + " --> Stopping Async Task");
this.cancel(true);
Log.d("CA Debug", getClass().getSimpleName() + " --> Async Task Stopped");
}
return type;
}
#Override
protected void onPostExecute(String types) {
if (types.equalsIgnoreCase("distance")) {
disRes = GMapsDistanceResponseJSONDeserializer.deserialize(jsonString);
} if (types.equalsIgnoreCase("directions")) {
dirRes = GMapsDirectionsResponseJSONDeserializer.deserialize(jsonString);
}
progress.dismiss();
}
}
public String requestContent(String url) {
Log.d("CA Debug",getClass().getSimpleName()+" --> URL : "+url);
try {
URL urlObj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) urlObj.openConnection();
con.setChunkedStreamingMode(0);
con.setRequestMethod("GET");
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null,null, new SecureRandom());
con.setSSLSocketFactory(sc.getSocketFactory());
InputStream clientResponse;
String jsonString;
int status = con.getResponseCode();
if(status >= HttpURLConnection.HTTP_BAD_REQUEST){
Log.d("CA Debug", getClass().getSimpleName()+" --> Bad Request");
jsonString = null;
} else {
Log.d("CA Debug", getClass().getSimpleName()+" --> converting Stream To String");
clientResponse = con.getInputStream();
jsonString = convertStreamToString(clientResponse);
}
Log.d("CA Debug", getClass().getSimpleName()+" --> JSON STRING : " + jsonString);
return jsonString;
} catch (IOException | NoSuchAlgorithmException | KeyManagementException e) {
Log.d("CA Debug", getClass().getSimpleName()+" --> Error when creating an Input Stream");
e.printStackTrace();
}
return null;
}
public String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
return sb.toString();
}
}
Quick and somewhat dirty solution would be to execute both AsyncTasks on a single AsyncTask and then on its onPostExecute code invoke getMapAsync. this way you will be sure your tasks finished before you dealing with map's readyness.
Firstly, run tasks after onMapReady because you will get rid of
concern of ready map.
Your async tasks are not parallel, they working on background but second one will be executed after first one completed, check this link
Move some parts of onMapReady to onPostExecute, something like below
Move
#Override
protected void onPostExecute(String types) {
if (types.equalsIgnoreCase("distance")) {
disRes = GMapsDistanceResponseJSONDeserializer.deserialize(jsonString);
}if (types.equalsIgnoreCase("directions")) {
dirRes = GMapsDirectionsResponseJSONDeserializer.deserialize(jsonString);
String points = dirRes.getRoutes().get(0).getOverviewPolyline();
List<LatLng> list = PolyUtil.decode(points);
googleMap.addPolyline(new PolylineOptions()
.geodesic(false)
.addAll(list)
.color(Color.RED)
.width(25)
);
}
}
AsyncTask.SERIAL_EXECUTOR is used to force AsyncTask to execute in Serial Fashion.
More over for your case a little trick will do the job.
Create call back for same AsyncTask and pass different parameters to differentiate the functions.
Now in the second call back initiate mapFragment.getMapAsync(this);
public class MainFragment ...
{
DataDownloader dataDownloader;
int processCount=1;
void initiateProcessFirst(){
new DataDownloader(this,processCount ).execute();
}
public void initiateSecondProcess(){
processCount++;
new DataDownloader(this,processCount ).execute();
}
public void secondProcessCompleted(){
mapFragment.getMapAsync(this);
}
}
AsyncTask Logic goes like the below
public class DataDownloader extends AsyncTask<Void,Void,Boolean> {
MainFragment context;
int processCount;
public DataDownloader(MainFragment context ,int processCount){
this.context=context;
this.processCount=processCount;
}
#Override
protected Boolean doInBackground(Void... params) {
boolean status=false;
// Do logic according to the Process Count
return status;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if(processCount==1)
context.initiateSecondProcess();
else
context.secondProcessCompleted();
}
}
I am working in Android Technology.In my application i am fetching the data from web service i used A sync Task for consuming web service.It show the data correctly on Toast i.e true or false but My Progress Bar is continuously moving it does not stopped when Background task completed its execution i called dismiss method in onPostExecute().But it failed to dismiss the progress bar.Again it start calling web service but progress bar is not dismmed.
Can you tell me what i did wrong in my code.Please solve my problem..
I am attaching source code here
Async task
public class MyTask extends AsyncTask<String,Void,String>
{
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
Toast.makeText(getApplicationContext(), ""+result,Toast.LENGTH_LONG).show();
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd=new ProgressDialog(MainActivity.this);
pd.setMessage("Please Wait");
pd.setCancelable(false);
pd.setIndeterminate(false);
pd.show();
}
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
v=new Validate();
String result;
result=v.SendParam(url,user,pass);
return result;
}
}
Here id Validate.java code
class Validate
{
ArrayList<NameValuePair> namevaluepair;
InputStream is;
String res;
public String SendParam(String url,String username,String password)
{
try
{
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
// add parameter here
namevaluepair=new ArrayList<NameValuePair>();
namevaluepair.add(new BasicNameValuePair("id",username));
namevaluepair.add(new BasicNameValuePair("password",password));
post.setEntity(new UrlEncodedFormEntity(namevaluepair));
HttpResponse response=client.execute(post);
HttpEntity entity=response.getEntity();
is=entity.getContent();
}
catch(Exception e)
{
Log.d("Httpconnection","error",e);
}
// read response from
try
{
BufferedReader reader=new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder builder=new StringBuilder();
String line;
while((line=reader.readLine())!=null)
{
builder.append(line+"\n");
}
is.close();
res=builder.toString();
}
catch(Exception e)
{
Log.d("reading Input Stream","",e);
}
return res;
}
}
Your code should work fine (the dialog should be dismissed without problems).
However I'm guessing your sendParam method is throwing an error, and so the onPostExecute method is not reached. Replace doInBackground with this in your code :
#Override
protected String doInBackground(String... arg0) {
try {
v=new Validate();
String result;
result=v.SendParam(url,user,pass);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
super.onPostExecute(result);
Try to remove this and execute. hope it works.
I'm saving two parts of data the users password and username to use at a later data and a random combination of letters to then check when the app is executed again to avoid the login screen again.
I had this working yesterday and for some reason, I expect I misplaced code when adding a feature and now cannot get it working again, I've tried all day to fix it and yet I cannot.
EDIT1: For some reason, it goes to the else statement on the "CheckPrefs" method, which I CANNOT UNDERSTAND.
EDIT2: It saves the preferences fine and goes to the intent but, it just can't read it.
Code:
public static final String PREFS_NAME = "MyPregs";
public static final String PREFS_CHECK = "CheckSignedIn";
public static final String UID ="";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CheckPrefs();
// Login button clicked
ok = (Button) findViewById(R.id.btn_login);
ok.setOnClickListener(this);
result = (TextView) findViewById(R.id.lbl_result);
}
private void CheckPrefs() {
// TODO Auto-generated method stub
//checks to see if the user has signed in before if they have it gets there data from SharedPreferences and checks against our database via HttpPost.
SharedPreferences settings = getSharedPreferences(PREFS_CHECK, 0);
String SCheck1 = settings.getString("key4", null);
if (SCheck1 != null && equals(UID)) {
Intent c = new Intent(this, CheckUserInfo.class);
startActivity(c);
} else {
}
}
//create bracket.
public void postLoginData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
// Add user name and password
uname = (EditText) findViewById(R.id.txt_username);
String username = uname.getText().toString();
pword = (EditText) findViewById(R.id.txt_password);
String password = pword.getText().toString();
SharedPreferences signedin = getSharedPreferences(PREFS_CHECK, 0);
SharedPreferences.Editor editor1 = signedin.edit();
editor1.putString("key4", UID);
editor1.commit();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("key1", username);
editor.putString("key2", password);
editor.commit();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("HttpPost", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("HttpPost", "TRUE");
result.setText("Login successful");
try {Thread.sleep(250);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent login = new Intent(LogIn.this, ChatService.class);
startActivity(login);
} else {
Log.w("HttpPost", "FALSE");
result.setText(str);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
public void onClick(View view) {
if (view == ok) {
postLoginData();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(pword.getWindowToken(), 0);
}
// Click end
}
// if statement
}
// class ends here
need to see where you are saving your preferences, so we can match it up with how you're calling your preferences... but, is this a typo?
public static final String PREFS_NAME = "MyPregs";
Should it be "MyPrefs" instead of "MyPregs"?
You have
if (SCheck1 != null && equals(UID))
but do you maybe mean to say
if (SCheck1 != null && !SCheck.equals(UID))
?
You could use the 'reverse comparison' pattern too:
if (UID.equals(SCheck1)) {
} else {
}
This way, you don't have to bother checking SCheck1 == null. UID.equals(null) will return false instead of null.equals(UID) throwing a NullPointerException.
I'm trying to add an AsyncTask to the following class but I'm not sure where to start. I would like to encapsulate the entire class if possible. I'm new to Android and Java so I really have no idea about what I'm doing. The following class works, and I can send all the information to my database properly. Each time the user's location is updated, the program first checks a table in the database for the user ID; if it does not exist in the table the GPS coordinates are sent, but if the user ID is in the table, the coordinates are not sent and the program stops sending location updates. This works like it should, but it locks up my UI and throws an ANR error when attempting to interact. I know that I need to implement an AsyncTask, but I need some guidance. Below is the complete code for the class. Any help would be great!
public class FindLocation {
protected static final Context SendLocation = null;
private LocationManager locManager;
private LocationListener locListener;
Context ctx;
public FindLocation(Context ctx) {
this.ctx = ctx;
}
public void startLocation(final Context context, String usr_id2) {
final String usr = usr_id2;
//get a reference to the LocationManager
locManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//checked to receive updates from the position
locListener = new LocationListener() {
public void onLocationChanged(Location loc) {
String lat = String.valueOf(loc.getLatitude());
String lon = String.valueOf(loc.getLongitude());
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", usr));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/test/example.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
String ct_name = json_data.getString("phoneID");
if(ct_name == usr) {
locManager.removeUpdates(locListener);
}
}
}
catch(Exception e){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/test/example.php");
try {
List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(2);
nameValuePairs1.add(new BasicNameValuePair("lat", lat));
nameValuePairs1.add(new BasicNameValuePair("lon", lon));
nameValuePairs1.add(new BasicNameValuePair("id", usr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
httpclient.execute(httppost);
}
catch (ClientProtocolException g) {
// TODO Auto-generated catch block
} catch (IOException f) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void onProviderDisabled(String provider){
}
public void onProviderEnabled(String provider){
}
public void onStatusChanged(String provider, int status, Bundle extras){
}
};
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 0, locListener);
}
}
All you should have to do is:
modify FindLocation class by extending asynctask
change startLocation for an override of doInBackground.
Then call the execute method of your asynctask instead of startLocation.
Also, in your case, an asynctask may not be the best. Usually you use an asynctask because you want to do something in the background and then, when the task is done, update some ui components with the result of the background operation. Here, as you just want something in the background but no UI update, you could be better using a normal thread :
make you class extend thread
change startLocation for an override of run
start your thread instead of calling startLocation
--Update with details --
This could be simpler but the idea to get more familiar with asyncTask ia a good one too.
public class LocationFinder extends Thread {
public LocationFinder( Context ctx ) {
this.ctx = ctx;
}
public void start( String userId ) {
this.userId = userId;
super.start();
}
//defensive programming : prevent your thread from beeing started in an undesired way
#Override
public void start() {
throw new IllegalStateException( "LocationFinder can't be started using start(). Prefer start( int )." );
}
public void run() {
//remaining of the code of startLocation except the first line.
}
}
to use your thread then do in an activity :
new LocationFinder( this ).start( userId );
private class BackgroundLoader extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
protected Long doInBackground() {
dialog = new ProgressDialog(ctx);
dialog.show();
}
protected void doInBackground() {
// do all your stuff here that doesn't modify the UI
}
protected void onPostExecute(Long result) {
// do what you need to to the UI
dialog.dismiss();
}
Then to create an instance call new BackgroundLoader().execute(); in your onCreate() method
I'm using eclipse and have been trying for a while to do login using http request and php script to connect to the server side.
The problem is when i click the login button nothing happens,my guess is there is a problem with the OnClikListener or the data for the textfield is not been send to the server
Here is my code.
public class LogInActivity extends Activity implements OnClickListener
{
Button ok,back,exit;
TextView result;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ok = (Button)findViewById(R.id.btn_login);
ok.setOnClickListener(LogInActivity.this);
result = (TextView)findViewById(R.id.lbl_result);
}
public void postLoginData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/androidRegistration/login.php");
try {
EditText uname = (EditText)findViewById(R.id.txt_username);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.txt_password);
String password = pword.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.w("LogInActivity", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent()).toString();
Log.w("LogInActivity", str);
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("LogInActivity", "TRUE");
result.setText("Login successful");
}else
{
Log.w("LogInActivity", "FALSE");
result.setText(str);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return total;
}
#Override
public void onClick(View view) {
if(view == ok){
postLoginData();
}
}
}
You should debug to check if the problem is with the onClick or with the HTTP transport.
Inside onClick I personally wouldn't check view like yours. Not sure if it's working or not but I usually use:
if(null != view)switch(view.getId()){
case R.id.btn_login: postLoginData();break;
}
You should try to scope down where the problem is so it's clear what need fixing.
I'd suggest you add Log.d right after you enter onClick to see if the listener is invoke when you click the screen.
Consider using Log.d(TAG, message) statements to debug your code. The logs can be seen using `adb logcat' or eclipse DDMS. This should tell you the flow of your code. You can also debug using breakpoints in eclipse.
Also, do not perform network I/O in the main loop. Its really bad for you users. Consider using an AsyncTask