How to send id with json request? - android

I have two things in my project first is login page which extended with Activity and to check username and password I am using following json {"status":"success","msg":"Your are now Login Successfully","user_login_id":2650}.
Now second thing is I am using navigation drawer which is extended with Activity and it uses different Fragment file,now after user log in successfully first fragment will display in which I want to parse some data in List view and for that I am using following json {"matching":[{"name":"Dynamic Street","profile_id":"","image":"path"}]}.So the problem is I need to use user login id 2650 to parse data in List view and want to send it with request in my http URL.
public class LoginPage extends Activity implements OnClickListener{
private Button btn;
private EditText user;
private EditText pass;
// Progress Dialog
private ProgressDialog pDialog;
//JSON parser class
JSONParser jsonParser = new JSONParser();
private Button btn1;
private static final String LOGIN_URL = "http://XXXXX/login";
private static final String TAG_SUCCESS = "status";
private static final String TAG_LOGIN = "login";
private static final String TAG_USERID="user_login_id";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_page);
user=(EditText)findViewById(R.id.loginmailid);
pass=(EditText)findViewById(R.id.loginpwd);
btn=(Button)findViewById(R.id.login);
btn1=(Button)findViewById(R.id.btnreg);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.btnreg:
Intent i = new Intent(this, RegistrationForm.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginPage.this);
pDialog.setMessage("Login..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("unused")
#Override
protected String doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String username = user.getText().toString();
String password = pass.getText().toString();
try {
//Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("version", "apps"));
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());
JSONObject jobj = new JSONObject(json.toString());
final String msg = jobj.getString("msg");
System.out.println("MSG : " + msg);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
return json.getString(TAG_SUCCESS);
//System.out.println(arr.toString());
//JSONObject arr1 = new JSONObject(json);
//String ss=arr1.getString("status");
//System.out.println(ss);
//System.out.println(arr1.getString("status"));
//String date = jObj.getString("status");
// json success tag
// success = json.getInt(TAG_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();
if(file_url.equals("success")) {
// Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginPage.this, MainActivity.class);
i.putExtra("user_login_id", TAG_USERID);
startActivity(i);
}else{
//Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
}}
}
for fragment class check this https://stackoverflow.com/questions/26816016/how-to-parse-json-data-from-server-using-fragment

You can send the LOGIN_ID value from Activity as:
Bundle bundle = new Bundle();
bundle.putString("LOGIN_ID", value);
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment get value in onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("LOGIN_ID");
return inflater.inflate(R.layout.fragment, container, false);
}
Edit :
Remove return line, check this code :
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String strtext = getArguments().getString("LOGIN_ID");
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
aList = new ArrayList<HashMap<String,String>>();
new LoadAlbums().execute();
return rootView;
}

You dont need NameValuePairs. remove below lines.
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("version", "apps"));
create another object.
JsonObject request = new JsonObject();
request.put("email", username));
request.put("password", password));
request.put("version", "apps"));
You can also add ID in it request.put("ID", ID_VALUE));
ask server developer format of request he will let you know exact format he is parsing on server.

change the code,
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginPage.this);
pDialog.setMessage("Login..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("unused")
#Override
protected JsonObject doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String username = user.getText().toString();
String password = pass.getText().toString();
try {
//Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("version", "apps"));
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());
JSONObject jobj = new JSONObject(json.toString());
final String msg = jobj.getString("msg");
System.out.println("MSG : " + msg);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
return jobj;
//System.out.println(arr.toString());
//JSONObject arr1 = new JSONObject(json);
//String ss=arr1.getString("status");
//System.out.println(ss);
//System.out.println(arr1.getString("status"));
//String date = jObj.getString("status");
// json success tag
// success = json.getInt(TAG_SUCCESS);
}catch (JSONException e) {
e.printStackTrace();
}
return null;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(JsonObject file_url) {
//dismiss the dialog once product deleted
pDialog.dismiss();
if(jobj.getString("status").equals("success")) {
// Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginPage.this, MainActivity.class);
i.putExtra("user_login_id", jobj.getString("user_login_id"));
startActivity(i);
}else{
//Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
}}

class AttemptLogin extends AsyncTask<String, String, String> {
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginPage.this);
pDialog.setMessage("Login..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("unused")
#Override
protected String doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String username = user.getText().toString();
String password = pass.getText().toString();
try {
//Building Parameters
JSONObject object = new JSONObject();
object.put("email", username);
object.put("password", password);
object.put("version", "apps");
String dat = object.toString();
JSONObject object1 = new JSONObject();
object1.put("userAuthentication", object);
String dat1 = object1.toString();
httppost.setEntity(new StringEntity(dat1, HTTP.US_ASCII));
httppost.setHeader("Content-type", "application/json;" + HTTP.UTF_8);
HttpResponse response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
content));
String line;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = builder.toString();
}catch (JSONException e) {
e.printStackTrace();
}
return result;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url) {
//dismiss the dialog once product deleted
pDialog.dismiss();
if(result!=null) {
// Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginPage.this, MainActivity.class);
i.putExtra("user_login_id", TAG_USERID);
startActivity(i);
}else{
//Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
}}
}

