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();
}
}
Related
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];
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);
}
This is my logcat
12-08 14:45:21.179: D/request!(6046): starting
12-08 14:45:21.719: D/Login attempt(6046): {"message":"Login successful!","success":1}
This is my Login.java
public class Login extends ActionBarActivity implements OnClickListener {
private Button login,register;
private EditText email,password;
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://192.168.1.14:1234/PMSS/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (Button) findViewById(R.id.login);
register = (Button) findViewById(R.id.registerlauncher);
email = (EditText) findViewById(R.id.userid);
password = (EditText) findViewById(R.id.password);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String Username = email.getText().toString();
String Password = password.getText().toString();
new AttemptLogin(Username,Password).execute();
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Login.this, Register.class);
startActivity(intent);
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// For the main activity, make sure the app icon in the action bar
// does not behave as a button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
/*case R.id.login:
new AttemptLogin().execute();
break;
case R.id.register:
Intent i = new Intent(Login.this, Register.class);
startActivity(i);
break;
*/
default:
break;
}
}
//AsyncTask is a seperate thread than the thread that runs the GUI
//Any type of networking should be done with asynctask.
class AttemptLogin extends AsyncTask<String, String, String> {
//three methods get called, first preExecture, then do in background, and once do
//in back ground is completed, the onPost execture method will be called.
boolean failure = false;
String res;
String Username;
String Password;
int success;
public AttemptLogin(String Username, String Password) {
this.Username = Username;
this.Password = Password;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", Username));
params.add(new BasicNameValuePair("password", Password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
System.out.print("Here");
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
res = json.getString(TAG_MESSAGE);
return res;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(int success) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (success == 1) {
Log.d("Login Successful!", res);
Intent i = new Intent(Login.this, MainMenu.class);
startActivity(i);
Toast.makeText(Login.this, res, Toast.LENGTH_LONG).show();
}else{
Log.d("Login Failure!", res);
Toast.makeText(Login.this, res, Toast.LENGTH_LONG).show();
}
}
}
}
As the logcat said I login succesfully but in my android phone still having the Attemping Login... and it will not go to my MainMenu interface. There is no compilation and runtime errors. I was wonder Intent i = new Intent(Login.this,MainMenu.class); and startActivity(i); does not work?
You should return success instead of res from your doInBackground. There is also something wrong with the types (arguments, return) of the various methods in AsyncTask. The return type of doInBackground should be the same as the argument type of onPostExecute.
Change your code like this:
class AttemptLogin extends AsyncTask<String, String, Integer> {
...
protected Integer doInBackground(String... args) {
...
return success;
}
protected void onPostExecute(Integer success) {
...
}
}
public class Login extends Activity implements OnClickListener {
private EditText user, pass;
private Button mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://192.168.2.4/mybringbacktutorial/login.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// setup input fields
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
// setup buttons
mSubmit = (Button) findViewById(R.id.login);
mRegister = (Button) findViewById(R.id.register);
// register listeners
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.register:
Intent i = new Intent(this, Register.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
// save user data
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = sp.edit();
edit.putString("username", username);
edit.commit();
Intent i = new Intent(Login.this, ReadComments.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
Guys how to create user session here in this code? i want ReadComments.class to have a logout button and when user press the back button the session of the log in user will not be destroy, also when application is close, if the app. is open again the user has the his log in still there.
In your doInBackground of AttemptLogin class try to add pDialog.dismiss(); before you call finish() when if (success == 1)
in your onDestory() check whether the dialog is showing or not if showing dismiss it like this..
#Override
protected void onDestroy() {
if (pDialog != null) {
if (pDialog.isShowing()) {
pDialog.dismiss();
pDialog = null;
}
}
super.onDestroy();
}