I am running a long running process (which is an servlet call) inside an AsyncTask doInBackground which may run for more than 5 minutes. But after 5 minutes the servlet is returned and I am getting a timeout problem.
Below is my code:
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.example.hanamom.LoginActivity.GetXMLTask;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.ProgressDialog;
public class NewInstallationActivity extends Activity {
Button install;
EditText branch_enter;
EditText cl_enter;
EditText sid_enter;
EditText sidpwd_enter;
EditText systempwd_enter;
EditText instance_enter;
EditText installationlocation_enter;
Bundle extras;
EditText desc_enter;
ProgressDialog pd;
public static final String URL = "<a servlet call>";
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
Intent intent;
String login_user,host,rootuser,rootpassword;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.install);
addListenerOnButton();
Log.e("test", "Entered New Instlalaiton activity");
branch_enter = (EditText) findViewById(R.id.branch_enter);
cl_enter = (EditText) findViewById(R.id.cl_enter);
sid_enter = (EditText) findViewById(R.id.sid_enter);
sidpwd_enter = (EditText) findViewById(R.id.sidpwd_enter);
systempwd_enter = (EditText) findViewById(R.id.systempwd_enter);
instance_enter=(EditText) findViewById(R.id.instance_enter);
installationlocation_enter=(EditText) findViewById(R.id.installationlocation_enter);
Bundle extras = this.getIntent().getExtras();
login_user=extras.getString("login_user").trim();
host = extras.getString("promptshost");
rootuser = extras.getString("lrootUser");
rootpassword = extras.getString("lrootpwd");
Log.e("login user",login_user);
Log.e("rootuser=",rootuser);
Log.e("rootpassword=",rootpassword);
}
private void addListenerOnButton() {
// TODO Auto-generated method stub
final Context context = this;
branch_enter = (EditText) findViewById(R.id.branch_enter);
cl_enter = (EditText) findViewById(R.id.cl_enter);
sid_enter = (EditText) findViewById(R.id.sid_enter);
sidpwd_enter = (EditText) findViewById(R.id.sidpwd_enter);
systempwd_enter = (EditText) findViewById(R.id.systempwd_enter);
instance_enter=(EditText) findViewById(R.id.instance_enter);
installationlocation_enter=(EditText) findViewById(R.id.installationlocation_enter);
install = (Button) findViewById(R.id.install);
install.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
}
});
}
private class GetXMLTask extends AsyncTask<String, Void, String> {
String response = "false";
private ProgressDialog pd;
protected void onPreExecute() {
pd = new ProgressDialog(NewInstallationActivity.this);
pd.setMessage("Please wait while SAP HANA system is being Installed..");
pd.setIndeterminate(false);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setProgress(0);
pd.show();
}
protected String doInBackground(String... urls) {
try {
Log.e("NewInstallationActivty", "New installation");
String branch=branch_enter.getText().toString();
String cl = cl_enter.getText().toString();
String sid=sid_enter.getText().toString();
String sidpwd=sidpwd_enter.getText().toString();
String systempwd=systempwd_enter.getText().toString();
String instance=instance_enter.getText().toString();
String installationlocation=installationlocation_enter.getText().toString();
Log.e("Branch=",branch);
Log.e("Host=",host);
Log.e("sid=",sid);
Log.e("sidpwd=",sidpwd);
Log.e("systempwd=",systempwd);
Log.e("instance=",instance);
Log.e("installationlocation=",installationlocation);
Log.e("rootuser=",rootuser);
Log.e("rootpassword=",rootpassword);
// String osuser=osuser_enter.getText().toString();
// String ospassword=ospassword_enter.getText().toString();
Log.e("NewInstlalationActivity", "installtion");
postParameters.add(new BasicNameValuePair("branch",branch));
postParameters.add(new BasicNameValuePair("cl", cl));
postParameters.add(new BasicNameValuePair("sid", sid));
postParameters.add(new BasicNameValuePair("sidpwd", sidpwd));
postParameters.add(new BasicNameValuePair("systempwd",systempwd));
postParameters.add(new BasicNameValuePair("instance",instance));
postParameters.add(new BasicNameValuePair("installationlocation",installationlocation));
postParameters.add(new BasicNameValuePair("host",host));
postParameters.add(new BasicNameValuePair("rootuser", rootuser));
postParameters.add(new BasicNameValuePair("rootpassword", rootpassword));
postParameters.add(new BasicNameValuePair("intent","install"));
Log.e("NewInstlalationActivity", "post parameters");
for (String url : urls) {
response = CustomHttpClient.executeHttpPost(url,postParameters);
}
}
catch(Exception e) {}
return "Success";
}
protected void onPostExecute(String output) {
Log.e("Login Activity",response);
while(!response.trim().equals("True"))
{
pd.show();
pd.setProgress(100);
continue;
}
if (response.trim().equals("True"))
{
Log.e("Entered Response = True", response);
pd.dismiss();
Intent intent = new Intent(getBaseContext(), NewInstallationActivity.class);
startActivity(intent);
}
else
{
Log.e("Else code","Else");
AlertDialog alertDialog = new AlertDialog.Builder(
NewInstallationActivity.this).create();
alertDialog.setTitle("Installation Failed!");
// Setting Dialog Message
alertDialog.setMessage(" Check logs at /var/tmp");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
}
}
}
}
Here my process dialog will wait until I get a True from the servlet but exactly after 5 minutes, it is sending a false.
Is there any method to wait for more than 5 minutes. Any hint would be helpful.
Thanks.
You can try the following :
private final static long TIMETOWAIT = 30000; // Set your timeout.
....
GetXMLTask.get(TIMETOWAIT,TimeUnit.MILLISECONDS);
....
For reference :
http://developer.android.com/reference/android/os/AsyncTask.html#get%28long,%20java.util.concurrent.TimeUnit%29
Related
I am trying to load a popup window that contains an edittext and a datepicker.
I have included my code below.
Basically the initial window is closed as expected, but my pop up doesn't appear?
I have checked the xml call and the id is correct, no errors and for some reason my logcat in eclipse has stopped working but thats a different issue!
Hopefully someone can tell me what I have missed and / or doing wrong? I am new to android programming so please ignore my ignorance if it is something simple!
package com.zelphe.zelpheapp;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.zelphe.zelpheapp.library.DatabaseHandler;
import com.zelphe.zelpheapp.library.UserFunctions;
public class LoginActivity extends Activity
{
Button btnLogin;
Button Btnregister;
Button passreset;
EditText inputEmail, inputName, inputPassword;
DatePicker inputDOB;
private TextView loginErrorMsg;
/**
* Called when the activity is first created.
*/
private static String KEY_SUCCESS = "success";
private static String KEY_REGISTER = "doRegister";
private static String KEY_UID = "uid";
private static String KEY_USERNAME = "uname";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
Button btnReg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_test);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.loginbtn);
//loginErrorMsg = (TextView) findViewById(R.id.loginErrorMsg);
/**
* Login button click event
* A Toast is set to alert when the Email and Password field is empty
**/
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if ( ( !inputEmail.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) )
{
NetAsync(view);
}
else if ( ( !inputEmail.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Password field empty", Toast.LENGTH_SHORT).show();
}
else if ( ( !inputPassword.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Email field empty", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),
"Email and Password field are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working.
**/
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(LoginActivity.this);
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(false);
nDialog.show();
}
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
#Override
protected Boolean doInBackground(String... args){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessLogin().execute();
}
else{
nDialog.dismiss();
loginErrorMsg.setText("Error in Network Connection");
}
}
}
/**
* Async Task to get and send data to My Sql database through JSON respone.
**/
private class ProcessLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String email,password;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
email = inputEmail.getText().toString();
password = inputPassword.getText().toString();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Logging in ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
pDialog.setMessage("Loading User Space");
pDialog.setTitle("Getting Data");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
* Clear all previous data in SQlite database.
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/**
*If JSON array details are stored in SQlite it launches the User Panel.
**/
Intent upanel = new Intent(getApplicationContext(), MainActivity.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(upanel);
/**
* Close Login Screen
**/
finish();
}else if(Integer.parseInt(res) == 2)
{
pDialog.dismiss();
Toast.makeText(getApplicationContext(),
"Incorrect Password!", Toast.LENGTH_SHORT).show();
}
else
{
pDialog.dismiss();
initiatePopupWindow();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private PopupWindow pwindo;
private void initiatePopupWindow()
{
try
{
// We need to get the instance of the LayoutInflater
LayoutInflater inflater = (LayoutInflater) LoginActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.activity_register,(ViewGroup)
findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 350, 350, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
btnReg = (Button) layout.findViewById(R.id.btnReg);
btnReg.setOnClickListener((android.view.View.OnClickListener) reguser);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private OnClickListener reguser = new OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
inputName = (EditText) findViewById(R.id.name);
inputDOB = (DatePicker) findViewById(R.id.dob);
if ( ( !inputName.getText().toString().equals("")) &&
( getAge(inputDOB.getDayOfMonth(), inputDOB.getMonth(), inputDOB.getYear()) > 15) )
{
//register user
}
else if ( ( inputName.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Please enter your name", Toast.LENGTH_SHORT).show();
}
else if (( getAge(inputDOB.getDayOfMonth(), inputDOB.getMonth(), inputDOB.getYear()) < 16) )
{
Toast.makeText(getApplicationContext(),
"You must be at least 16 to use this app", Toast.LENGTH_SHORT).show();
}
}
};
}
public int getAge (int _year, int _month, int _day) {
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, a;
y = cal.get(Calendar.YEAR);
m = cal.get(Calendar.MONTH);
d = cal.get(Calendar.DAY_OF_MONTH);
cal.set(_year, _month, _day);
a = y - cal.get(Calendar.YEAR);
if ((m < cal.get(Calendar.MONTH))
|| ((m == cal.get(Calendar.MONTH)) && (d < cal
.get(Calendar.DAY_OF_MONTH)))) {
--a;
}
if(a < 0)
throw new IllegalArgumentException("Age < 0");
return a;
}
public void NetAsync(View view){
new NetCheck().execute();
}
}
Embarassingly enough, there is no issue with the popup, I had an error further up in my code, doh!
![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 have a problem with my project
here is my LoginActivity
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class LoginActivity extends Activity {
private final Context context = this;
EditText un;
EditText pw,ds;
TextView error;
String i;
String x;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
un=(EditText)findViewById(R.id.un);
pw=(EditText)findViewById(R.id.pwd);
error=(TextView)findViewById(R.id.tv_error);
}
public void clickHandler(View view){
Intent i = null;
switch (view.getId()){
case R.id.btnLogin:
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
/* String valid = "1";*/
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/android/cek.php", postParameters);
String res = response.toString();
res = res.trim();
res = res.replaceAll("\\s+","");
error.setText(res);
if (res.equals("1")){
i = new Intent (this, Menu.class);
startActivity(i);
} else {
error.setText("Sorry!! Username or Password salah");
}
} catch (Exception e) {
un.setText(e.toString());
}
break;
case R.id.registerBtn:
i = new Intent(this, RegisterActivity.class);
startActivity(i);
break;
case R.id.btnExit:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Keluar dari aplikasi ini?");
builder.setCancelable(false);
builder.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
});
builder.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Create and show the dialog
builder.show();
break;
}
}
public String uname(){
x = un.getText().toString();
return x;
}
}
and here is my KirimInfo.java
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
public class KirimInfo extends Activity {
String time,date,type,jln,y;
EditText usrn,ket,ds;
Spinner nj,st1;
TextView error;
String[] jalan = {"A.Yani","Ambengan", "Anjasmoro","Baliwerti","Basuki Rahmat","Bintoro","Ciliwung","Darmo Raya","Darmokali","Diponegoro Raya","Dharmawangsa","Dinoyo","Embong Kemiri","Embong Malang"};
String[] stat = {"Macet Total", "Padat", "Padat Merayap","Padat Lancar","Lancar","Sepi"};
/** Called when the activity is first created. */
LoginActivity l = new LoginActivity();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kirim_info);
ket=(EditText)findViewById(R.id.keterangan);
usrn=(EditText)findViewById(R.id.usrnm);
error=(TextView)findViewById(R.id.tv_error3);
nj=(Spinner)findViewById(R.id.namjal);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, jalan);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
nj.setAdapter(aa);
st1=(Spinner)findViewById(R.id.statusKepadatan);
ArrayAdapter<String> bb = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, stat);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
st1.setAdapter(bb);
}
public void clickHandler(View view){
Intent i = null;
switch (view.getId()){
case R.id.btnKirimInfo:
jln = jalan[nj.getSelectedItemPosition()];
type = stat[st1.getSelectedItemPosition()];
String y = l.uname();
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", y));
postParameters.add(new BasicNameValuePair("nama_jalan", jln));
postParameters.add(new BasicNameValuePair("keterangan", ket.getText().toString()));
postParameters.add(new BasicNameValuePair("status", type));
/* String valid = "1";*/
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/android/kepadatan.php", postParameters);
String res = response.toString();
res = res.trim();
res = res.replaceAll("\\s+","");
error.setText(res);
if (res.equals("1"))
error.setText("Data Berhasil Masuk");
else
error.setText("Gagal");
} catch (Exception e) {
error.setText(e.toString());
}
break;
case R.id.kembali:
i = new Intent(this, Menu.class);
startActivity(i);
break;
}
}
}
I want to send the username from LoginActivity.java to KirimInfo.java. because that I make method "uname" to pass the username.
but when I run the program, it pass empty or NULL even though I have write the username (whereas I have write down username and password correctly from the database)
what I want to ask, am I write the method "uname" correct? can you tell me how to write a correct method and initiate object so I can pass the username?
because I don't know how to make a method and initiate object in android correctly
please tell me how....any help will appreciate
Thank You
LoginActivity l = new LoginActivity();
String y = l.uname();
This is not right procedure for sending value from one activity to Another activity.
Add the following in your program.
in LoginActivity.java add :..
Whaen you call the KirimInfo.java Activity
add
Intent intent = new Intent(LoginActivity.this,KirimInfo.class);
intent.putExtra("username",""+uname());
in KirimInfo actrivity add the following
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String userName = bundle.getString("username");
when you in KirimInfo then you are accessing the UI of LoginActivity in uname() which is not a recommend way to do so.
If you want to transfer data between activities use Bundle
for example
Intent intent = new Intent(LoginActivity.this, KirimInfo.class);
intent.putExtra("USER_NAME", "Safarudin");
startActivity(intent);
and to get data in other activity use like this in OnCreate
String userName=getIntent().getStringExtra("USER_NAME");
I have this async Task on android 2.3.5
class InternetConnexionErrorAsync extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
mdpiImageView.setClickable(false);
journalsImageView.setClickable(false);
accountImageView.setClickable(false);
Toast.makeText(getBaseContext(),errorMessage , Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... aurl) {
try {
Thread.sleep(3450);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String unused)
{
finish();
}
}
Everything is working well.
When I try this in Android 4.0, I am newer accessint the onPostExecute.
Could you please help me. No error message, only that the onPostExecute is newer reached.
Whatever you need to update on the UI you need to do in onPostExecute.
The code below, take a look at onPostExecute - specifically the activity.xx() methods send updates to the main activity that do things on the UI.
For example:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import library.DatabaseHandler;
import library.JSONParser;
import library.UserFunctions;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.R;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginTask extends AsyncTask<String, Void, Integer> {
private ProgressDialog progressDialog;
private Polling activity;
private int id = -1;
private JSONParser jsonParser;
private static String loginURL = "http://davidjkelley.net/android_api/";
private static String registerURL = "http://davidjkelley.net/android_api/";
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_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private int responseCode = 0;
public LoginTask(Polling activity, ProgressDialog progressDialog)
{
this.activity = activity;
this.progressDialog = progressDialog;
}
#Override
protected void onPreExecute()
{
progressDialog.show();
}
protected Integer doInBackground(String... arg0) {
EditText userName = (EditText)activity.findViewById(R.id.emailEditText);
EditText passwordEdit = (EditText)activity.findViewById(R.id.passEditText);
String email = userName.getText().toString();
String password = passwordEdit.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
//user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(activity.getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
//Log.v("name", json_user.getString(KEY_NAME));
// Clear all previous data in database
userFunction.logoutUser(activity.getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL),
json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
responseCode = 1;
// Close Login Screen
//finish();
}else{
responseCode = 0;
// Error in login
}
}
} catch (NullPointerException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
return responseCode;
}
#Override
protected void onPostExecute(Integer responseCode)
{
EditText userName = (EditText)activity.findViewById(R.id.emailEditText);
EditText passwordEdit = (EditText)activity.findViewById(R.id.passEditText);
if (responseCode == 1) {
progressDialog.dismiss();
activity.loginReport(responseCode);
userName.setText("");
passwordEdit.setText("");
//shared prefences, store name
}
if (responseCode == 0) {
progressDialog.dismiss();
activity.loginReport(responseCode);
}
//if(responseCode == 202)
//activity.login(id);
//else
//activity.showLoginError("");
}
}
Here's the main activity, you can see what loginReport does:
public class Polling extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
private final static String TAG = "21st Polling:";
private Button loginButton;
private Button registerButton;
private CheckBox remember;
SharedPreferences sharedPreferences;
Toast toast;
ActionBar bar;
//DatabaseHandler ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate");
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText(R.string.login),
LoginFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.economics),
EconFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.elections),
ElectionsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.politics),
PoliticsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.science),
ScienceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.finance),
FinanceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.religion),
ReligionFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.military),
MilitaryFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.international),
InternationalFragment.class, null);
}
public void loginReport(int responseCode) {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
UserFunctions userFunctions = new UserFunctions();
Context context = getApplicationContext();
//login succeeded, sent when LoginTask doInBg sends a 1 to onPostExecute
if (responseCode == 1) {
loginButton = (Button)findViewById(R.id.loginButton);
loginButton.setText("Log Out");
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "Logged in.", duration);
toast.show();
bar.getTabAt(0).setText(db.getUserDetails().get(db.KEY_EMAIL));
//Log.v(TAG, db.getUserDetails().toString());
}
//login failed, sent when LoginTask doInBg sends a 0 to onPostExecute
if (responseCode == 0) {
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "Incorrect username/password", duration);
toast.show();
}
if (responseCode == 2) {
//logout button clicked, listened from within LoginFragment
//remove user from active sql db here rather than LoginFragment?!
bar.getTabAt(0).setText(R.string.login);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Logged out", duration);
toast.show();
userFunctions.logoutUser(context);
}
}
The solution I adopted, after the suggestion of #Davek804 is that I replace the AsyncTask with a delayed runable like this:
private Runnable mMyRunnable = new Runnable()
{
public void run()
{
finish();
}
};
Toast.makeText(getBaseContext(),errorMessage , Toast.LENGTH_LONG).show();
Handler myHandler = new Handler();
myHandler.postDelayed(mMyRunnable, 3450);
So the effect will be the same.
I found the solution here
Instead of using :
task.execute();
use :
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null);
I have an Activity that retrieves information from a url. I have 2 textviews which are multi-line (txtTitle & txtContent). If I populate them without using thread, it displays as multi-line. However, when I use a thread, the text views become single-line.
Is there anything I'm missing? Is the UI not completely ready when I tried putting text in it?
My sample code is below:
package com.mysite.app;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spanned;
import android.widget.TextView;
public class ViewNewsActivity extends Activity implements Runnable{
private ProgressDialog progressDialog = null;
private String apiUrl = "";
private String title = "";
private String content = "";
private Runnable viewNews;
private TextView txtTitle = null;
private TextView txtContent = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_news);
Intent myIntent = getIntent();
apiUrl = "http://www.mysite.com" + myIntent.getStringExtra("api_url");
Thread thread = new Thread(this);
thread.start();
progressDialog = ProgressDialog.show(ViewNewsActivity.this,
"Please wait...", "Retrieving News ...", true);
}
public void run() {
txtTitle = (TextView)findViewById(R.id.view_news_title);
txtContent = (TextView)findViewById(R.id.view_news_content);
getNews(apiUrl);
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
txtTitle.setText(title);
Spanned contentHtml = Html.fromHtml(content);
txtContent.setText(contentHtml.toString());
}
};
private void getNews(String apiUrl) {
String result = JSONUtils.getJSONResponse(apiUrl);
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(result);
title = jsonResponse.getString("title");
content = jsonResponse.getString("content");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}