Related

How to send id of autocompletetextview?

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;
}

How to add client side validation before execute asynctask?

Hello I am new to android,in my app I have Login page and it works fine with my response but I want to add something like this,if my user name and password edittext is blank and user click on login button it should show message instead of start async task.
public class LoginPage extends Activity implements OnClickListener{
private Button btn;
private EditText user;
private EditText pass;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
// Session Manager Class
SessionManager session;
// Progress Dialog
private ProgressDialog pDialog;
//JSON parser class
JSONParser jsonParser = new JSONParser();
private Button btn1;
private String userid;
private static final String LOGIN_URL = "xxxxx";
private static final String TAG_SUCCESS = "status";
private static final String TAG_LOGIN = "login";
private static String TAG_USERID="user_login_id";
private static final String TAG_SESSION="session";
String session_id="";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_page);
// Session Manager
session = new SessionManager(getApplicationContext());
user=(EditText)findViewById(R.id.loginmailid);
pass=(EditText)findViewById(R.id.loginpwd);
Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();
btn=(Button)findViewById(R.id.login);
btn1=(Button)findViewById(R.id.btnreg);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login:
if(user.equals(null) || pass.equals(null))
{
Toast.makeText(getApplicationContext(), "Enter Email and Password", Toast.LENGTH_SHORT).show();
}
else
{
new AttemptLogin().execute();
System.out.println("<<<<<<<<<<<<<<<<<<<<< Session ID : " + session_id);
session.createLoginSession(session_id);
System.out.println(session);
break;
}
case R.id.btnreg:
Intent i = new Intent(this, RegistrationForm.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask {
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginPage.this);
pDialog.setMessage("Login..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("unused")
#Override
protected String doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String username = user.getText().toString();
String password = pass.getText().toString();
try {
//Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("version", "apps"));
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());
JSONObject jobj = new JSONObject(json.toString());
final String msg = jobj.getString("msg");
session_id = jobj.getString("user_login_id");
System.out.println("Session ID : " + session_id);
System.out.println("MSG : " + msg);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
return json.getString(TAG_SUCCESS);
//JSONArray arr = json.getJSONArray("login");
//System.out.println(arr.toString());
//JSONObject arr1 = new JSONObject(json);
//String ss=arr1.getString("status");
//System.out.println(ss);
//System.out.println(arr1.getString("status"));
//String date = jObj.getString("status");
}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();
if(file_url.equals("success")) {
session.createLoginSession(session_id);
// Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginPage.this, MainActivity.class);
i.putExtra("id", session_id);
System.out.println("Session Id : >>>>>>>>>>>>>>>>" + session_id);
startActivity(i);
}else{
//Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
}}
}
try like this,
if(user.getText().toString().trim().length() > 0 && pass.getText().toString().trim().length() > 0)
{
new AttemptLogin().execute();
System.out.println("<<<<<<<<<<<<<<<<<<<<< Session ID : " + session_id);
session.createLoginSession(session_id);
System.out.println(session);
break;
}
else
{
Toast.makeText(getApplicationContext(), "Enter Email and Password", Toast.LENGTH_SHORT).show();
}
try it this way...
case R.id.login:
if(user.getText().toString().trim().length()==0 || pass.getText().toString().trim().length()==0)
{
Toast.makeText(getApplicationContext(), "Enter Email and Password", Toast.LENGTH_SHORT).show();
}
else
{
new AttemptLogin().execute();
System.out.println("<<<<<<<<<<<<<<<<<<<<< Session ID : " + session_id);
session.createLoginSession(session_id);
System.out.println(session);
break;
}

retrieve data using json in android

