I have a problem i need the token to transfer it to my SessionManagement class to compare it with the saved token , but in my onCreate it's always null ,i need a workaround to make my token not null in oncreate
please help.
here is my code
private static final String LOGIN_URL = "http://baymd.myterranet.com/api/auth";
private static final String TAG_SUCCESS = "code";
private static final String TAG_MESSAGE = "message";
private static final String TAG_DATA = "data";
private static final String TAG_TOKEN = "access_token";
JSONParser jsonParser = new JSONParser();
private EditText user, pass;
private Button mSubmit;
private ProgressDialog pDialog;
private String token, none,SavedToken;
SesionManagement session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
session=new SesionManagement(getApplicationContext());
HashMap<String, String> tokens = session.getUserDetails();
SavedToken = tokens.get(session.KEY_NAME);
if(token==null) {//This line
Log.d("TOKEN ====== ", "NULLL");
}
session.checkLogin(token, SavedToken);
user = (EditText) findViewById(R.id.inputEmail);
pass = (EditText) findViewById(R.id.inputPass);
mSubmit = (Button) findViewById(R.id.loginBtn);
mSubmit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new AttemptLogin().execute();
}
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) {
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params, none);
success = json.getInt(TAG_SUCCESS);
if (success == 200) {
JSONObject c = json.getJSONObject(TAG_DATA);
token = c.getString(TAG_TOKEN);//The token wich is null in oncreate
Intent i = new Intent(Login.this, NavDraver.class);
i.putExtra("cjson", c.toString());
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
json.getString(TAG_MESSAGE);
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
session.createLoginSession(token);
Log.d("SAVED TOKEN",SavedToken);
pDialog.dismiss();
}
}
}
Try this:
token = c.optString(TAG_TOKEN, yourDefaultValueHere);
if(token == null){
token = ""; // or whatever you want to init here
}
Hope it helps.
Related
This question already has answers here:
Method getText() must be called from the UI Thread (Android Studio)
(5 answers)
Closed 6 years ago.
I'm making the register in Android Studio, and I found a problem on
String name = names. getText (). toString ();
String address = address. getText (). toString ();
String telephone = telephone. getText (). toString ();
String username = user. getText (). toString ();
String password = pass. getText (). toString ();,
Possible solutions?
Here is my Activity code:
public class ActivityRegister extends Activity implements View.OnClickListener {
private EditText user, pass, nama, alamat, telpon;
private TextView t1;
private RadioButton rb1, rb2;
private Button mRegister;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://10.0.2.2/coba/api/register.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header)));
bar.setTitle("Register Distro App");
nama = (EditText) findViewById(R.id.nama);
alamat = (EditText) findViewById(R.id.alamat);
telpon = (EditText) findViewById(R.id.telpon);
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
rb1=(RadioButton)findViewById(R.id.option1);
rb2=(RadioButton)findViewById(R.id.option2);
t1=(TextView)findViewById(R.id.TextView01);
mRegister = (Button)findViewById(R.id.register);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ActivityRegister.this);
pDialog.setMessage("Mendaftar Member...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
int success;
String namanya = nama.getText().toString();
String alamatnya = alamat.getText().toString();
String telponnya = telpon.getText().toString();
String username = user.getText().toString();
String password = pass.getText().toString();
if(rb1.isChecked() == true)
t1.setText(rb1.getText());
if(rb2.isChecked() == true)
t1.setText(rb2.getText());
if(rb1.isChecked() == false && rb2.isChecked() == false)
t1.setText("");
String jenkel = t1.getText().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("nama", namanya));
params.add(new BasicNameValuePair("alamat", alamatnya));
params.add(new BasicNameValuePair("telpon", telponnya));
params.add(new BasicNameValuePair("jenkel", jenkel));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
Log.d("Register attempt", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Register Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if (file_url != null){
Toast.makeText(ActivityRegister.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
The reason is in AsyncTask behavior.
Methods onPreExecute(), onPostExecute are called from UI Thread.
But doInBackground() is called in separate thread.
The solution is to pass text parameters to AsyncTask#execute.
See: AsyncTask tutorial
You have a background thread but when you access UI components you have to access them through the man UI thread. You can do this by
youActivity.runOnUiThread(new Runnable() {
public void run() {
t1.setText(rb1.getText());
}
});
Error shows: FATAL EXCEPTION: AsyncTask #1
public class NewProductActivity extends Activity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
private static String url_create_product = "http://127.0.0.1/android_connect/create_product.php";
private static final String TAG_SUCCESS = "success";
static List<String> citations = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
class CreateNewProduct extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
finish();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
Move in your onPostExecute(....)
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
finish();
Never call finish(); or Intent in doInBackground(....)
My code is working in Android Emulator. I can connect to database from localhost...
But when I run in my Android Device. The app isn't run well..
Can you give reference for connect database from localhost to Android Device ? I have searched in Google, but I don't get it.
public class Login extends Activity implements View.OnTouchListener {
EditText usernameInput, passwordInput;
Button loginButton;
String username, password;
ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
TextView createAccountLink;
private static String login_url = "http://10.0.2.2/ujian_online/login.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
ArrayList<HashMap<String, String>> arraylist;
JSONArray products = null;
String image_link;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
usernameInput = (EditText) findViewById(R.id.username);
passwordInput = (EditText) findViewById(R.id.password);
loginButton = (Button) findViewById(R.id.login_button);
jsonParser = new JSONParser();
createAccountLink = (TextView) findViewById(R.id.createAccountLabel);
createAccountLink.setOnTouchListener(this);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new CheckAccounts().execute();
}
});
//HANCURIN SESSION
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if(v.getId() == R.id.createAccountLabel) {
Intent i = new Intent(getApplicationContext(), Registration.class);
startActivity(i);
finish();
}
return true;
}
public class CheckAccounts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("System checks your account.....");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
username = usernameInput.getText().toString();
password = passwordInput.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.makeHttpRequest(login_url, "POST", params);
try {
int success = json.getInt("success");
Log.d("SUKSES", String.valueOf(success));
int id = 0;
if (success == 1) {
products = json.getJSONArray(TAG_PRODUCTS);
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
id = c.getInt("id");
}
new SessionManagement(getApplicationContext()).putInteger("ID", id);
Intent i = new Intent(getApplicationContext(), MainMenu.class);
startActivity(i);
finish();
} else {
pDialog.setMessage("Your username or password is wrong");
pDialog.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
Your are using 10.0.2.2 which is a special url for emulator ONLY to point to the machine localhost. For real devices use actual ip address of the machine and be on same network.
The url you are using should only be used in emulators.
Use it like this
private static String login_url = "http://real_ip_of_your_machine/ujian_online/login.php";
Get the ip of your maching using ipconfig(Windows) or ifconfig (Linux/Mac). Also, your machine and the device should be on same network.
i am trying to make get a json value to display on another class but it is returning a null value and i am trying to save it using sharedpreferences and it is not working . i want to get editor.putString("username", username); display the username on the next class which is menu . and it is displaying anon
public class MainActivity extends Activity {
Button login,signin,reg,forr;
private EditText user,pass;
private ProgressDialog pDialog;
int flag=0;
JSONParser jsonParser = new JSONParser();
private static String LOGIN_URL = "http://10.0.2.2/wordtinss/login.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String DAIRY = "dairy";
public static final String PREFS_NAME = "LoginPrefs";
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login=(Button)findViewById(R.id.login);
user=(EditText)findViewById(R.id.username);
pass=(EditText)findViewById(R.id.password);
reg=(Button) findViewById(R.id.reg);
forr=(Button) findViewById(R.id.forg);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getString("logged", "").toString().equals("logged")) {
Intent intent = new Intent(MainActivity.this, Menu.class);
startActivity(intent);
}
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Register.class);
finish();
startActivity(i);
}
//Close code that check online details
});
//Close log in
forr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Forget.class);
finish();
startActivity(i);
}
//Close code that check online details
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Check all fields
if(user.length()<1 || pass.length()<1)
{
Toast.makeText(MainActivity.this,"Please Enter both username and password", Toast.LENGTH_LONG).show();
return;
}
//check connectivity
if(!isOnline(MainActivity.this))
{
Toast.makeText(MainActivity.this,"No network connection", Toast.LENGTH_LONG).show();
return;
}
//from login.java
new loginAccess().execute();
}
//code to check online details
private boolean isOnline(Context mContext) {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
{
return true;
}
return false;
}
//Close code that check online details
});
//Close log in
}
class loginAccess extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// 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());
// Clear all previous data in database
String dar=json.getString(DAIRY);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("logged", "logged");
editor.putString("username", username);
editor.putString("dairy", dar);
editor.commit();
Intent i = new Intent(getApplicationContext(),Menu.class);
finish();
startActivity(i);
// Close all views before launching Dashboard
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if(flag==1)
Toast.makeText(MainActivity.this,"Please Enter Correct informations", Toast.LENGTH_LONG).show();
}
}
}
public class Menu extends Activity {
private List<list> myCars = new ArrayList<list>();
int flag=0;
String namee ,dar;
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
private static String LOGIN_URL = "http://10.0.2.2/wordtinss/login.php";
private static final String dairy= "dairy";
private static final String TAG_MESSAGE = "message";
public static final String PREFS_NAME = "LoginPrefs";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
populateCarlist();
populateListView();
registerclick();
SharedPreferences un = PreferenceManager.getDefaultSharedPreferences(Menu.this);
namee = un.getString("username", "anon");
TextView usern= (TextView) findViewById(R.id.usern);
usern.setText(namee);
}
}
Use:
namee = getSharedPreferences(PREFS_NAME , Context.MODE_PRIVATE).getString("username", "anon");
instead. Because I think you're using different preference files.
i want to pass my id into another activity. can you show me how? i try search in google but nothing can help me. i hope that you can help me a little. i must be great if you can help me. i'm stuck with this problem for 3 days. makes me confused.
this is my code for pass :
private ProgressDialog mProgressDialog;
private static final String TAG_SUCCESS = "success";
JSONParser jsonParser = new JSONParser();
EditText inputfirstname,
inputmiddlename,
inputlastname,
inputaliasname,
inputcitybirth,
inputyearbirth;
RadioGroup gender;
RadioButton mr,mrs;
private static final String TAG_ID = "ID_Person";
private static String url_create_person ="http://172.18.0.20/person_new_xml.php";
private Spinner date,month,year;
Button saveperson,cancelperson;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.newperson);
inputfirstname = (EditText) findViewById(R.id.newfirstname);
inputmiddlename = (EditText) findViewById(R.id.newmiddlename);
inputlastname = (EditText) findViewById(R.id.newlastname);
inputaliasname = (EditText) findViewById(R.id.newaliasname);
gender = (RadioGroup)findViewById(R.id.jekel);
inputcitybirth = (EditText) findViewById(R.id.newcitybirth);
date = (Spinner) findViewById(R.id.spinnerdate);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource
(this, R.array.date_array, android.R.layout.simple_spinner_dropdown_item);
date.setAdapter(adapter);
month = (Spinner) findViewById(R.id.spinnermonth);
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource
(this, R.array.month_array, android.R.layout.simple_spinner_dropdown_item);
month.setAdapter(adapter2);
year = (Spinner) findViewById(R.id.spinneryear);
ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource
(this, R.array.year_array, android.R.layout.simple_spinner_dropdown_item);
year.setAdapter(adapter3);
cancelperson = (Button) findViewById(R.id.btncancelnewperson);
saveperson = (Button) findViewById(R.id.btnsnextnewperson);
saveperson.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreatePerson().execute();
}
});
}
private class CreatePerson extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Creating Product..");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
String select = null;
switch (gender.getCheckedRadioButtonId())
{
case R.id.mr:
select="Mr.";
break;
case R.id.mrs:
select="Mrs.";
default:
break;
}
String firstname = inputfirstname.getText().toString();
String middlename = inputmiddlename.getText().toString();
String lastname = inputlastname.getText().toString();
String aliasname = inputaliasname.getText().toString();
String city = inputcitybirth.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("FirstName", firstname));
params.add(new BasicNameValuePair("MiddleName", middlename));
params.add(new BasicNameValuePair("LastName", lastname));
params.add(new BasicNameValuePair("AliasName", aliasname));
params.add(new BasicNameValuePair("Gender", select));
params.add(new BasicNameValuePair("CityBirth", city));
params.add(new BasicNameValuePair("DateBirth", date.getSelectedItem().toString()));
params.add(new BasicNameValuePair("MonthBirth", month.getSelectedItem().toString()));
params.add(new BasicNameValuePair("YearBirth", year.getSelectedItem().toString()));
JSONObject json = jsonParser.makeHttpRequest(url_create_person, "POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
String id = ((Button) findViewById(R.id.btnsnextnewperson)).getText().toString();
Intent i = new Intent(getApplicationContext(),CreateUser.class);
i.putExtra(TAG_ID, id);
startActivity(i);
finish();
} else {
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
mProgressDialog.dismiss();
}
}
}
and this is my code for receive :
private ProgressDialog mProgressDialog;
private static final String TAG_SUCCESS = "success";
JSONParser jsonParser = new JSONParser();
String ID;
//String Name;
private static final String TAG_Person = "person";
private static final String TAG_ID = "ID_Person";
TextView id;
EditText inputuser,inputpassword,inputanswer;
private Spinner question;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.registeruser);
ID = getIntent().getStringExtra(TAG_ID);
id =(TextView) findViewById(R.id.textname);
inputuser = (EditText) findViewById(R.id.inputuser);
inputpassword = (EditText) findViewById(R.id.inputpassword);
inputanswer = (EditText) findViewById(R.id.inputanswer);
question = (Spinner) findViewById(R.id.questionspinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource
(this, R.array.securityquestion, android.R.layout.simple_spinner_dropdown_item);
question.setAdapter(adapter);
new User().execute();
save = (Button) findViewById(R.id.savebutton);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Createuser().execute();
}
});
}
private class User extends AsyncTask<String, String, JSONArray>{
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(CreateUser.this);
mProgressDialog.setMessage("Loading products. Please wait...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected JSONArray doInBackground(String... param) {
// TODO Auto-generated method stub
JSONArray personobj = new JSONArray();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("ID_Person", ID));
String url_product_detials = "http://172.18.0.20/get.php";
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
Log.d("Single Person Details", json.toString());
personobj = json.getJSONArray(TAG_Person);
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
return personobj;
}
protected void onPostExecute(JSONArray personobj){
mProgressDialog.dismiss();
try {
for (int i = 0; i < personobj.length(); i++) {
JSONObject person;
person = personobj.getJSONObject(i);
String Id = person.getString("ID_Person");
id.setText(Id);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I will recommend to call the intent in onPostExecute of AsyncTask. Also store the text of the button in a string before going into doInBackground. The doInBackground is a seperate thread and can't communicate with Main UI Thread.
as berserk said,the doInBackground is a seperate thread that cant communicate with main UI Thread,so, as my recommedn,you should startActivity() in the onPostExecute.
just change to below
private class CreatePerson extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Creating Product..");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
//String select = null;//member var of outside class
switch (gender.getCheckedRadioButtonId())
{
case R.id.mr:
select="Mr.";
break;
case R.id.mrs:
select="Mrs.";
default:
break;
}
String firstname = inputfirstname.getText().toString();
String middlename = inputmiddlename.getText().toString();
String lastname = inputlastname.getText().toString();
String aliasname = inputaliasname.getText().toString();
String city = inputcitybirth.getText().toString();
//List<NameValuePair> params = new ArrayList<NameValuePair>();//member var of outside class
params.add(new BasicNameValuePair("FirstName", firstname));
params.add(new BasicNameValuePair("MiddleName", middlename));
params.add(new BasicNameValuePair("LastName", lastname));
params.add(new BasicNameValuePair("AliasName", aliasname));
params.add(new BasicNameValuePair("Gender", select));
params.add(new BasicNameValuePair("CityBirth", city));
params.add(new BasicNameValuePair("DateBirth", date.getSelectedItem().toString()));
params.add(new BasicNameValuePair("MonthBirth", month.getSelectedItem().toString()));
params.add(new BasicNameValuePair("YearBirth", year.getSelectedItem().toString()));
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// JSONObject json = null//member var of outside class
json = jsonParser.makeHttpRequest(url_create_person, "POST", params);
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
if(mProgressDialog != null && mProgressDialog.isShow()){
mProgressDialog.dismiss();
}
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
String id = ((Button) findViewById(R.id.btnsnextnewperson)).getText().toString();
Intent i = new Intent(getApplicationContext(),CreateUser.class);
i.putExtra(TAG_ID, id);
startActivity(i);
finish();
} else {
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}