I need to update a textView with data from remote db MYSQL, but I have a problem when I try to update the textview in AsyncTask.I tryed everything but it always give me a void textview.
This is my code:
public class Credits extends Activity implements OnClickListener{
private Button home;
private String user;
public TextView totSpesa;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String URL = "http://**********/services.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_ERROR_MESSAGE = "error_msg";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_credits);
user=PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("id", "");
totSpesa= (TextView)findViewById(R.id.tot_spesa);
home = (Button)findViewById(R.id.home_btn);
home.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.home_btn:
Intent i = new Intent(Credits.this, MainActivity.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptCredits extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Credits.this);
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
//Intent in = getIntent();
//user = in.getStringExtra("id");
String tot_spesa="";
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", "get_credits"));
params.add(new BasicNameValuePair("username", user));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
URL, "POST", params);
tot_spesa=json.getString("tot_spesa");
} catch (JSONException e) {
e.printStackTrace();
}
return tot_spesa;
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String tot_spesa) {
totSpesa.setText(tot_spesa);
}
}
}
Maybe I'm missing something but I don't think you're actually launching your AsyncTask.
Try to do :
new AttemptCredits().execute(user);
In onCreate,
and get your user in doInBackground with
user = args[1];
Related
I have created a custom AsyncTask class named ConnectionHttp. Which have to return a Json String, when called by a button in the main activity (test1.java). Everything is okay for the connection and I can get the string.
The point is that I want to display a ProgressDialog on the main activity while the background task is runing but it does not work. i don't see any ProgressDialog.
1) How can i fix the progressDialog
2) How can i solve the problem in logs (the application may be doing too much work ...) (I'm testing on a real device)
Here is my code :
test1.java (main activity)
public class test1 {
public static final String URL = ".....";
private ProgressDialog pDialog;
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test1);
pDialog = new ProgressDialog(test1.this);
tv = (TextView)findViewById(R.id.tvTest);
Button btRun = (Button) findViewById(R.id.btTestRun);
btRun.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
ConnectionHttp conn = new ConnectionHttp(test1.this, pDialog, URL);
String str = conn.execute().get();
tv.setText(str);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
}
ConnectionHttp.java
public class ConnectionHttp extends AsyncTask
{
private ProgressDialog pDialog;
private Context context;
private String LOGIN_URL;
private JSONParser jsonParser;
// TAGS
private final String TAG_SUCCESS = "success";
private final String TAG_MESSAGE = "message";
private final String TAG_VALUES = "values";
public ConnectionHttp(Context context, ProgressDialog pDialog, String url) {
this.context = context;
this.pDialog = pDialog;
this.LOGIN_URL = url;
this.jsonParser = new JSONParser();
}
#Override
public void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Connexion au serveur distant...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
public String doInBackground(String... args) {
// TODO Auto-generated method stub
int success;
String values = "";
try {
List<NameValuePair> params = new ArrayList<>();
// adding parameters
// ...
params.add(.....);
//
Log.d("request #1", "starting");
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
// success tag for json
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("request #1", "Successfull");
values = json.getString(TAG_VALUES);
return json.getString(TAG_MESSAGE);
}else{
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return values;
}
public void onPostExecute(String message) {
Log.d("request #1", "done.");
pDialog.setMessage("done.");
pDialog.dismiss();
}
Android logs
D/request #1﹕ starting
D/request #1 : Successfull !
I/Choreographer﹕ Skipped 49 frames! The application may be doing too much work on its main thread.
D/request #1﹕ done
Dont pass progress dialog to the Async class. Instead create it on the Async class.
Modify onPreExecute to this
#Override
public void onPreExecute() {
super.onPreExecute();
pdialog = new ProgressDialog(getActivity(),"","Connexion au serveur distant...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
Delete progress dialog from test1.java
first remove your progress dialog from AsyncTask and use your passed context to create ProgressDialog;
public ConnectionHttp(Context context, ProgressDialog pDialog, String url) {
this.context = context;
this.pDialog = new ProgressDialog(context);
this.LOGIN_URL = url;
this.jsonParser = new JSONParser();
}
In my application I used autocompletetextview to retrieve data,the data which I display is using json,now autocompletetextview works well,but what I want is after getting name in my autocompletetextview I want to send id of category,but it sends name..following is my response..and my snippet code is here..Autocompletetextview not working
{
"category":
[
{
"id":"4",
"name":"cat1"
},
{
"id":"7",
"name":"aditya"}
]
}
Add_Catagory.java
public class MainActivity extends Activity {
private Button btns;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private MultiAutoCompleteTextView acTextView;
private static final String FEEDBACK_URL = "";
private static final String FEEDBACK_SUCCESS = "status";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
acTextView = (MultiAutoCompleteTextView) findViewById(R.id.autoComplete);
acTextView.setAdapter(new SuggestionAdapter(this,acTextView.getText().toString()));
acTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
/* JsonParse jp=new JsonParse();
List<SuggestGetSet> list =jp.getParseJsonWCF(acTextView.getText().toString());
list.get(0).getId();*/
btns=(Button)findViewById(R.id.btn);
btns.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AttemptLogin().execute();
}
});
}
class AttemptLogin extends AsyncTask<String, String, String> {
boolean failure = false;
private String catid;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Sending..");
pDialog.setIndeterminate(true);
// pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("unused")
#Override
protected String doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String pweighttype=acTextView.getText().toString();
try {
JsonParse jp=new JsonParse();
List<NameValuePair> params = new ArrayList<NameValuePair>();
List<SuggestGetSet> list =jp.getParseJsonWCF(acTextView.getText().toString());
for(int i = 0;i<list.size();i++){
if(list.get(i).getName().equals(acTextView.getText().toString()))
params.add(new BasicNameValuePair("parentid",list.get(i).getId()));
System.out.println("Su gayu server ma"+params);
catid=list.get(i).getId().toString();
}
System.out.println("Su catid"+catid);
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest (
FEEDBACK_URL, "POST", params);
//check your log for json response
Log.d("Login attempt", json.toString());
JSONObject jobj = new JSONObject(json.toString());
final String msg = jobj.getString("msg");
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
}
});
return json.getString(FEEDBACK_SUCCESS);
}catch (JSONException e) {
e.printStackTrace();
}
return null;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url) {
//dismiss the dialog once product deleted
pDialog.dismiss();
//parentcat.getText().clear();
}}
try this//modify doInBackground
try {
JsonParse jp=new JsonParse();
List<NameValuePair> params = new ArrayList<NameValuePair>();
List<SuggestGetSet> list =jp.getParseJsonWCF(acTextView.getText().toString());
for(int i = 0;i<list.length();i++){
if(list.get(i).getName().equals(acTextView.getText().toString()))
params.add(new BasicNameValuePair("parentid",list.get(i).getId()));
break;
}
I did log in using Facebook account by importing Facebook sdk as library in my android app but the main problem is i want to go to another activity when i do log in with Facebook account i am not understanding how to do this.
LoginActivity.java :
public class LoginActivity extends FragmentActivity {
private ProgressDialog pDialog;
Button btn_login,bnt_Register ;
EditText edt_email,edt_password;
JSONParser jsonParser = new JSONParser();
private static String url_create_product = "http://192.168.1.6/laravel/public/user";
private static final String TAG_SUCCESS = "success";
//private static final String TAG_PORTFOLIOS = "lists";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
bnt_Register=(Button)findViewById(R.id.btnRegister);
btn_login =(Button)findViewById(R.id.btnLogin);
edt_email = (EditText)findViewById(R.id.loginEmail);
edt_password=(EditText)findViewById(R.id.loginPassword);
bnt_Register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in = new Intent(LoginActivity.this,AccountRegister.class);
startActivity(in);
}
});
btn_login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new EmailPassword().execute();
}
});
}
class EmailPassword extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String email =edt_email.getText().toString();
String password =edt_password.getText().toString();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("email", email));
params1.add(new BasicNameValuePair("password", password));
try{
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params1);
Log.d("Create Response", json.toString());
return json.toString();
}catch(Exception e){}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
try {
JSONObject json = new JSONObject(file_url);
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
//Toast.makeText(getApplicationContext(),"Login", Toast.LENGTH_LONG).show();
// closing this screen
//finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
}
#Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
}
}
you should do that in onPostExecute method. set a flag for response for example set a boolean to true if login was successful and start your other activity in onPostExecute method if flag == true .
change your Post execute method:
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
Intent in = new Intent(LoginActivity.this,YourActivity.class);
startActivity(in);
}
I want to use webservice to get data from after click on my button(button1)unfortunatly stopped I'm using json my debugger is not coming onclick view and my json is not giving response.
JSONParser jsonParser = new JSONParser();
private static final String about = "about";
private static String url = "http://www.mydomain/staticinfo";
private static final String TAG_SUCCESS = "id";
private static final String TAG_SUCCESS1="success";
#SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public void action(View v)
{
if(v.getId()==R.id.button1)
new aboutAccess().execute();
else
Toast.makeText(this, "This is demo for smlsolution", Toast.LENGTH_LONG).show();
}
class aboutAccess extends AsyncTask<String, String, String>{
private String id;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
//String url = "http://10.0.2.2/about.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
String ID="1";
params.add(new BasicNameValuePair("id ","ID"));
JSONObject json = jsonParser.makeHttpRequest(url,"POST", params);
Log.d("Create Response", json.toString());
try{
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
flag=0;
String abt=json.getString(about);
Intent i = new Intent(getApplicationContext(),About.class);
i.putExtra("about", abt);
startActivity(i);
}
else{
flag=1;
}
}
catch (JSONException e){
e.printStackTrace();
System.out.println(e.toString());
}
// TODO Auto-generated method stub
return null;
}
protected void onPostExecute(String file_url){
pDialog.dismiss();
if(flag==1)
Toast.makeText(MainActivity.this,"Data Not Found", Toast.LENGTH_LONG).show();
}
}
Your app is crashing because you are doing Activity switching operations in the doInBackground(). Change the following piece of code from doInBackground() to onPostExecute(),
Intent i = new Intent(getApplicationContext(),AboutUs.class);
startActivity(i);
finish();
Do something like below,
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if(flag==1)
Toast.makeText(MainActivity.this,"Please Enter Correct informations",Toast.LENGTH_LONG).show();
else{
Intent i = new Intent(getApplicationContext(),AboutUs.class);
startActivity(i);
finish();
}
}
I am trying to create an activity that allows a user to login by checking the username and password from a database, however after the creadentials are fetched successfully, the doInbackground doesnt stop executing.I not sure what i can do to make the onpostexecute to run. Here is the code
public class LoginActivity extends Activity{
public String username;
public String password;
public String userid;
JSONParser jParser = new JSONParser();
JSONObject json;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
context=getApplicationContext();
setContentView(R.layout.activity_login);
Button loginbutton=(Button) findViewById(R.id.loginbutton);
final EditText usernameText=(EditText) findViewById(R.id.usernameInput);
final EditText passwordText=(EditText) findViewById(R.id.passwordInput);
loginbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
username=usernameText.getText().toString();
password=passwordText.getText().toString();
if(username.trim().length()==0 || password.trim().length()==0){
AlertDialogManager diag=new AlertDialogManager();
diag.showAlertDialog(getApplicationContext(), "Fill Fields", "enter a username and password", false);
}else{
//send the username and password for verification
new Login().execute();
}
}
});
}
//http class starts here.
class Login extends AsyncTask<String, String, String> {
InputStream is = null;
JSONObject jObj = null;
ProgressDialog pDialog;
static final String url = "http://10.0.2.2/newptk/dalvik/auth.php";
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Authenticating...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
Log.e("Auth", "working");
JSONArray document = null;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
json = jParser.makeHttpRequest(url, "POST", params);
return null;
}
protected void onPostExecute() {
pDialog.dismiss();
SessionManager smg=new SessionManager(getApplicationContext());
int flag = 0;
try {
flag = json.getInt("success");
if(flag==1){
userid=json.getString("userid");
//set the session
smg.createLoginSession(username, userid);
//Login the user
Intent i = new Intent(getApplicationContext(), ReportFound.class);
startActivity(i);
finish();
}else{
AlertDialogManager diag=new AlertDialogManager();
diag.showAlertDialog(LoginActivity.this, "Login", "Incorrect Username/password", false);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}//end of http class
}
The first thing I see is that you are telling onPostExecute() to accept a String in your class header
class Login extends AsyncTask<String, String, String>
but aren't accepting anything or passing anything to it
protected void onPostExecute() {
if you don't want to pass it anything then change it to
class Login extends AsyncTask<Void, Void, Void>
and
protected void onPostExecute(Void result) {
...
}
#Override
protected void doInBackground(String... arg0) {
Notice this section in the Docs
The three types used by an asynchronous task are the following:
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the
background computation.
Result, the type of the result of the
background computation.
Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
Change
protected void onPostExecute()
to
protected void onPostExecute(String result)
and you should be golden. Consider adding #Override tags in your code to prevent these subtle bugs in the future.