I need to display the result in android text view that I obtained by json result. I only get the success message when I run the app. I want to get the textview displayed.
Java Code:
JSONObject hay;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "////////////////////// "; // change to the webhost
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
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.activity_main);
//setup input fields
user = (EditText) findViewById(R.id.user);
txtFname = (TextView) findViewById(R.id.fname);
txtMname = (TextView) findViewById(R.id.lname);
txtLname = (TextView) findViewById(R.id.mname);
//setup buttons
get = (Button) findViewById(R.id.get);
//register listeners
get.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AttemptLogin().execute();
}
class AttemptLogin extends AsyncTask < String, String, String > {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempt 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();
try {
// Building Parameters
List < NameValuePair > params = new ArrayList < NameValuePair > ();
params.add(new BasicNameValuePair("username", username));
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());
//
//Intent i = new Intent(Login.this, MainActivity.class);
//finish();
//startActivity(i);
//finish();
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;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
try {
JSONObject json = null;
JSONObject hay = new JSONObject((Map) json);
JSONArray user = hay.getJSONArray("user");
JSONObject jb = user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");
// displaying all data in textview
txtFname.setText("Firstname: " + firstname);
txtMname.setText("Middle Name: " + middlename);
txtLname.setText("Last Name " + lastname);
} catch (Exception e) {
e.printStackTrace();
}
if (file_url != null) {
Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
PHP Code:
<?php
require('config.inc.php');
if (!empty($_POST)) {
//initial query
$query = "Select last_name, first_name, middle_initial FROM admin where username = :user";
$query_params = array(':user' => $_POST['username']);
//execute query
try {
$stmt = $db -> prepare($query);
$result = $stmt -> execute($query_params);
} catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt -> fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["user"] = array();
foreach($rows as $row) {
$user = array();
// $user["designation"] = $row["designation"];
$user["middlename"] = $row["middle_initial"];
$user["firstname"] = $row["first_name"];
$user["lastname"] = $row["last_name"];
//update our repsonse JSON data
array_push($response["user"], $user);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No user available!";
die(json_encode($response));
}
} else {}
?>
<form action="test.php" method="POST">
Username: <input type="text" name="username">
<input type="submit" value="Submit">
</form>
sorry can't comment but what you getting at post execute from background task is file_url as string which is your param at on post execute......i think if you are getting result all params like first name ,lastName etc then you needed to pass jsonObject at onpost Execute
so you can parse at onPostExecute...your jsonResult and display it in textbox
Problem is in you current code is
txtFname.setText("Firstname: " + firstname);
in which firstName is from
String firstname = jb.getString("firstname");
JSONObject jb= user.getJSONObject(0);
JSONArray user = hay.getJSONArray("user");
JSONObject hay = new JSONObject ((Map) json);
JSONObject json = null;
i have reversed it so you can find problem here json is null so here is problem and pls try logging at each point and let we know so we and you can have exact idea....or give us json format...
the problem is with your this code segment:
JSONObject json = null;
JSONObject hay = new JSONObject((Map) json);
JSONArray user = hay.getJSONArray("user");
JSONObject jb = user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");
here what you are doing is: making another JSONObject as
JSONObject json = null;
that is creating a variable with local scope, the local variable will have more priority than global, that you understood. actually you need the json which is created from doInBackgrounnd(). so pass the json from doInBackground to onPostExecute: it is simple,
change the statements:
return json.getString(TAG_MESSAGE); => return json;
return json.getString(TAG_MESSAGE); => return json;
also change the type of doInBackground to JSONObject and avoid making a new local JSONObject and trying to get datafrom that (bcz it is null you initialized with).
JSONObject json = null; //remove this
JSONObject hay = new JSONObject((Map) json); //remove this
JSONArray user = hay.getJSONArray("user"); // change hay to json
also change the
protected void onPostExecute(String file_url)// to protected void onPostExecute(JSONObject json)
EDIT 2
here is your changed code, let me know what you are getting if some errors.
//edited1
public static JSONObject json = null;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "////////////////////// "; // change to the webhost
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_USER = "user";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setup input fields
user = (EditText) findViewById(R.id.user);
txtFname = (TextView) findViewById(R.id.fname);
txtMname = (TextView) findViewById(R.id.lname);
txtLname = (TextView) findViewById(R.id.mname);
//setup buttons
get = (Button) findViewById(R.id.get);
//register listeners
get.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AttemptLogin().execute();
}
class AttemptLogin extends AsyncTask < String, String, String > {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempt 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();
try {
// Building Parameters
List < NameValuePair > params = new ArrayList < NameValuePair > ();
params.add(new BasicNameValuePair("username", username));
Log.d("request!", "starting");
// getting product details by making HTTP request
// edited2
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());
//
//Intent i = new Intent(Login.this, MainActivity.class);
//finish();
//startActivity(i);
//finish();
//edited3
return json.getString(TAG_MESSAGE);
//return json;
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
//edited4
return json.getString(TAG_MESSAGE);
//return json;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String message) {
// dismiss the dialog once product deleted
pDialog.dismiss();
try {
//JSONObject json = null;
//JSONObject hay = new JSONObject((Map) json);
JSONArray user = json.getJSONArray("user");
JSONObject jb = user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");
// displaying all data in textview
txtFname.setText("Firstname: " + firstname);
txtMname.setText("Middle Name: " + middlename);
txtLname.setText("Last Name " + lastname);
} catch (Exception e) {
e.printStackTrace();
}
if (file_url != null) {
Toast.makeText(MainActivity.this, json.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
}
}
did four changes in total: mentioned as edited# wherever I did. please fins them and make it in your file,

make a string from AsyncTask not null in onCreate

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.

Pass string with button into next activity

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();
}
}
}

Categories

Resources